Misconstrued Monomials There exists an equation, assuming n and x are positive,

that expresses the relationship between two monomials, one being a common misrepresentation of the other. Many people make the simple mistake of equating these (i.e. 3x^2 and (3x)^2).

Challenge

Given a positive integer, i, determine and return the solution n and x with the smallest sum as an array [n, x]. In the case of a tie, any solution set is acceptable.

Test Cases

62658722541234765
[15, 11]

202500
[4, 15]

524288
[8, 4]

33044255768277
[13, 9]

Mathematica, 61 bytes

Thanks to miles for saving 2 bytes, plus a whole bunch of bytes I counted for no reason!

Last@Select[{n,(#/n)^(1/n)}~Table~{n,2Log@#},IntegerQ@*Last]&

Computes a table of pairs {n,x}, where x = (i/n)^(1/n), using all possible values of n; keeps only those for which the corresponding x is an integer; then returns the pair with the largest value of n.

Here, "all possible values of n" ranges from 1 to 2*ln(i). This ignores the solution {n,x} = {i,1}, but that's okay since the solution {n,x} = {1,i} will suffice if it's the best choice. So x never needs to get smaller than 2, which means that n*2^n ≤ i, and all such n are less than 2*ln(i).

One can show using calculus that the pair {n,x} that minimizes their sum in this context is the same as the pair {n,x} with largest n (not counting {i,1}). That's why the initial Last is good enough to find the optimal pair.


Filesystem-sort my directory please Sometimes lexicographical sorting of strings may cut it, but when browsing the filesystem, you really need better sorting criteria than just ASCII indices all the time.

For this challenge, given a list of strings representing filenames and folders in a directory, do a filesystem sort, explained below:

Split every string into an array of alternating digits (0123456789) and non-digits. If the filename begins with digits, insert an empty string at the beginning of the array.
For each element in the array, if the element is a string, lexicographically sort all the strings by that element in all lowercase or uppercase. If the element is a number, sort by numerical order. If any files are tied, continue to the next element for more specific sorting criteria.

Here is an example, starting with strings that are initially sorted lexicographically:

Abcd.txt
Cat05.jpg
Meme00.jpeg
abc.txt
cat.png
cat02.jpg
cat1.jpeg
meme03-02.jpg
meme03-1.jpeg
meme04.jpg

After step 1, you'll get this:

"Abcd.txt"
"Cat", 5, ".jpg"
"Meme", 0, ".jpeg"
"abc.txt"
"cat.png"
"cat", 2, ".jpg"
"cat", 1, ".jpeg"
"meme", 3, "-", 2, ".jpg"
"meme", 3, "-", 1, ".jpeg"
"meme", 4, ".jpg"

After step 2, you'll get this:

abc.txt
Abcd.txt
cat1.jpeg
cat02.jpg
Cat05.jpg
cat.png
Meme00.jpeg
meme03-1.jpeg
meme03-02.jpg
meme04.jpg

Here are the rules:

You may not assume the list of input strings is sorted in any order
You may assume that the input strings only contain printable ASCII characters
You may assume that when the filenames are converted to all lowercase or all uppercase, there will be no duplicates (i.e., a case-insensitive filesystem)
Input and output may be specified via any approved default method
Standard loopholes apply

Here is an example implementation of the sorting algorithm if there is any confusion:

function sort(array) {
  function split(file) {
    return file.split(/(\D*)(\d*)/);
  }

  return array.sort((a, b) => {
    var c = split(a);
    var d = split(b);

    for (var i = 0; i < Math.min(c.length, d.length); i++) {
      var e = c[i].toLowerCase();
      var f = d[i].toLowerCase();

      if (e-f) {
        return e-f;
      }

      if (e.localeCompare(f) !== 0) {
        return e.localeCompare(f);
      }
    }

    return c.length - d.length;
  });
}

This is code-golf, so shortest answer wins!

Bean, 116 121 118 bytes

Hexdump:

00000000 26 55 cd a0 62 80 40 a0 6f 53 d0 80 d3 d0 80 a0  &UÍ b.@ oSÐ.ÓÐ.
00000010 6f 20 80 0d 21 80 81 00 20 80 92 20 6f 53 d0 80  o ..!... .. oSÐ.
00000020 a0 78 20 80 83 40 a0 5d a0 5e 53 d0 80 d3 a0 62   x ..@ ] ^SÐ.Ó b
00000030 20 5d 20 80 8b 40 a0 5f a0 60 a0 65 a0 6e dd a0   ] ..@ _ ` e nÝ
00000040 61 50 84 d3 a0 62 20 5e 20 65 4e ce a0 5f 80 4c  aP.Ó b ^ eNÎ _.L
00000050 a0 60 8c 20 61 80 53 d0 80 d3 50 80 a0 60 20 80   `. a.SÐ.ÓP. ` .
00000060 b9 20 80 b3 53 50 80 a0 61 20 80 b9 a8 dc c4 aa  ¹ .³SP. a .¹¨ÜÄª
00000070 a9 a8 dc e4 aa 29                                ©¨Üäª)
00000076

Equivalent JavaScript (140 bytes, ignoring added whitespace for formatting):

f=s=>s.split(/(\D*)(\d*)/).concat(s),
_.sort(
  (a,b)=>f(a).reduce(
    (c,d,i,r,e=f(b)[i])=>
      c||d-e||d.toLowerCase().localeCompare(e.toLowerCase())
  )
)

Basically a golfed version of the example implementation given in the question.

Click here for the demo!


Tips for golfing in JavaScript What general tips do you have for golfing in JavaScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JavaScript (e.g. "remove comments" is not an answer).

  Note: Also see Tips for Golfing in ECMAScript 6 and above

Splitting with numbers to save the quotemarks:

"alpha,bravo,charlie".split(",") // before
"alpha0bravo0charlie".split(0)   // after


Cambridge Transposition I'm sure most, if not all, of you have come across this at some point or another:

Aoccdrnig to a rscheeachr at Cmabrigde Uinervtisy, it deosn't mttaer
in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is
taht the frist and lsat ltteer be at the rghit pclae. The rset can be
a toatl mses and you can sitll raed it wouthit porbelm. Tihs is
bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the
wrod as a wlohe.

Create a program that inputs any amount of text. For testing purposes, use the unscrambled version of the above text, found below.

The program must then randomly transpose the letters of each word with a length of 4 or more letters, except the first and last letter of each word.

All other formatting must remain the same (capitalization and punctuation, etc.).

Testing text:

According to a researcher at Cambridge University, it doesn't matter
in what order the letters in a word are, the only important thing is
that the first and last letter be at the right place. The rest can be
a total mess and you can still read it without problem. This is
because the human mind does not read every letter by itself but the
word as a whole.

As usual, this is a code-golf. Shortest code wins.

Ruby - 50 48 chars, plus -p command line parameter.

gsub(/(?<=\w)\w+(?=\w)/){[*$&.chars].shuffle*''}

Thanks @primo for -2 char.

Test

➜  codegolf git:(master) ruby -p 9261-cambridge-transposition.rb < 9261.in
Acdrcinog to a racreseher at Cagribmde Ursvetniiy, it dsoen't mttaer in waht odrer the leertts in a word are, the olny ionarpmtt tnhig is that the fsirt and last letetr be at the rghit pcale. The rset can be a taotl mses and you can slitl raed it wthiuot perlbom. Tihs is buaecse the hmuan mind does not raed ervey lteetr by ietlsf but the word as a wlhoe.


Crunch vowels out of a string Task description

Sometimes, you really need to fit something you’re writing in a small space. It may be tempting to drop the vowels and wrt lk ths – and failing that, who really needs spaces? Thssprfctlrdbl!†

Write a function or program that removes lowercase vowels aeiou, and then spaces, and then any characters from an input string. Furthermore, each time you remove a character, it must be the rightmost character eligible for removal. It must repeat this process until the string is no longer than some given input length.

† “This is perfectly readable!” But if you’re reading this footnote, it probably isn’t, really... :)

Examples

Here, you can see this process applied for successively smaller input sizes:

23: Hello, Code Golf World!
22: Hello, Code Golf Wrld!
21: Hello, Code Glf Wrld!
20: Hello, Cod Glf Wrld!
19: Hello, Cd Glf Wrld!
18: Hell, Cd Glf Wrld!
17: Hll, Cd Glf Wrld!
16: Hll, Cd GlfWrld!
15: Hll, CdGlfWrld!
14: Hll,CdGlfWrld!
13: Hll,CdGlfWrld
12: Hll,CdGlfWrl
11: Hll,CdGlfWr
(etc.)

After squeezing the string down to 17 characters, we run out of vowels to remove, so the next character we remove is the rightmost space; when we hit 14 characters, we’ve removed all vowels and spaces, so we simply start munching the string from right to left.

Here is some pseudocode Python code that solves this challenge:

def crunch_string(string, to_length):
    while len(string) > to_length:
        # Store the best candidate index for deletion here.
        best = None

        # First, find the rightmost vowel's index.
        for i in range(len(string)):
            if string[i] in 'aeiou':
                best = i

        # If there were no vowels, find the rightmost space's index.
        if best is None:
            for i in range(len(string)):
                if string[i] == ' ':
                    best = i

        # If there were no spaces either, use the final index.
        if best is None:
            best = len(string) - 1

        # Remove the selected character from the string.
        string = string[:best] + string[best + 1:]

    # Return the string once `len(string) <= to_length`.
    return string

Rules

This is code-golf, so the shortest code in bytes wins.
The input string will consist of the printable ASCII characters from space (, decimal 32) up to and including tilde (~, decimal 126). There will be no uppercase vowels AEIOU in the string. In particular, there will be no Unicode, tabs, or newlines involved.
Call the input string s, and the input target length t. Then 0 < t ≤ length(s) ≤ 10000 is guaranteed. (In particular, the input string will never be empty. If t = length(s), you should just return the string unmodified.)

Test cases

Input:  50, Duis commodo scelerisque ex, ac consectetur metus rhoncus.
Output: Duis commodo scelerisque ex, ac cnscttr mts rhncs.

Input:  20, Maecenas tincidunt dictum nunc id facilisis.
Output: Mcnstncdntdctmnncdfc

Input:  150, golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf
Output: glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glfglfglfglfglfglfglfglfglfglf

Perl, 48 45 43 bytes

Includes +4 for -Xlpi (-X can be left out but leaves ugly warnings on STDERR)

Run with the number after the -i option and the input on STDIN (supports multiple lines too). e.g. perl -Xlpi50 crunch.pl <<< "Duis commodo scelerisque ex, ac consectetur metus rhoncus."

crunch.pl:

s/.*\K[aeiou]|.*\K |.$// while pos=-$^I


Prime factors buddies Given an integer N > 1, output all other numbers which prime decompositions have the same digits as the prime decomposition of N.

For example, if N = 117, then the output must be [279, 939, 993, 3313, 3331], because

117 = 3 × 3 × 13

therefore, the available digits are 1, 3, 3 and 3 and we have

279  = 3 × 3 × 31
939  = 3 × 313
993  = 3 × 331
3313 = 3313
3331 = 3331

Those are the only other possible numbers, because other combination of these digits yield non-prime integers, which can't be the result of prime factorization.

If N is any of 117, 279, 939, 993, 3313 or 3331, then the output will contain the five other numbers: they are prime factors buddies.

You cannot use leading zeroes to get primes, e.g. for N = 107, its only buddy is 701 (017 is not considered).

Input and Outputs

The input and output buddies must be taken and returned in the decimal base.
N will always be strictly greater than 1.
The output can be formatted rather freely, as long as it only contains the buddies and separators/list syntactic elements.
The ordering of the output is unimportant.
You may take the input through STDIN, as a function argument or anything similar.
You may print the output to STDOUT, return it from a function, or anything similar.

Test cases

Your program should solve any of the test cases below in less than a minute.

N        Buddies
2        []
4        []
8        []
15       [53]
16       []
23       [6]
42       [74, 146, 161]
126      [222, 438, 483, 674, 746, 851, 1466, 1631, 1679]
204      [364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547]

Scoring

This is code-golf, so the shortest answer in bytes wins.

PowerShell v3+, 450 bytes

param($n)function f{param($a)for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
$y=($x=@((f $n)-split'(.)'-ne''|sort))|?{$_-eq(f $_)}
$a,$b=$x
$a=,$a
while($b){$z,$b=$b;$a=$a+($a+$y|%{$c="$_";0..$c.Length|%{-join($c[0..$_]+$z+$c[++$_..$c.Length])};"$z$c";"$c$z"})|select -u}
$x=-join($x|sort -des)
$l=@();$a|?{$_-eq(f $_)}|%{$j=$_;for($i=0;$i-le$x;$i+=$j){if(0-notin($l|%{$i%$_})){if(-join((f $i)-split'(.)'|sort -des)-eq$x){$i}}}$l+=$j}|?{$_-ne$n}

Finally!

PowerShell doesn't have any built-ins for primality checking, factorization, or permutations, so this is completely rolled by hand. I worked through a bunch of optimization tricks to try and reduce the time complexity down to something that will fit in the challenge restrictions, and I'm happy to say that I finally succeeded --

PS C:\Tools\Scripts\golfing> Measure-Command {.\prime-factors-buddies.ps1 204}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 27
Milliseconds      : 114
Ticks             : 271149810
TotalDays         : 0.000313830798611111
TotalHours        : 0.00753193916666667
TotalMinutes      : 0.45191635
TotalSeconds      : 27.114981
TotalMilliseconds : 27114.981

Explanation

There's a lot going on here, so I'll try to break it down.

The first line takes input $n and defines a function, f. This function uses accumulative trial division to come up with a list of the prime factors. It's pretty speedy for small inputs, but obviously bogs down if the input is large. Thankfully all the test cases are small, so this is sufficient.

The next line gets the factors of $n, -splits them on every digit ignoring any empty results (this is needed due to how PowerShell does regex matching and how it moves the pointer through the input and is kinda annoying for golfing purposes), then sorts the results in ascending order. We store that array of digits into $x, and use that as the input to a |?{...} filter to pull out only those that are themselves prime. Those prime digits are stored into $y for use later.

We then split $x into two components. The first (i.e., smallest) digit is stored into $a, while the rest are passed into $b. If $x only has one digit, then $b will be empty/null. We then need to re-cast $a as an array, so we use the comma operator quick-like to do so.

Next, we need to construct all possible permutations of the digits. This is necessary so our division tests later skip a bunch of numbers and make things faster overall.

So long as there's element left in $b, we peel off the first digit into $z and leave the remaining in $b. Then, we need to accumulate into $a the result of some string slicing and dicing. We take $a+$y as array concatenation, and for each element we construct a new string $c, then loop through $c's .length and insert $z into every position, including prepending $z$c and appending $c$z, then selecting only the -unique elements. That's again array-concatenated with $a and re-stored back into $a. Yes, this does wind up having goofy things happen, like you can get 3333 for input 117, which isn't actually a permutation, but this is much shorter than attempting to explicitly filter them out, ensures that we get every permutation, and is only very marginally slower.

So, now $a has an array of all possible (and then some) permutations of the factor's digits. We need to re-set $x to be our upper-bound of possible results by |sorting the digits in -descending order and -joining them back together. Obviously, no output value can be larger than this number.

We set our helper array $l to be an array of values that we've previously seen. Next, we're pulling out every value from $a (i.e., those permutations) that are prime, and enter a loop that is the biggest time sink of the whole program...

Every iteration, we're looping from 0 to our upper bound $x, incrementing by the current element $j. So long as the $i value we're considering is not a multiple of a previous value (that's the 0-notin($l|%{$i%$_}) section), it's a potential candidate for output. If we take the factors of $i, sort them, and they -equal $x, then add the value to the pipeline. At the end of the loop, we add our current element $j into our $l array for use next time, as we've already considered all those values.

Finally, we tack on |?{$_-ne$n} to pull out those that are not the input element. They're all left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> 2,4,8,15,16,23,42,117,126,204|%{"$_ --> "+(.\prime-factors-buddies $_)}
2 -->
4 -->
8 -->
15 --> 53
16 -->
23 --> 6
42 --> 74 146 161
117 --> 279 939 993 3313 3331
126 --> 222 438 674 746 1466 483 851 1679 1631
204 --> 782 2921 3266 6233 3791 15833 2951 7037 364 868 8561 15491 22547 852 762 1626 692 548 1268 2654 3446 2474 5462 4742 5426 4274 14426 6542 6434 14642


Sort items based on dependency Goal

Sort a list of items ensuring that each item is listed after its specified dependencies.

Input

An array of arrays of integers, where each integer specifies the 0-based or 1-based index of another item that this item must come after.  The input may be an array or string or anything else human readable.

For example, a 0-based input:

[
  [ 2 ],    // item 0 comes after item 2
  [ 0, 3 ], // item 1 comes after item 0 and 3
  [ ],      // item 2 comes anywhere
  [ 2 ]     // item 3 comes after item 2
]

Assume there are no circular dependencies, there is always at least one valid order.

Output

The numbers in order of dependency.  An ambiguous order does not have to be deterministic.  The output may be an array or text or anything else human readable.

Only one order should be given in the output, even where there are multiple valid orders.

Possible outputs for the above input include:

[ 2, 3, 0, 1 ]
[ 2, 0, 3, 1 ]

Scoring

A function or program that completes this in the least number of bytes wins the glory of acceptance.  The deadline is in 6 days.

Pyth, 21 bytes

hf.A.e!f>xYTxkTbQ.plQ

                    Q  input
                   l   length of input array
                 .p    all permutations of [0, 1, ..., lQ-2, lQ-1]
hf                     find the first permutation for which...
    .e          Q        map over the input array with indices...
       f       b           find all elements in each input subarray where...
        >xYT                 index of dependency is greater than...
            xkT              index of item
      !                    check whether resulting array is falsy (empty)
  .A                     is the not-found check true for [.A]ll elements?

Test:

llama@llama:~$ echo '[[2],[0,3],[],[2]]' | pyth -c 'hf.A.e!f>xYTxkTbQ.plQ'
[2, 0, 3, 1]


ASCII clock with dot & comma time markers Introduction

Imagine that line of chars is in fact two rows. Upper row - dots -  represents hours (24 hour system), while lower - commas - represents minutes. One character can represent hour, minute or both - whenever it's possible.
At first probably you'd have to convert minutes since midnight to hours and minutes.
The result is the string showing current time in "dot format". The dot count (apostrophe counts here as a dot and will be called so!) is the hour count since midnight and comma count is minutes count. I'll show a few examples to make it clear.

(Remark) hh:mm - result
(Only hours) 05:00 - '''''
(Only minutes) 00:08 - ,,,,,,,,
(hours < minutes) 03:07 - ;;;,,,,
(hours > minutes) 08:02 - ;;''''''
(hours = minutes) 07:07 - ;;;;;;;
(the start of the day) 00:00 -   (empty result)

Notice that "both" character can be used max 23 times - for 23:xx, where xx is 23 or more.
Symbols
If character have to (see rule 5.) be escaped in your language, you could changed it to one of alternatives. If said alternatives aren't enough, you may use other symbols - but keep it reasonable. I just don't want escaping to be a barrier.

; (semicolon) - marker for both hours and minutes (alt: :)
' (apostrophe) - marker for hours (alt: '``°)
, (comma) - marker for minutes (alt: .)

Additional rules

The code with the least amount of bytes wins!
You have to use both symbol whenever it's possible. For 02:04 the result can't be '',,,,, nor ;',,,. It have to be ;;,,
Input - can be script/app parameter, user input (like readline) or variable inside code
3.1. If the variable inside code is used, then its lenght have to be the longest possible. It's 1439 (23:59), so it would look like t=1439
The common part which is symbolized by "both" character (12 in 12:05, 3 in 03:10) must be placed on the beginning of the string
Symbols can be replaced to alternatives only if they would have to be escaped in your code.
Input is given in minutes after 00:00. You can assume that this is a non-negative integer.

Test cases
Input: 300
Output: '''''

Input: 8
Output: ,,,,,,,,

Input: 187
Output: ;;;,,,,

Input: 482
Output: ;;''''''

Input: 427
Output: ;;;;;;;

Input: 0
Output:  (empty)

Pyth, 19 bytes

:.iF*V.DQ60J"',"J\;

Test suite

:.iF*V.DQ60J"',"J\;
      .DQ60            Divmod the input by 60, giving [hours, minutes].
           J"',"       Set J equal to the string "',".
    *V                 Perform vectorized multiplication, giving H "'" and M ','.
 .iF                   Interleave the two lists into a single string.
:               J\;    Perform a substitution, replacing J with ';'.


Inspired by HQ9+: 4-Behavior Polyglot Create a program that can be run in 4 different languages such that:

One language prints "Hello World!"
One language outputs its own source code
One language outputs 99 bottles of beer on the wall, that is:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall

98 bottles of beer on the wall
98 bottles of beer
Take one down...

<the pattern continues for a while>

...pass it around
1 bottle of beer on the wall

1 bottle of beer on the wall
1 bottle of beer
Take one down, pass it around
No more bottles of beer on the wall

One language takes a nonnegative integer as an input and outputs that integer + 1

Rules and Scoring

This is code golf, so shortest code wins. Score in character count rather than byte count for this challenge so that golfing languages that use specialized codepages are not disadvantaged by their UTF-8 representations.
Standard rules and loopholes apply
Each language may optionally output a trailing newline for its designated output
Each language may use any I/O convention that is convenient to that language. The convention does not need to be consistent across all four languages; for instance, one uses stdout, another uses the return value, one writes to a file, and the last one spawns an alert containing the text.
Golfing languages that have the option to use specialized codepages must use a standard encoding; they may not take advantage of a byte being interpreted as a different character in another encoding.
Hello World may optionally include a comma after "Hello", thus Hello, World! is a valid output.
Standard quine rules apply and the only superfluous output allowed is a trailing newline.

Text, or any other "language" where all programs are quines, is not a valid language for the quine.

99 Bottles of Beer requires:

A blank line between each verse
No blank lines within any verse
The singular/plural distinction of 'bottle' vs 'bottles'
no more instead of 0 on the last line
Each line may have any amount of trailing whitespace (or none at all)

The incrementing program must support all input integers that can be incremented natively by its language.

For languages which support unsigned integers, the largest unsigned integer should be used
For languages which represent all numbers as floating point numbers, this would require supporting all input numbers up to \$2^{53}-1\$.
For languages which natively support arbitrary-sized integers, all positive integers must be supported.

Format the header of your answer like this:
# <language for H, <language for Q>, <language for 9>, <language for +>, n characters

Ruby, ><>, HQ9+, Befunge-93, 62 characters
#9&1+.@.10[0[fr'
puts"\u0048ello World!"#.1*57;!?lo r]r}:*3da'

"Hello World!" (Ruby)
Relevant part of code:
puts"\u0048ello World!"
quine (><>)
After colliding with the # mirror, both lines are read as string literals and printed with a newline between.
99 bottles of beer on the wall (HQ9+)
Code contains no H or Q, and exactly one 9, so the lyrics of the song are printed once.
+1 program (Befunge-93)
After jumping over 9 due to the # trampoline, a simple +1 program is run &1+.@


Convert between balanced bases! Balanced bases:

Balanced bases are essentially the same as normal bases, except that digits can be positive or negative, while in normal bases digits can only be positive.

From here on, balanced bases of base b may be represented as balb - so balanced base 4 = bal4.

In this challenge's definition, the range of digits in a balanced base of base b is from -(k - 1) to b - k, where

k = ceil(b/2)

Examples of the range of digits in various balanced bases:

bal10:
  k = ceil(10/2) = 5
  range = -(5 - 1) to 10 - 5 = -4 to 5
        = -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
bal5:
  k = ceil(5/2) = 3
  range = -(3 - 1) to 5 - 3 = -2 to 2
        = -2, -1, 0, 1, 2

Representations of numbers in balanced bases is basically the same as normal bases. For example, the representation of the number 27 (base 10) to bal4 (balanced base 4) is 2 -1 -1, because

  2 -1 -1 (bal4)
= 2 * 4^2 + -1 * 4 + -1 * 1
= 32 + (-4) + (-1)
= 27 (base 10)

Task:

Your task is, given three inputs:

the number to be converted (n)

this input can be flexible, see "I/O Flexibility"

the base which n is currently in (b)
the base which n is to be converted to (c)

Where 2 < b, c < 1,000.

Return the number in balanced base c representation of n. The output can also be flexible.

The program/function must determine the length of n from the input itself.

I/O Flexibility:

Your input n and output can be represented in these ways:

your language's definition of an array
a string, with any character as a separator (e.g. spaces, commas)

Examples:

Note that these use a Python array as n and the output. You may use whatever fits your language, as long as it fits within "I/O Flexibility"'s definition.

[2, -1, -1] 4 7 = [1, -3, -1]
[1, 2, 3, 4] 9 5 = [1, 2, 2, -1, 2]
[10, -9, 10] 20 5 = [1, 1, 1, -2, 1, 0]

This is code-golf, so shortest code in bytes wins!

Mathematica, 85 bytes
#~FromDigits~#2~IntegerDigits~#3//.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}&

Explanation
#~FromDigits~#2

Convert #1 (1 is implied--input 1, a list of digits) into an integer base #2 (input 2).
... ~IntegerDigits~#3

Convert the resulting integer into base #3 (input 3), creating a list of digits.
... //.{p___,a_:0,b_,q___}/;b>⌊#3/2⌋:>{p,a+1,b-#3,q}

Repeatedly replace the list of digits; if a digit is greater than floor(#3/2), then subtract #3 from it and add 1 to the digit to the left. If there is nothing on the left, insert a 0 and add 1.


Python 2, 81 bytes

x=0
exec"print'%05.2f.2017'%(x%30.99+1.01);x+=7+'0009ANW'.count(chr(x/7+40));"*53

Try it online!

No date libraries, computes the dates directly. The main trick is to treat the dd.mm as a decimal value. For example, 16.04.2017 (April 16) corresponds to the number 16.04. The number is printed formatted as xx.xx with  .2017 appended.

The day and month are computed arithmetically. Each week adds 7 days done as x+=7. Taking x modulo 30.99 handles rollover by subtracting 30.99 whenever the day number gets too big. This combines -31 to reset the days with +0.01 to increment the month.

The rollover assumes each month has 31 days. Months with fewer days are adjusted for by nudging x upwards on certain week numbers with +[8,8,8,17,25,38,47].count(x/7). These list is of the week numbers ending these short months, with 8 tripled because February is 3 days short of 31.

This list could is compressed into a string by taking ASCII values plus 40. The shift of +40 could be avoided by using unprintable chars, and could be accessed shorter as a bytes object in Python 3.


Check all the keys of a keyboard Write the shortest program that waits for every key of a Standard 101 key US Keyboard* to be pressed and then exits writing OK!

Every time a key is pressed the program displays on a new line the remaining number of unpressed unique keys that need to be pressed until all key are pressed at least once. The program should be able to test a 101 keyboard and see if every key works. So pressing twice a key or enter is to be allowed as long as this is specified to the user.

Pressing same key twice or more should not disrupt the code nor change the displayed number of remaining unpressed keys.

All keys (Left Shift, Right Shift, Right Control, Esc, Enter, etc.) should be included.

The actual keyboard keys are important in this challenge so from the perspective of the program (A and a, are the same and so are 6 and ^).

Combined keys will not be registered as a combined command and only the individual keys will be registered if Ctrl + Alt + Del is pressed that will count for all the individual keys in the combination being pressed. So no need to press also the capital letters if you pressed already the lowercase and vice-versa.

Numeric keys on the numeric keypad are different from the perspective of the program, so they are still needed to be pressed for the program to finish, if you have a laptop or any other keyboard that doesn't have the US Standard 101 keyboard layout you cannot fulfill the challenge unless you plugin a compatible keyboard.

*Keyboards having Fn key and laptop key will not be supported to keep this challenge doable

This is the list of keys for a US Standard 101 keyboard layout:

backspace
tab
enter
right shift
right ctrl
right alt
left shift
left ctrl
left alt
print screen
pause/break
caps lock
escape
page up
page down
end
home
left arrow
up arrow
right arrow
down arrow
insert
delete
0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
numpad 0
numpad 1
numpad 2
numpad 3
numpad 4
numpad 5
numpad 6
numpad 7
numpad 8
numpad 9
multiply
add
subtract
decimal point
numpad enter
divide
f1
f2
f3
f4
f5
f6
f7
f8
f9
f10
f11
f12
num lock
scroll lock
semi-colon
equal sign
comma
dash
period
forward slash
grave accent
open bracket
back slash
close braket
single quote
space

Javascript, 524 bytes
Hi, this is my first ever post here, so excuse me if I'm still ignorant on some stuff, I think I stayed within the rules though.
k=[8,9,"130","133","161","162","171","172","181","182",19,20,27,44,45,46,48,49,50,51,52,53,54,55,56,57,144,145,186,187,188,189,190,191,192,219,220,221,222];for(i=32;i<124;i+=1){i<41?k.push(i):i>64?i<91?k.push(i):i>95?i!=108?k.push(i):0:0:0}d=[13,16,17,18];m=document.addEventListener;c=console.log;m("keydown",e=>{e.preventDefault()});m("keyup",e=>{c(e.code);if(d.includes(e.which)){l=e.which+""+e.location;if(k.includes(l)){k.splice(k.indexOf(l),1)}}else if(k.includes(e.which)){k.splice(k.indexOf(e.which),1)}c(k.length)})

It seems buggy if I don't use Chrome, but you can try it out here.
(be sure to open the console before you focus on the example window, as the default functionality of F12 is prevented)
Overview
The program makes an array of all the 101 "keycodes". Some are written explicitly, some sequences are added with a for loop and some are stored as strings. I have a seperate array for the "double" keycodes, since left and right control for instance give the same keycode. They also give a location, however, so I combine the keycodes with the locations as strings in the array. From there it's just an eventlistener that prevents default keydown functionality (don't wanna refresh with F5 in this case) and a seperate eventlistener for keyup, because every single key can be detected on keydown, EXCEPT FOR PRINTSCREEN.
After every keyup event the remaining keys (aka the length of the array) gets logged, as well as the name of the keycode (so there is the distinction between left and right shift, etc). I wasn't sure if that was a requirement, if not you can subtract another 10 bytes from the score.
Limitations

It only seems to work well in Chrome

I hope this answer is appreciated and please let me know if I've done anything wrong.


Smallest chess program Inspired by this recent article telling of a French programmer who wrote a 487 byte 2-player (human vs. human) chess program in Assembly, I wondered how small chess programs could be in other languages.

Details

The program must only accept legal chess moves.
Declaration of check/checkmate is not necessary (just desirable), although the first rule applies in cases of check.
As per the article, castling is not a necessary implementation.
Also, you do not have to implement en passant.
You do however, have to permit pawn promotion upon reaching eighth rank (you may opt to simply force conversion to queen).
It is up to you how the board is displayed - terminal ASCII, GUI, etc.
You must display whose turn it is.

The rules of chess can be found here - ignore specified tournament rules (e.g. timing, touching), and remember castling and en passant are not necessary implementations.

C, 650 600

n=8,t=65,s,f,x,y,p,e,u=10,w=32,z=95;char a[95],b[95]="RNBKQBNR";v(){p=a[s]&z;y=f/u-s/u;x=f-s-y*u;e=x*x+y*y;n=s%u/8|f%u/8|a[s]/w-t/w|a[f]/w==t/w|!(p==75&e<3|p>80&x*y==0|p%5==1&x*x==y*y|p==78&e==5|p==80&x*(z-t)>0&(a[f]-w?e==2:e==1|e==4&s%5==1));if(!n&&p-78)for(e=(f-s)/abs(x*x>y*y?x:y),x=s;(x+=e)-f;)n|=a[x]-w;}main(){for(a[93]=40;n--;a[92]=47)sprintf(a,"%s%cP    p%c \n",a,b[n],b[n]+w);for(;1;){puts(a);for(n=1;n;){putchar(t);scanf("%d%d",&s,&f);v();memcpy(b,a,z);if(!n){a[f]=p-80|f%u%7?a[s]:t+16;a[s]=w;a[f]&z^75||(a[z-t/w]=f);f=a[z-t/w];t^=w;for(n=1,s=80;n&&s--;)v();if(n=!n)memcpy(a,b,z),t^=32;}}}}

To reduce the code for initializing the board, the display has White (uppercase) playing from left to right and Black (lowercase) playing from right to left. Input is in the form of two 2-digit decimal numbers (start position and finish position), giving file(0-7) and rank(0-7). For a bit of extra code (subtract 11 from each input), input could be made to comply with http://en.wikipedia.org/wiki/ICCF_numeric_notation (digits 1-8)
Here's a sample screenshot where Black has just advanced his Rook's Pawn. White tries various illegal moves with his queen, before finally capturing the pawn. Turn indicators are a for Black and A for White.

An interesting feature of my validation is the use of the square of the Euclidean distance. For the knight this is always 1^2+2^2=5, but I also use it for the King and the pawn.
Test for Check is done by backing up the board, carrying out the players move, and scanning all 64 possible opponent's moves.
The program has to be ended with Ctrl-C. I cant think of a more gracious way of doing it, other than putting in a special move to end the program. A game of chess actually ends when one player is unable to move on his turn (checkmate or stalemate) and that requires a lot of tests that arent required by the spec.
Commented code
n=8,t=65,s,f,x,y,p,e,u=10,w=32,z=95;                 // 8,10 height and width of board. w=ASCII space, also difference between ucase and lcase
                                                     // 95 is bitmask for conversion lowercase to uppercase, but also used as length of array, etc.
char a[95],b[95]="RNBKQBNR";                         // a is main board, b is backup board (but used at start to hold 1st row data.)

v(){                                                 // validate move in all aspects except check
  p=a[s]&z;                                          // p=uppercase(character on start square)
  y=f/u-s/u;                                         // signed distance in y direction
  x=f-s-y*u;                                         // and x direction
  e=x*x+y*y;                                         // square of Euclidean distance
  n=s%u/8|f%u/8|                                     // n=true if 2nd digit of input out of bounds OR
  a[s]/w-t/w|a[f]/w==t/w|                            // start sq not friendly piece OR finish sq is friendly piece (also eliminates case where start=finish)
  !(                                                 // OR NOT geometry valid
    p==75&e<3|                                       // 'K'(ASCII75) AND euclidean distance squared =1 or 2 OR
    p>80&x*y==0|                                     // 'Q'or'R' AND x or y = 0 OR
    p%5==1&x*x==y*y|                                 // 'Q'or'B' AND abs(x)=abs(y)
    p==78&e==5|                                      // 'N' AND euclidean distance squared = 5
    p==80&x*(z-t)>0&(a[f]-w?e==2:e==1|e==4&s%5==1)   // 'P'(ASCII80):x direction must correspond with case of player (z-t)
  );                                                 // if capturing e=2. Otherwise e=1 (except on start rows 1 and 6, e can be 4)
  if(!n&&p-78)                                       // if not yet invalid and piece not 'N'(ASCII78)
    for(e=(f-s)/abs(x*x>y*y?x:y),x=s;(x+=e)-f;)      // Set e to the numeric difference to travel 1 square in right direction. Set x to start square
       n|=a[x]-w;                                    // and iterate x through all intervening squares, checking they are blank
}

main(){

  for(a[93]=40;n--;a[92]=47)                         // iterate n through 8 rows of board. vacant spaces in bracket are use to assign start positions of kings to a[92&93]
    sprintf(a,"%s%cP    p%c \n",a,b[n],b[n]+w);      // build up start position, each row 10 squares wide, including filler space the end and newline

  for(;1;){                                          // loop forever
    puts(a);                                         // display board
    for(n=1;n;){                                     // loop while move invalid
      putchar(t);                                    // display prompt 'A' for white 'a' for black
      scanf("%d%d",&s,&f);                           // get input
      v();                                           // validate move
      memcpy(b,a,z);                                 // backup board (and king position metadata)
      if(!n){                                        // if move not yet invalid
        a[f]=p-80|f%u%7?a[s]:t+16;                   // if not a pawn on last row, content of finish square = start square, ELSE queen of correct case (t+16)
        a[s]=w;                                      // start square becomes blank (ASCII32)
        a[f]&z^75||(a[z-t/w]=f);                     // if finish square king, update king position metadata
        f=a[z-t/w];                                  // to begin scanning to see if king in check, set f to current king position
        t^=w;                                        // and change colour
        for(n=1,s=80;n&&s--;)v();                    // for s=79..0 search for valid opponent move to capture king (stops with n=0)
        if(n=!n)memcpy(a,b,z),t^=32;                 // valid opponent threat on king means invalid player move. Invert n, recover board from backup and change colour back.
      }
    }
  }
}


Find the haystack in the needles In a twist on finding a needle in a haystack, you need to find the largest contiguous haystack containing exactly one needle. Note that you cannot connect cells on diagonals, only left/right/up/down.

Input

An array (or a number of user input lines, your pick) of 'N' (needles) and '#' (hay) characters. Input only contains those two characters, and must contain at least one of each. For example:

N#N#N
#NN##
###N#
N##N#

Output

The size of the largest possible valid haystack. For our example, we would output 11 (there are 11 pieces of hay, and one needle).

   #
#  ##
###N#
 ## #

This is code-golf, so shortest code wins.  Standard loophole restrictions apply.

Test Cases

Input on left, possible maximal haystack on right

Case 1: 4

N##    ##
NN#     #
#NN     N
#N#     #

Case 2: 7

###   ###
N#N    #
NNN    N
###   ###

Case 3: 10

N###N    ###
#N#N#   #N#
#N#N#   # #
N###N    ###

Case 4: 10

N#N#N
#N#N#   # # #
##N##   ##N##
#N#N#   # # #
N#N#N

Case 5: 1

NN#NN
NNNNN
#NNN#   #N
NN#NN

Ruby, 207
->a{d=->b{0...b.size}
f=c=s=->y,x{(d[a]===y&&d[a[0]]===x&&!f[y][x]&&a[y][x]==c)?(c,f[y][x]=?#,1
1+s[y,x-1]+s[y,x+1]+s[y-1,x]+s[y+1,x]):0}
d[a].map{|y|d[y].map{|x|f,c=a.map{|b|b.map{p}},?N
s[y,x]}.max}.max-1}

This is an anonymous function that takes in the input as an array of arrays. Usage:
f=->a{......}

f["
N##
NN#
#NN
#N#
".strip.split.map(&:chars)] # => 4

The proc named s recursively finds the size of the haystack with needle at specific coordinates and is called on each needle in the haystack.


Extract an RGB channel of an image Given an image, either as input (possibly in RGB triplets) or with the filename as input (you may assume the image has a specific filename, possibly without an extension), output an image representing a single color channel of the image.

You will also take another input, representing which channel to output. The input can be one of any 3 distinct symbols.  However, the symbols must be either a string or a number. You cannot take a matrice to apply to the array as input however. (such as {1, 0, 0}, or {0, 1, 0}).

You will output the <input> channel of the input image.  You may either save it to a file or output a set of RGB pairs.

Your program should have no limits on the size of the image (in px), and must support either .png, .jpg/.jpeg/.JPG, or RGB triplets as image formats. (it can support as many as you want however)

Test case:

Red channel:

Green channel:

Blue channel:

And another test case, entirely of red.  Original photo, red, green, and blue.  (warning: the plain and red channel hurt to look at for too long)

2 more test cases:

Original, red, green, blue.

Original, red, green, blue.

The latter two test cases are from Images with all colors.

JavaScript (ES6), 29 bytes

a=>n=>a.map(b=>b.map(c=>c&n))

Input is a 2D array of 24-bit integers (e.g. [[0x0000ff,0x00ff00],[0xff0000,0xffffff]]) and 16711680 for red, 65280 for green, 255 for blue. If this isn't valid, try this instead:

JavaScript (ES6), 48 bytes

a=>n=>a.map(b=>b.map(c=>c.map((d,i)=>i==n?d:0)))

Input is a 3D array of color values and 0 for red, 1 for green, 2 for blue.


Print a non-clashing binary search tree Brief

Print an ASCII representation of a binary search tree.
You should write your own minimum implementation logic of a BST (node, left, right, insert)

(50,30,70,20,80,40,75,90) gives:

__50__70__80__90
   |       |
   |       |__75
   |
   |__30__40
       |
       |__20

Detailed requirements

Items are inserted into the tree in the order in which they are in the list
All node values are right aligned in columns.
Right nodes are joined using __
Right nodes are represented along the horizontal and appear directly to the right of the parent node
Right nodes are separated by a minimum of 2 underscores (__)
Left nodes are joined using | and |__ on the next line
Left nodes are represented along the vertical and appear under and to the right of the parent (ie, next column).
Left nodes are separated by a a minimum of a blank line (discounting pipes (|) linking child to parent)
The vertical pipes joining 2 left nodes should be in the column directly under the last character of the parent node (see samples)
Column width is determined using something like max(col_values[]).toString().length() + 2
Branching left always adds a new row to the tree diagram
2 separate (left) branches never appear on the same line (right__right__right is OK)
The root node may optionally be prefixed with __ (Removing it just about doubled my test code!)
Input is a set of positive and/or negative integers
You do not need to deal with duplicate values (drop/ignore them)
I'm not placing many restrictions on trailing whitespaces:

You may have trailing whitespaces after the last node on a line
You may have trailing whitespace after a | on the empty lines
No whitespace between nodes when when branching right

Standard loopholes and T&Cs apply
This is code-golf. Shortest code in bytes wins!

I'm aware that this is a potential duplicate, but I think I've been specific enough in my requirements that it should pose new challenges.

Sample Input/Output

Input

(50,40,30,20,10)

Output

__50
   |
   |__40
       |
       |__30
           |
           |__20
               |
               |__10

Input

(10,20,30,40,50)

Output

__10__20__30__40__50

Input

(50,700,30,800,60,4,5,10,20,2,500,850,900,950,870,35,1,-10)

Output

__50__700__800__850__900__950
   |    |              |
   |    |              |__870
   |    |
   |    |___60__500
   |
   |___30___35
        |
        |____4____5___10___20
             |
             |____2
                  |
                  |____1
                       |
                       |__-10

Java 1286 1106 1100 bytes

Here's an easy entry to beat ;-)

Pretty messy. I traverse the tree, populating a 2d array with the node values (and left branch pipes), and a size array with the maximum column widths. Then print the node array using size array to determine correct horizontal spacing.  I look forward to seeing a better way of doing this.

class N{N l,r;int v,i,h,g,b,e,c,j;String[][]a=new String[10][10];int[]w=new int[10];String o="",p="";N(int x){v=x;}void i(int n){if(n>v)if(r==null)r=new N(n);else r.i(n);else if(n<v)if(l==null)l=new N(n);else l.i(n);}void p(N node){a[b][h]=""+node.v;if(w[h]<a[b][h].length())w[h]=a[b][h].length();if(node.r!=null){h++;p(node.r);h--;}if(node.l!=null){b++;while(g<b)a[++g][h]="|";h++;p(node.l);if(a[--g][--h].equals("|"))g--;}}void d(){for(e=-1;++e<a.length;){o="";for(j=-1;++j<a[0].length;){p=a[e][j];if(p!=null)if(p.equals("|")){for(i=0;i++<w[j]-p.length()+2;)o+=" "; o+=p;}else for(i=0;i++<w[j]+2;)o+=" ";else for(i=0;i++<=w[j]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);o="";for(c=-1;++c<a[0].length;){p=a[e][c];if(p!=null)if(p.equals("|")){for(i=0;i++<w[c]-p.length()+2;)o+=" ";o+=p;}else{for(i=0;i++<w[c]-p.length()+2;)o+="_"; o+=p; }else for(i=0;i++<=w[c]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);}}public static void main(String[]a){String[]q=a[0].split(",");N t=new N(Integer.parseInt(q[0]));for(int i=0;i++<q.length-1;)t.i(Integer.parseInt(q[i]));t.p(t);t.d();}}

__50__700__800__850__900__950
   |    |              |
   |    |              |__870
   |    |
   |    |___60__500
   |
   |___30___35
        |
        |____4____5___10___20
             |
             |____2
                  |
                  |____1
                       |
                       |__-10

Ungolfed

class N {
    N leftNode, rightNode;
    int index, loop, curRight, curDown, maxDown, row,col;
    String[][] nodes = new String[10][10];
    int[] colWidths = new int[10];
    String line = "", node="";

N(int index) {
    this.index = index;
}

void i(int newValue) {
    if (newValue > index) {
        if (rightNode == null) {
            rightNode = new N(newValue);
        }
        else {
            rightNode.i(newValue);
        }
    }
    else if (newValue < index) {
        if (leftNode == null) {
            leftNode = new N(newValue);
        }
        else {
            leftNode.i(newValue);
        }
    }
}

void p(N node) {
    // Push current node
    nodes[maxDown][curRight] = ""+node.index;
    // Keep track of max column widths
    if (colWidths[curRight] < nodes[maxDown][curRight].length()) {
        colWidths[curRight] = nodes[maxDown][curRight].length();
    }
    // Branch right
    if (node.rightNode != null) {
        curRight++;
        p(node.rightNode);
        curRight--;
    }
    // Branch left
    if (node.leftNode != null) {
        maxDown++;
        while (curDown<maxDown){
            nodes[++curDown][curRight] = "|";
        }
        curRight++;
        p(node.leftNode);
        if (nodes[--curDown][--curRight].equals("|")) { //following the ladder back up
            curDown--;
        }
    }
}

void d() {
    for ( row = -1; ++row < nodes.length;) {
        // Sloppy. Inject extra rows to extend pipes (double spacing)
        line = "";
        for (int col = -1; ++col < nodes[0].length;) {
            node = nodes[row][col];
            if (node!=null){
                if (node.equals("|")) {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2; ){
                        line+=" ";
                    }
                    line+=node;
                }
                else {
                    for (loop=0; loop++< colWidths[col]  + 2;){
                        line+=" ";
                    }
                }
            }
            else {
                for (loop=0; loop++<=colWidths[col]+1;){
                    line+=" ";
                }
            }
        }
        if (!line.trim().equals("")){
            System.out.println(line);
        }
        line="";

        for ( col = -1; ++col < nodes[0].length;) {
            node = nodes[row][col];
            if (node!=null){
                if (node.equals("|")) {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2;){
                        line+=" ";
                    }
                    line+=node;
                }
                else {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2;){
                        line+="_";
                    }
                    line+=node;
                }
            }
            else {
                for (loop=0; loop++<=colWidths[col]+1;){
                    line+=" ";
                }
            }
        }
        if (!line.trim().equals("")){
            System.out.println(line);
        }
    }
}

public static void main(String[]a){
    String[] values = a[0].split(",");
    N t=new N(Integer.parseInt(values[0]));
    for (int i=0;i++<values.length-1;)
    t.i(Integer.parseInt(values[i]));
    t.p(t);
    t.d();
}
}


Power Grid Resource Costs Power Grid Resource Costs

Introduction

In the board game Power Grid, an integral part of the game is the act of buying resources to fuel your power stations. There are four types of resource used in the game (five, if you include renewable energy, but obviously you can't buy resources for that). These are Coal, Oil, Garbage, and Uranium. The resource market looks like this:

1---- | 2---- | 3---- | 4---- | 5---- | 6---- | 7---- | 8---- | 10  | 12
CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   |  U  |  U
OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | 14  | 16
GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   |  U  |  U

When resources are bought, they are taken from the left of the market, where they are cheapest. When new resources are added to the market, they are added from the right. As can be seen, this produces a supply and demand balance - if more resources of a particular type are being bought than are being replenished each round, the price of that resource will rise. Similarly, if it's less, the cost will reduce.

Coal, Oil, and Garbage all scale up in cost at the same rate, while Uranium scales much faster. A single unit of a non-Uranium resource costs 8 - floor((<units available> - 1) / 3). A single unit of Uranium costs 13 - <units available> if there are 5 or more units available, and 18 - (2 * <units available>) otherwise.

For example, at the start of the game there are all 24 units of Coal available to buy. If the first player would like to buy 4 units of Coal, the first three units would cost 1 each, and the 4th would cost 2, making the total cost 5. This leaves 20 units available. If the second player would also like to buy 4 units of Coal, the cost would be (2*2 + 2*3) = 10.

The Challenge

Your challenge is to write a program or function which calculates the cost of buying a given amount of a particular resource, assuming that there is a given amount of that resource present in the market.

Your submission should accept, in any reasonable input format and in any order, the following parameters:

The resource type - guaranteed to be one of [C, O, G, U].
The amount of that resource that is present in the market - guaranteed to be a non-negative integer. If the resource type is not U, it will not be greater than 24. If the resource type is U, it will not be greater than 12.
The amount of that resource that a player would like to buy - guaranteed to be a non-negative integer which is less than or equal to the amount already present in the market.

The output should be the cost of the requested resources.

Additional Rules

The formulae given are for illustrative purposes only, feel free to use any method of calculating the costs you like.
The letter codes for the different resource types (C, O, G, U) may be replaced by their lower case equivalents. You may also replace the letters for numbers, either in the form C=0, O=1, G=2, U=3 or C=1, O=2, G=3, U=4.
This is code-golf, so the smallest submission in bytes will be the winner.
If your submission requires the input in a different order or format than specified in the previous section, you should provide details.

Test cases

Test case format:

resource type, amount in market, amount to buy
> result

Test cases:

C, 24, 4
> 5

C, 20, 4
> 10

O, 3, 3
> 24

U, 1, 1
> 16

C, 1, 1
> 8

G, 0, 0
> 0

O, 10, 7
> 44

U, 12, 4
> 10

G, 11, 4
> 22

Python 3, 71 69 bytes
Thanks to @xnor for -2 bytes
f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1)

A function that takes input via argument of the zero-indexed resource type r, the amount available a and the amount to buy b, and returns the cost.
This makes use of the fact that True and False equate to 1 and 0 in Python, allowing the use of Boolean expressions to index into lists.
How it works
f=lambda r,a,b           Function with input resource type r, amount available a and amount
                         to buy b
b and...                 Base case: return 0 if b=0
[8-int(~-a/3),...][r>2]  If not uranium, yield the unit cost 8-floor((a-1)/3)...
max(18-2*a,13-a)         ..else yield the current uranium unit cost
...f(r,a-1,b-1)          Decrement a and b, then pass to function
...+...                  Add the cost of each unit to give the total cost
:...                     Return the above

Try it on Ideone


Find the maximum operation The challenge is to find the maximum number you can get from a list of integer using basic arithmetic operators (addition, substraction, multiplication, unary negation)

Input

A list of integers

Output

The maximum result using every integer in the intput.

The input order doesn't matter, result should be the same.

You do not need to output the full operation, just the result.

Examples

Input : 3 0 1
Output : 4 (3 + 1 + 0)

Input : 3 1 1 2 2
Output : 27 ((2+1)*(2+1)*3))

Input : -1 5 0 6
Output : 36 (6 * (5 - (-1)) +0)

Input : -10 -10 -10
Output : 1000 -((-10) * (-10) * (-10))

Input : 1 1 1 1 1
Output : 6 ((1+1+1)*(1+1))

Rules

Shortest code wins
Standard "loopholes" apply
You may only use + * - operators (addition, multiplication, substraction, unary negation)
The code should work as long as the result can be stored on a 32 bit Integer.
Any overflow behaviour is up to you.

I hope this is clear enough, this is my first Code Golf challenge suggestion.

C - 224 bytes - Running time O(n)
o=0,w=0,n[55],t,*m=n,*p=n;main(r){for(;scanf("%d",++p);t<3?--p,w+=t/2,o+=t&1:t<*m|m==n?m=p:9)t=*p=abs(*p);t=o<w?o:w;o-=t;w-=t;t+=o/3;for(o%3?o%3-2?t?t--,w+=2:++*m:w++:9;t--;)r*=3;for(r<<=w;--p>n;)r*=*p;printf("%d",r>1?r:o);}

It was amusing to see only exponential-time solutions for a linear-time problem, but I suppose it was the logical way to proceed since there were no bonus points for actually having an algorithm, which is an anagram of logarithm.
After converting negative numbers to positive and discarding zeroes, clearly we are mostly interested in multiplication. We want to maximize the logarithm of the final number.
log(a + b) < log(a) + log(b) except when a = 1 or b = 1, so ones are the only case in which we are interested in adding anything together. In general it is better to add a 1 to  a smaller number, because that causes a bigger increase in logarithm, i.e. a larger percentage increase, than adding 1 to a big number.
There are four possible scenarios, ordered most to least preferable, for utilizing ones:

Adding one to a 2 gives +log .405  [log(3) - log(2)]
Combining ones into threes gives +log .366 per one  [log(3) / 3]
Making a 2 out of ones gives +log .347 per one  [log(2) / 2]
Adding one to a number 3 or higher gives +log .288 or less  [log(4) - log(3)]

The program keeps track of the number of ones, the number of twos, and the minimum number greater than 2, and goes down the list of the most to least preferable ways of using the ones. Finally, it multiplies all the remaining numbers.


Swap encoding iteration count Introduction
In this challenge, I asked you to implement swap encoding.
Swap encoding is an encoding method where you iterate through the string, reversing substrings between identical characters. The basic algorithm is:
For each character in the string:
Check: Does the string contain the character again, after the instance you found?
If so, then modify the string by reversing the section between the character and the next instance, inclusive.
Otherwise do nothing.
Example
Start with the string 'eat potatoes'.
e is found again, so reverse that section: eotatop taes
o is found again, so reverse that section (doing nothing as it is palindromic)
t is found again, so reverse that section (doing nothing as it is palindromic)
a is found again, so reverse that section: eotat potaes
t is found again, so reverse that section: eotatop taes
None of 'op taes' are found again, so eotatop taes is our final string!
Anyway, in this chat, @okie and I discussed what would happen if you repeatedly ran the swap algorithm on something until it returned to the original string. We managed to prove that it will always return.
Okay, that's a lot of preamble. Here's your challenge:
Write a program or function that takes a string as input, and returns the number of times it has to be swapped before it will return to itself.
Scoring
Answers will be timed on their combined score on all the scored testcases, so please append a snippet to your program that runs all the testcases one after another.
I will time all answers on all on my computer (2018 Macbook Air), although please link to a downloadable interpreter/compiler for less mainstream languages.
Here is my reference implementation.
Testcases
Simple testcases (Just to check it works):
1231 => 2
1234512345 => 6
123142523
Sandbox for Proposed Challenges => 1090
Collatz, Sort, Repeat => 51
Rob the King: Hexagonal Mazes => 144
Decompress a Sparse Matrix => 8610
14126453467324231 => 1412
12435114151241 - 288
Closest Binary Fraction => 242
Quote a rational number => 282
Solve the Alien Probe puzzle => 5598

Scored testcases (The ones I'm timing you on)
124351141512412435325 => 244129
Write a fast-growing assembly function => 1395376
And I'm now heading to the elevator => 207478
I'm in the now infamous elevator => 348112
1549827632458914598012734 => 1025264
i was always mediocre at golfing => 1232480
tho, i like some code challenges => 2759404
I am once again in an elevator => 1606256
A person with mannerism of cat => 867594

IMPORTANT
To make it fair, I have to time all programs under the same load on my computer. So if one person requests a retime, I have to retime them all. This means your time may fluctate.

C++ (gcc), 3.809 seconds

Compile with g++ -O3 -std=c++14.
As requested by the OP, the testcases were included in the source.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

constexpr int TESTCASES_NUM = 9;
constexpr char *TESTCASES[TESTCASES_NUM] = {"124351141512412435325", "Write a fast-growing assembly function", "And I'm now heading to the elevator", "I'm in the now infamous elevator", "1549827632458914598012734", "i was always mediocre at golfing", "tho, i like some code challenges", "I am once again in an elevator", "A person with mannerism of cat"};

int solve(char *s, int n) {
    int ans = 0;
    int i, j;
    char *p, *q, b;
    char s0[n];
    memcpy(s0, s, n);
    do {
        for(i = 0; i < n; ++i) {
            for(j = i + 1; j < n; ++j) {
                if(s[i] == s[j]) {
                    for(p = s + i + 1, q = s + j - 1; p < q; ++p, --q) {
                        b = *p;
                        *p = *q;
                        *q = b;
                    }
                    break;
                }
            }
        }
        ++ans;
    } while (memcmp(s0, s, n));
    return ans;
}

int main(int argc, char **argv) {
    for(int t = 0; t < TESTCASES_NUM; ++t) {
        char* s = TESTCASES[t];
        int  n = strlen(s);

        int count[300];
        memset(count, 0, sizeof(count));
        for(int i = 0; i < n; ++i) {
            ++count[s[i]];
        }
        char z[n];
        int m = 0;
        for(int i = 0; i < n; ++i) {
            if(count[s[i]] == 1) {
                if(i > 1 and count[s[i - 1]] == 1 and count[s[i - 2]] == 1) {
                    continue;
                }
            }
            if(i > 1 and s[i] == s[i - 2] and count[s[i - 1]] == 1) {
                --m;
                continue;
            }
            if(m == 0 and count[s[i]] == 0) {
                continue;
            }
            z[m++] = s[i];
        }
        while(m > 1 and count[z[m - 1]] == 1) {
            --m;
        }

        printf("%d\n", solve(z, m));
    }
}

Try it online!
The naive implementation, with a couple of preprocessing optimizations.
Say that a character is unique if it occurs exactly once in the input string.

If there are more than 2 consecutive unique characters, we can remove some of them until there are exactly 2 consecutive ones.
We can remove every prefix or suffix consisting entirely of unique characters.
We can make substitutions aba -> a whenever b is unique (thanks to kops for the suggestion!).


Visualize Nicomachus's Theorem Nichomachus's Theorem relates the square of a sum to the sum of cubes:

and has a beautiful geometric visualization:

Challenge: Create the 2d part of this visualization in ascii.

You will need to ensure that all visual demarcations are upheld by your diagram.  This is simplest to do with four "colors," though it's possible to achieve with only three (see last example below for how).  With four colors, you use two to distinguish between regions within a "strip" (ie, the different parts that make up a single cube), and two to distinguish between adjacent strips.  You may also use more than four colors if you like.  If any of this is confusing, the example output below should clarify.

Input / Output

Input is a single integer greater than 0.  Output is an ascii grid similar to the examples below, corresponding to the flattened grid for that input number in the image above.  Leading and trailing whitespace are ok.

This is code golf, with standard rules.

Sample outputs

N = 1

#

N = 2

#oo
o@@
o@@

N = 3

#oo+++
o@@+++
o@@+++
+++###
+++###
+++###

N = 4

#oo+++oooo
o@@+++oooo
o@@+++@@@@
+++###@@@@
+++###@@@@
+++###@@@@
oo@@@@oooo
oo@@@@oooo
oo@@@@oooo
oo@@@@oooo

N = 5

#oo+++oooo+++++
o@@+++oooo+++++
o@@+++@@@@+++++
+++###@@@@+++++
+++###@@@@+++++
+++###@@@@#####
oo@@@@oooo#####
oo@@@@oooo#####
oo@@@@oooo#####
oo@@@@oooo#####
+++++#####+++++
+++++#####+++++
+++++#####+++++
+++++#####+++++
+++++#####+++++

Three color version for N = 4, thanks to @BruceForte:

#oo+++oooo
o##+++oooo
o##+++####
+++ooo####
+++ooo####
+++ooo####
oo####++++
oo####++++
oo####++++
oo####++++

MATL, 30 28 27 bytes

t:P"@:s:@/Xk&+@+8MPt&(]30+c

Try it online!

Bonus features:

For 26 bytes, the following modified version produces graphical output:

t:P"@:s:@/Xk&+@+8MPt&(]1YG

Try it at MATL Online!
The image is begging for some colour, and it only costs 7 bytes:

t:P"@:s:@/Xk&+@+8MPt&(]1YG59Y02ZG

Try it at MATL Online!
Or use a longer version (37 bytes) to see how the character matrix is gradually built:

t:P"@:s:@/Xk&+@+8MPt&(t30+cD9&Xx]30+c

Try it at MATL Online!

Example outputs

For input is 8, the following shows the basic version, graphical output, and colour graphical output.

Explanation

General procedure

A numeric matrix is built from outer to inner layers in N steps, where N is the input. Each step overwrittes an inner (upper-left) part of the previous matrix. At the end, the numbers in the obtained matrix are changed to characters.

Example

For input 4 the first matrix is

10 10  9  9  9  9  8  8  8  8
10 10  9  9  9  9  8  8  8  8
 9  9  8  8  8  8  7  7  7  7
 9  9  8  8  8  8  7  7  7  7
 9  9  8  8  8  8  7  7  7  7
 9  9  8  8  8  8  7  7  7  7
 8  8  7  7  7  7  6  6  6  6
 8  8  7  7  7  7  6  6  6  6
 8  8  7  7  7  7  6  6  6  6
 8  8  7  7  7  7  6  6  6  6

As a second step, the matrix

7 7 7 6 6 6
7 7 7 6 6 6
7 7 7 6 6 6
6 6 6 5 5 5
6 6 6 5 5 5
6 6 6 5 5 5

is overwritten into the upper half of the latter. Then the same is done with

6 5 5
5 4 4
5 4 4

and finally with

3

The resulting matrix is

3 5 5 6 6 6 8 8 8 8
5 4 4 6 6 6 8 8 8 8
5 4 4 6 6 6 7 7 7 7
6 6 6 5 5 5 7 7 7 7
6 6 6 5 5 5 7 7 7 7
6 6 6 5 5 5 7 7 7 7
8 8 7 7 7 7 6 6 6 6
8 8 7 7 7 7 6 6 6 6
8 8 7 7 7 7 6 6 6 6
8 8 7 7 7 7 6 6 6 6

Lastly, 30 is added to each entry and the resulting numbers are interpreted as codepoints and converted to characters (thus starting at 33, corresponding to !).

Construction of the intermediate matrices

For input N, consider decreasing values of k from N to 1. For each k, a vector of integers from 1 to k*(k+1) is generated, and then each entry is divided by k and rounded up. As an example, for k=4 this gives (all blocks have size k except the last):

1 1 1 1 2 2 2 2 3 3

whereas for k=3 the result would be (all blocks have size k):

1 1 1 2 2 2

This vector is added, element-wise with broadcast, to a transposed copy of itself; and then k is added to each entry. For k=4 this gives

6  6  6  6  7  7  7  7  8  8
6  6  6  6  7  7  7  7  8  8
6  6  6  6  7  7  7  7  8  8
6  6  6  6  7  7  7  7  8  8
7  7  7  7  8  8  8  8  9  9
7  7  7  7  8  8  8  8  9  9
7  7  7  7  8  8  8  8  9  9
7  7  7  7  8  8  8  8  9  9
8  8  8  8  9  9  9  9 10 10
8  8  8  8  9  9  9  9 10 10

This is one of the intermediate matrices shown above, except that it is flipped horizontally and vertically. So all that remains is to flip this matrix and write it into the upper-left corner of the "accumulated" matrix so far, initiallized to an empty matrix for the first (k=N) step.

Code

t       % Implicitly input N. Duplicate. The first copy of N serves as the
        % initial state of the "accumulated" matrix (size 1×1). This will be
        % extended to size N*(N+1)/2 × N*(N+1)/2 in the first iteration
 :P     % Range and flip: generates vector [N, N-1, ..., 1]
"       % For each k in that vector
  @:    %   Push vector [1, 2, ..., k]
  s     %   Sum of this vector. This gives 1+2+···+k = k*(k+1)/2
  :     %   Range: gives vector [1, 2, ..., k*(k+1)/2]
  @/    %   Divide each entry by k
  Xk    %   Round up
  &+    %   Add vector to itself transposed, element-wise with broadcast. Gives
        %   a square matrix of size k*(k+1)/2 × k*(k+1)/2
  @+    %   Add k to each entry of the this matrix. This is the flipped
        %   intermediate matrix
  8M    %   Push vector [1, 2, ..., k*(k+1)/2] again
  Pt    %   Flip and duplicate. The two resulting, equal vectors are the row and
        %   column indices where the generated matrix will be written. Note that
        %   flipping the indices has the same effect as flipping the matrix
        %   horizontally and vertically (but it's shorter)
  &(    %   Write the (flipped) intermediate matrix into the upper-left
        %   corner of the accumulated matrix, as given by the two (flipped)
        %   index vectors
]       % End
30+     % Add 30 to each entry of the final accumulated matrix
c       % Convert to char. Implicitly display


Catch some drug dealers (spoilers on decade-old TV show below)

In the HBO show "The Wire", the dealers use a system of encoding phone numbers where they "jump the 5" on the number pad.

+-----------+
| 1 | 2 | 3 |
+-----------+
| 4 | 5 | 6 |
+-----------+
| 7 | 8 | 9 |
+-----------+
| # | 0 | * |
+-----------+

A "1" becomes a "9", "4" becomes "6", etc ... and "5" and "0" swap places.  So, the input number 2983794-07 becomes 8127316-53.  # and * are undefined.  Input in the show was numeric with a dash, your code does not need to preserve the dash but it does need to accept it.  No real restrictions on how user interaction is handled, can be a function or console application as needed.

Scoring criteria:

This is a code golf, fewest characters wins.  There is a 100 character penalty for solving it with a number/character swap or array lookup (I'm trying to broadly paint a brush stroke to avoid "9876043215"[i]-style lookups).  10 character bonus for not stripping dashes.

MATLAB, 25 bytes
Function accepting a string.
- is converted to =... so the dash is not just preserved, there is twice as much of it?
@(n)106-n-5*(n==48|n==53)


Optimizing edge selection from a list of numbers You are given a list, L, with the length N. L contains N random positive integer values. You are only able to select from the outer edges of the list (left/right), and after each selection every value in the remaining list increase by a factor of the current selection. The goal is to maximize the total sum of the selection you make until the list is empty.

An example of L where N = 3, [1,10,2].

Starting list [1,10,2], factor = 1.

Chosen path left

New list [10 * factor, 2 * factor] => [20, 4], where factor = 2

Chosen path right

New list [10 * factor] => [30], where factor = 3

Total value = 1 + 4 + 30 => 35.

Output: should be the total sum of all selections, and the list of all the directions taken to get there. 35 (left, right, left). Keep in mind that the the most important part is the total sum. There may exist more than one path that leads to the same total sum, for example 35 (left, right, right).

Test case 1

[3,1,3,1,1,1,1,1,9,9,9,9,2,1] => 527

(right left left left left left left left left right left left left left)

Test case 2

[1,1,4,1,10,3,1,2,10,10,4,10,1,1] => 587

(right left left right left left left left left left right right left right)

Rules

This is code-golf, shortest codes in bytes win.

Standard loopholes are forbidden.

k, 48 43 38 bytes

-5 bytes thanks to ngn.

{a@*>*+a:x{(+/x*1+<y*|!#x;y)}/:+!2|-x}

Try it online! It simply tries all possibilities, and chooses the first one with the maximum value. Left/right encoded as 0/1.

{                                    } /functions accepts x
                               +!2|-x  /all possible selections
          { +/x*1+<y*|!#x   }          /calculate the total sum
           (             ;y)           /also record the selection with each sum
         x                   /:        /map over all selections
 a@*>*+a:                              /choose the one with max total sum

This can probably be golfed further.


That's a prime... almost If you've ever learned about primes in math class, you've probably have had to, at one point, determine if a number is prime. You've probably messed up while you were still learning them, for example, mistaking 39 for a prime. Well, not to worry, as 39 is a semiprime, i.e., that it is the product of two primes.

Similarly, we can define a k-almost prime as being the product of k prime numbers. For example, 40 is the 4th 4-almost prime; 40 = 5*2*2*2, the product of 4 factors.

Your task is to write a program/function that accepts two integers n and k as input and output/return the nth k-almost prime number. This is a code-golf, so the shortest program in bytes wins.

Test cases

n, k => output
n, 1 => the nth prime number
1, 1 => 2
3, 1 => 5
1, 2 => 4
3, 2 => 9
5, 3 => 27

Miscellaneous

You have to generate the primes yourself by any means other than a simple closed form, if such a closed form exists.

Pyth, 9 bytes
e.fqlPZQE

Explanation
          - autoassign Q = eval(input())
     PZ   -      prime_factors(Z)
    l     -     len(^)
   q   Q  -    ^ == Q
 .f     E -  first eval(input()) of (^ for Z in range(inf))
e         - ^[-1]

Try it here!
Or try a test suite!


Maths Metagolf Mania! Mathemania Specs:

Every piece of Mathemania code starts off with the number 2. From the 2, you can do the following operations:

e: Exponentiation. This command's default is squaring the number.
f: Factorial. This command's default is using the single factorial on the number (using f on 2 = 2! = 2).
r: Root. This command's default is square-rooting the number.
c: Ceiling function.
l: Floor function.

To generate a number in Mathemania, you must string together these commands, which are performed left-to-right on the number 2.

Examples:

ef = (2^2)! = 4! = 24
rl = floor(sqrt(2)) = floor(1.4...) = 1
er = sqrt(2^2) = sqrt(4) = 2
efrrc = ceil(sqrt(sqrt((2^2)!)))
      = ceil(sqrt(sqrt(24)))
      = ceil(sqrt(4.89...))
      = ceil(2.21...)
      = 3

The e, f and r commands can be altered by extra Mathemania commands (which also start off with 2 as its "base" number) to generate different exponentiations, factorials and roots by placing brackets after the altered function and placing the Mathemania commands inside it.

For example, to cube a number instead of squaring it, you can put the command for 3 after e like so:

e(efrrc) -> cube a number, "efrrc" = 3

NOTE: for our purpose, the factorial command (f) start off with 2 as a single factorial. So if you do f(efrrc), that will get evaluated to a double factorial, not a triple factorial.

For n-factorials (e.g. double factorials = 2-factorial, triple factorial = 3-factorial etc.), the base number is multiplied by the number that is n less than it, and n less than that, and so on until the final number cannot be subtracted by n without becoming 0 or negative.

For example:

7!! = 7 * 5 * 3 * 1 = 105 (repeatedly subtract 2, 1 is the last term as
                           1 - 2 = -1, which is negative)
9!!! = 9 * 6 * 3 = 162 (repeatedly subtract 3, 3 is the last term as
                        3 - 3 = 0, which is 0)

For more information, see here.

You can insert it anywhere, and it will get treated by Mathemania as a single function:

e(efrrc)rc = ceil(sqrt(2^3))
           = ceil(2.82...)
           = 3

You're also allowed to nest these inside one another:

e(e(e)) = e(4th power)
        = (2^4)th power
        = 16th power

For an interpreter of Mathemania code, click here (cheers, @BradGilbertb2gills!)

Task:

Your task is to create a program that, when given a positive integer n as input, generates a Mathemania program that when executed, returns n.

However, the Mathemania programs that you generate must be as small (golfed) as possible, and your final score is determined by the sum of the number of bytes in the generated Mathemania programs of the sample, which are the integers 10,000 to 10,100. The lowest score wins.

Rules and specs:

Your program must output a valid Mathemania program for any positive integer, but only the numbers between 10,000 and 10,100 will be tested.
You are not allowed to output Mathemania programs that do not result in an integer. If you do so, your program is disqualified.
For the commands e, f and r, the Mathemania code inside those functions (e.g. e(efrrc), where the efrrc is the code inside the function) must evaluate to a positive integer above 2. If your program doesn't follow this rule, it is disqualified as well.
Your program must return a Mathemania program for any one of the 101 test integers in at most 30 minutes on a modern laptop.
Your program must return the same solution for any integer every time it is run. For example, when a program is given an input 5 and it outputs efrc, it must output that every time the input 5 is given.
You may not hard-code any solutions for any positive integer.
In order to fully maximise golfing potential in your output, your program should be able to handle arbitrarily large integers. It is not a requirement, though good luck if your language doesn't support this.

This is metagolf, so lowest score wins!

Python 3.5, Score of ??

As of now I don't have the output for all 101 inputs, but once I run the program for all the test cases I will update with my score.

from math import *

memoized = {}
same = {}

def _(mathmania, n):
    memoized[n] = mathmania
    return mathmania

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False
    for divisor in range(3, int(sqrt(n)) + 1, 2):
        if n % divisor == 0:
            return False
    return True

def pair_key(pair):
    low, high = pair
    diff = high - low
    if diff == 0:
        return 100
    low_done, high_done, diff_done = low in memoized, high in memoized, diff in memoized
    if high_done and memoized[high] == None or low_done and memoized[low] == None:
        return -1
    return (high_done + diff_done + (diff + 1 == low)) * 33 + low / high

def major_pairs(n):
    for i in range(n, int(sqrt(n)), -1):
        d = n / i
        if i - d < d - 1:
            break
        if d == int(d):
            yield (int(d), i)

def fact_key(pair):
    i, f = pair
    if i in memoized:
        if memoized[i] == None:
            return -1
        return 1
    return i / f

def near_fact(n, level):
    s = 4
    if n in same:
        s = same[n]
    for i in range(s, n ** 2 ** level):
        f = factorial(i)
        if f > (n - 1) ** 2 ** level:
            if f < (n + 1) ** 2 ** level:
                same[n] = i
                yield (i, f)
            else:
                return

def generate_mathmania(n):
    if n in memoized and memoized[n] != None:
        return memoized[n]
    memoized[n] = None
    binx = log(n, 2)
    if binx == int(binx):
        if binx == 2:
            return _("e", n)
        if binx == 1:
            return _("er", n)
        if binx == 0:
            return _("rl", n)
        return _("e(" + generate_mathmania(int(binx)) + ")", n)
    sq = sqrt(n)
    if sq == int(sq):
        return _(generate_mathmania(int(sq)) + "e", n)
    low, high = max(major_pairs(n), key=pair_key)
    if pair_key((low, high)) == -1:
        level = 1
        while True:
            try:
                i, f = max(near_fact(n, level), key=fact_key)
            except:
                level += 1
                continue
            if fact_key((i, f)) == -1:
                return _(generate_mathmania((n - 1) ** 2 + 1) + "rc", n)
            if f == n ** 2 ** level:
                return _(generate_mathmania(i) + "f" + "r" * level, n)
            if f < n ** 2 ** level:
                return _(generate_mathmania(i) + "f" + "r" * level + "c", n)
            return _(generate_mathmania(i) + "f" + "r" * level + "l", n)
    if low != 1:
        if low == high:
            return _(generate_mathmania(low) + "e", n)
        if high - low == 1:
            return _(generate_mathmania(high) + "f", n)
        return _(generate_mathmania(high) + "f(" + generate_mathmania(high - low + 1) + ")", n)
    good = None
    for i in range(n ** 2 - 1, (n - 1) ** 2, -1):
        if i in memoized:
            return _(generate_mathmania(i) + "rc", n)
        if not is_prime(i):
            good = i
    if good:
        return _(generate_mathmania(good) + "rc", n)
    for i in range((n + 1) ** 2 - 1, n ** 2, -1):
        if i in memoized:
            return _(generate_mathmania(i) + "rl", n)
        if not is_prime(i):
            good = i
    if good:
        return _(generate_mathmania(good) + "rl", n)
    return _(generate_mathmania((n - 1) ** 2 + 1), n)

Additionally, I was unable to verify the outputs of some of the test cases I tried due to sheer number size, and at that point @BradGilbertb2gills's online interpreter times out. Hopefully all the outputs work.


Sourcecode combinatorics Objective:

  The task is to create two programs using the same or different
  programming languages. The sourcecodes will be combined in two
  different ways and the resulting sourcecodes can be in any programming
  languages. The four programs (original two + the two combinations)
  should output different things.

Rules:

Your programs (all four) should not take any input (from user, filename, network or anything).
The first program should output exactly Hello, nothing else.
The second program should output exactly world, nothing else.
The first combinated program should output Hello human!, nothing else.
The second combinated program should output Hello computer!, nothing else.

Here is how the two combinated programs may be created:

First combined program:

Choose two numbers (equal or different) between 1 and 6 (that is: 2, 3, 4 or 5), the two numbers are called: n1 and n2.
Copy n1 number of characters from the first program and paste into the combined sourcecode
Copy n1 number of characters from the second program and paste into the combined sourcecode
Copy n2 number of characters from the first program and paste into the combined sourcecode
Copy n2 number of characters from the second program and paste into the combined sourcecode
Next, start over copy n1 number of characters again and so on. Copy from start to end from the sourcecodes, paste from start to end into the combined sourcecode.

Second combined program:

The sourcecode is the reverse of the first combined program sourcecode above. You may replace up to 3 characters at any place afterwards (optional). You can replace the up to 3 characters with any other characters. Replacing means 1 char for 1 char at up to 3 different positions on the sourcecode. The final sourcecode size in characters should therefor be exactly the same size as the first combined program size.

Example creating the combinated programs using numbers 3 and 4:

            First program:    {'Hello'}:p
           Second program:    /*         */ console.log ("World");
 First combinated program:    {'H/* ello    '}:   */ console.log ("World");
Second combinated program:    ;)"dlroW"( gol.elosnoc /*   :}'    olle */H'}

Be sure to declare all four programming languages that you use (even if they are all the same) and what numbers you have used when creating the first combinated sourcecode.

This is code-golf, shortest code in bytes for the two sourcecodes wins! Good luck, have fun!


Big code... for you! At the opening scene of the Dark Knight rises, there is a rather awkward dialogue between a CIA agent and the villain Bane.

CIA agent: “If I pull that [mask] off, will you die?”
Bane: “It would be extremely painful…”
CIA agent: “You’re a big guy.”
Bane: “…for you.”

It’s unsure if Bane intends to say “painful for you” or “big guy for you”. Let’s settle this problem once for all through code golfing!
Challenge
Your task is write a program that reorders the above dialogue depending on an integer given as input.
CIA agent dialogue words are:
If I pull that off will you die? You're a big guy.
Bane’s dialogue words are:
It would be extremely painful... for you!
Please note that die?, You’re, painful... and you! are considered as single words.

Given an integer n as input, convert it to binary
Reading the binary digits from left to right, output the next word from CIA agent dialogue if the digit is 1, and the next word from Bane dialogue if the digit is 0. The words should be separated by a space.
When the speaker changes, add a line feed. Also, prefix each dialogue line with the speaker name (BANE:  or CIA: ).

You can assume that the input always starts with a 1 in binary form, and has 12 ones and 7 zeroes.
Example
522300

Converted to binary: 1111111100000111100

The number starts with 8 ones, so we output the 8 first words from CIA’s agent dialogue, and prefix them with CIA:
CIA: If I pull that off will you die?

Then we got 5 zeroes, so we get the 5 first words from Bane’s dialogue:
BANE: It would be extremely painful...

Then there are 4 ones, so we output the 4 next CIA words:
CIA: You’re a big guy.

Then 2 zeroes:
BANE: for you!

Final result:
CIA: If I pull that off will you die?
BANE: It would be extremely painful...
CIA: You’re a big guy.
BANE: for you!

More test cases:
494542
CIA: If I pull that
BANE: It would be
CIA: off
BANE: extremely
CIA: will you die? You're
BANE: painful... for
CIA: a big guy.
BANE: you!

326711
CIA: If
BANE: It would
CIA: I pull that off will you
BANE: be extremely painful... for
CIA: die? You're
BANE: you!
CIA: a big guy.

Pyth - 138 bytes
I should look into compressing the movie script.
K_cc"guy big a You're die? you will off that pull I If you! for painful... extremely be would That"d12jmj;++@c"BANECIA"4ed\:m.)@Kedhdr8jQ2

Test Suite.


Create a pointer sequence Lets define a pointer sequence to be any sequence such that a(n) = a((n-1)-(a(n-1))) forall n greater than some finite number.  For example if our sequence begun with

3 2 1

Our next term would be 2, because a(n-1) = 1, (n-1)-1 = 1, a(1) = 2 (this example is zero index however it does not matter what index you use the calculation will always be the same.).  If we repeat the process we get the infinite sequence

3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2

Task

Given some initial array of positive integers output the pointer sequence starting with that array.

Output types

Output is intended to be flexible, if you choose to write a function as your program it can return, either an infinite list of integers or a function that indexes the sequence.  If you choose to write a full program you may output terms of the sequence indefinitely.

You may also choose to take two inputs, the starting array and an index.  If you choose to do this you need only output the term of the sequence at that index.

You will never be given a sequence that requires indexing before the beginning of the sequence.  For example 3 is not a valid input because you would need terms before the 3 to resolve the next term.

This is code-golf so your score will be the number of bytes in your program with a lower score being better.

Test Cases

test cases are truncated for simplicity

2 1   -> 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 ...
2 3 1 -> 2 3 1 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ...
3 3 1 -> 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 ...
4 3 1 -> 4 3 1 3 4 4 3 3 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 ...

JavaScript (ES6), 25 bytes

a=>f=n=>a[n]||f(--n-f(n))

An anonymous function that, when called, creates a function f that gives the item at a given index in the sequence.

Please let me know if I misunderstood anything...


Convert a number to Korean Goal

You will be given a positive integer number less than 10^20. You must convert it to Korean.

For example, if the input is 12345, the output should be 일만이천삼백사십오.

Technical details (Small)

Let's starts with simple numbers.

// 1 - 9
1 -> 일
2 -> 이
3 -> 삼
4 -> 사
5 -> 오
6 -> 육
7 -> 칠
8 -> 팔
9 -> 구

// 10, 100, 1000
10 -> 십
100 -> 백
1000 -> 천

You can concatenate 2 ~ 9 front of 10, 100, 1000.
However, you should not concatenate 1 front of 10, 100, 1000.

// 20 = 2 * 10
20 -> 이십

// 300 = 3 * 100
300 -> 삼백

// 9000 = 9 * 1000
9000 -> 구천

// 1000 is just 1000
1000 -> 천

For integer less than 10000, below rule is used for pronunciation.

// 1234 = 1000 + 200 + 30 + 4
1234 -> 천이백삼십사

// 1002 = 1000 + 2
1002 -> 천이

// 2048 = 2000 + 40 + 8
2048 -> 이천사십팔

// 510 = 500 + 10
510 -> 오백십

// 13 = 10 + 3
13 -> 십삼

Technical details (Large)

Now let's go to the hard part.

First, you need to know some parts used in larger numbers:

1 0000 -> 만
1 0000 0000 -> 억
1 0000 0000 0000 -> 조
1 0000 0000 0000 0000 -> 경

When Koreans pronounce big numbers

Cut it with width 4
Convert each of them using methods for less than 10000
Combine them with default form of big numbers

Here is some detailed examples. (I added some space to korean for readability)

// 12345678 = 1234 5678
// 1234 -> 천이백삼십사
// 5678 -> 오천육백칠십팔
12345678 -> 천이백삼십사 만 오천육백칠십팔

// 11122223333 = 111 2222 3333
// 111 -> 백십일
// 2222 -> 이천이백이십이
// 3333 -> 삼천삼백삼십삼
11122223333 -> 백십일 억 이천이백이십이 만 삼천삼백삼십삼

// 10900000014 = 109 0000 0014
// 109 -> 백구
// 0000 -> (None)
// 0014 -> 십사
10900000014 -> 백구 억 십사

// 100000000 -> 1 0000 0000
// 1 -> 일
// 0000 -> (None)
// 0000 -> (None)
100000000 -> 일 억

Here are some more examples.

Rule

You can make your program gets input from stdin and output to stdout, or make a function that gets string/integer and returns string.

This is code-golf, so answers will be scored in bytes with fewer bytes being better.

Aheui, 1555 bytes

살밦발따밝따빠따밦발다빠따다빠밞빠따받다빠따밝발따두
수터더떠벋벓떠뻐더벖떠뻐벍뻐터터떠벌벖떠뻐떠벋벎뻐더
방뺘우차빠발발다빠따빠뚜
우노여뗘뻐떠뻐더벌벌썪러
샦우싹어
아삳부
ㅇ아삭뺘우차빠불
ㅇ유어우여려더벌
ㅇ요ㅇ빠받반타탸우처삳뺘우처밝밤뚜
ㅇㅇ우쑨여텨여볋여뗘여뼈여뎌벅떠벓
ㅇ요아삭뺘우차삳빠박탸유처발불
ㅇㅇ우어ㅇ여따뱖볆뚜텨벎떠뻐떠
ㅇ요ㅇ우어쎤여뎌여별여어
ㅇㅇㅇ빠밤탸우처밣빠따밞다뿌
ㅇ요ㅇ우어쎤여뗘벎더떠벋벓떠
ㅇㅇㅇ빠밦탸우처밞밦따빠뚜
ㅇ뇨ㅇ숙어쎤여뗘벎떠벅터벖
ㅇㅇㅇ빠박탸우처밝밤따밣따북
ㅇ됴ㅇ우어썬여텨더벓벓떠뻐더
ㅇㅇㅇ빠받탸우처밣밝다빠따붇
ㅇ뵬ㅇ우어썬여뎌떠벍벓떠뻐터
ㅇㅇㅇ빠밤탸우처밣밝다빠따붇
ㅇ뵬ㅇ우어썬여뎌떠벌벓떠뻐터
ㅇㅇㅇ빠발탸우처밣밝다빠따뿌
ㅇ묘ㅇ우어썬여뎌떠벎더벌벖떠
ㅇㅇㅇ빠밦탸우처밣밝다빠따빠뚜
ㅇ쇽ㅇ우어썬여뎌떠벓더벓떠뻐벖
ㅇㅇㅇ빠밝탸우처밞밞따빠따붒
ㅇ됴ㅇ우어썬여뗘벓더더벍떠뻐
ㅇㅇㅇ빠밣탸우처발발따발따붒
ㅇ뵥ㅇ우어썬여뗘벎더범떠벓떠
ㅇㅇㅇ빠밟탸우처밝발따빠따붏
ㅇ숃어어어쎤여뎌벓떠벎떠범더
ㅇ마샬우싹샥우파뺘무차파쑨
ㅇㅇ오유여어유여ㅇ며ㅇㅇ우
오ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ어
우ㅇㅇ어ㅇㅇ어어
샨희맣어

Try it online! (trailing new line for input is necessary)

Why not?

Hours of coding, and another hours of packing and layouting. I think it can be golfed furthermore, but it already took so much effort. I really wanted  to pack it into a rectangle.

Because 10^20 is larger than 2^64, not every implementation of Aheui will not support 경-scale numbers.
Luckily, Python and pyaheui implementation (which is used on  TIO) uses much-larger precision numbers, so it can support not only 경, but more than 해, 자, 양, 구, 간, 정, 재, 극.
And my code can be easily extended to use more larger unit suffixes.

This code will not terminate on input 0, but this spec was not defined in the question (which should output 영).

Explanation-ish Unpacked Code

ㅣPush unit suffixes (만, 억, 조, 경) to stack ㄹ
ㅣ
술
밦발따밝따빠따밦발다우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠따다빠밞빠따받다빠따밝발따다다우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠밞받따빠따밦발따타타우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
빠밝빠따밦다빠따밣받따다타우
우ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣ
ㅣGet input as number
ㅣ
사방우
우ㅡ어
ㅣ
ㅣSplit input by four digits
ㅣ
ㅣㅣIf input is zero, end the loop
아아뺘우차우
우ㅇㅡ어　ㅣ
ㅣㅣ우ㅡㅡ어
ㅣㅣㅣTake mod 10000 to stack ㄲ
ㅣㅣ빠발발다빠따빠따라싺우
ㅣㅣ우ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣDivide by 10000
ㅣㅣ발발다빠따빠따나우
ㅣ오ㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣ
ㅣReverse stack ㄲ to stack ㄱ
ㅣ
샦우싹어
우어
ㅣ
ㅣProcess four digits
ㅣ
아우ㅣUse ㄷ stack for index (0, 2, 4, 6)
ㅣ아삳바우
ㅣ우ㅡㅡ어
ㅣㅣ
ㅣㅣㅣConvert four digits into korean
ㅣ아아숙
ㅣㅣㅣㅣIf current multiplier is zero, escape
ㅣㅣㅣ뺘우차우
ㅣ우ㅇㅡ어　ㅣ
ㅣㅣㅣ우ㅡㅡ어
ㅣㅣㅣㅣTake mod 10
ㅣㅣㅣ빠발발다라우
ㅣㅣㅣ우ㅡㅡㅡㅡ어
ㅣㅣㅣㅣIf remainder - 1 is 0 (remainder is 1) and index is 0 (ones digit), push 일 on stack ㄴ
ㅣㅣㅣ빠받반타탸우처삳뺘우처밝밤따밣따박다빠따밣타싼우
ㅣㅣㅣ우ㅡㅡㅡㅡ어ㅡㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣIf remainder is not 0
ㅣㅣㅣ삭뺘우차우
ㅣㅣㅣ우ㅡ어　ㅣ
ㅣㅣㅣㅣ우ㅡㅡ어
ㅣㅣㅣㅣ숟
ㅣㅣㅣㅣㅣIf index is [2, 4, 6], push [십, 백, 천] on stack ㄴ
ㅣㅣㅣㅣ빠박탸우처발발따빠따밞타밞따밞따발다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밤탸우처밣빠따밞다빠따밣받따다밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밦탸우처밞밦따빠따밦타박따밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣㅣ
ㅣㅣㅣㅣㅣIf remainder is [2 ... 9], push [이 ... 구] on stack ㄴ
ㅣㅣㅣㅣ숙
ㅣㅣㅣㅣ빠박탸우처밝밤따밣따박다빠따밣밣다타싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠받탸우처밣밝다빠따받타빠따밣밝따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밤탸우처밣밝다빠따받타빠따밣발따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠발탸우처밣밝다빠따빠따밦발다밞따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밦탸우처밣밝다빠따빠따밦빠따밣다밣따다싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밝탸우처밞밞따빠따밦빠따밝다다밣따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밣탸우처발발따발따밦따밣따밤다밞따싼우
ㅣㅣㅣㅣ우ㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ빠밟탸우처밝발따빠따밣다밤따밞따밣다싼우
ㅣㅣㅣ우ㅡㅡㅡ어ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣㅣㅣ
ㅣㅣㅣㅣIncrease index, move onto next digit
ㅣㅣㅣ삳박다삭마발발다나우
ㅣㅣ오ㅡㅡㅡㅡㅡㅡㅡㅡㅡ어
ㅣㅣ
ㅣㅣㅣPop zero
ㅣ아무
ㅣㅣㅣ
ㅣㅣㅣㅣMove one suffix to stack ㄱ
ㅣㅣㅣㅣIf all suffix has been used, escape
ㅣㅣ아샬우싹삭우
ㅣ우ㅇㅡ어　　ㅣ
ㅣㅣㅣ우ㅡㅡㅡ어
ㅣㅣㅣㅣIf next multiplier is zero, discard next multiplier and suffix, then check next
ㅣㅣㅣㅣIf next multipler is not zero, move suffix to stack ㄴ and continue
ㅣㅣㅣㅣIf all multiplier has been processed, escape
ㅣㅣㅣ야우파뺘우차파싼우
오ㅇㅇㅡㅇㅡㅡㅇㅡㅡㅡ어
우어ㅇㅡ어ㅡㅡㅣ
ㅣㅡ오ㅡㅡ머머어
샨희맣어


Session-Saving Quine Inspired by this question.

Create a program that prompts the user to store some data, and when the program is quitting, spit out the program itself, except the session data changed.

The user then open the newly generated program, and can recall the data from the previous program.

Commands

KEY VALUE: sets session variable KEY to VALUE
*: clear all data
! KEY: delete KEY
? KEY: query KEY (if not exist: print nothing and move on)
otherwise, quit the program

Neither key or value cannot contain any spaces.
The newly generated program's filename must identify the version of the program, you can use dates or counters.

Example interaction:

 name test                    store name = test
                              data is now { name: test }
 0 1                          data is now { name: test, 0: 1 }
 ? name                       output: test
 ! 0                          delete 0
                              data is now { name: test }
 hello good world             data is now { name: test, hello: good }
                              the extra word "world" is ignored
 egiwiwegiuwe                 the "otherwise" case: quit program

The user opens the newly generated program

 ? name                       output: test
 name retest                  data is now { name: retest }
 *                            clear
                              data is now { }

Sample implementation: https://gist.github.com/1128876

Rules

You do not need to preserve comments or insignificant whitespaces in the quined program: just preserve the functionality and the data
You cannot use any external storage.
No cheating quines, like any other quine problems.
Shortest code wins.

D (419 chars)

enum c=q{string[string] m;import std.stdio;import std.array;void main(){foreach(string s;lines(stdin)){auto a=s.split;if(!a.length)goto e;switch(a[0]){case "*":m.clear;break;case "!":m.remove(a[1]);break;case "?":writeln(m.get(a[1],""));break;default:if(a.length<2){goto e;}m[a[0]]=a[1];}stdout.flush;}e:write("static this(){");foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v);write("}enum c=q{",c,"};mixin(c);");}};mixin(c);

formatted:

enum c=q{
    string[string] m;
    import std.stdio;
    import std.array;
    void main(){
        foreach(string s;lines(stdin)){
            auto a=s.split;
            if(!a.length)goto e;
            switch(a[0]){
                case "*":m.clear;break;
                case "!":m.remove(a[1]);break;
                case "?":writeln(m.get(a[1],""));break;
                default:if(a.length<2){goto e;}m[a[0]]=a[1];
            }
            stdout.flush;
        }
        e:write("static this(){");
        foreach(i,v;m)writef("m[`%s`]=`%s`;",i,v);
        write("}enum c=q{",c,"};mixin(c);");
    }
};mixin(c);

variant of my D quine

the * command relies on m.clear; to work correctly which it doesn't in dmd 2.52 (bug in the compiler)

the need for stdout.flush; depends whether auto flush is enabled (it isn't on my machine)


Tips for golfing in PHP What general tips do you have for golfing in PHP? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PHP (e.g. "remove comments" is not an answer). Please post one tip per answer.

Understand how variables and whitespace interact with PHP's language constructs.

In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace.

echo$v;, for example, is perfectly valid, as are return$v; and other similar constructs. These small reductions in whitespace can lead to a significant cumulative decrease in length.

Keep in mind, though, that variables before language constructs require a space after, as in the following example:

foreach($a AS$b){}

Because AS is a language construct, a space is not required before the variable $b, but if one were to omit the space before it, resulting in $aAS, this would be parsed as a variable name and lead to a syntax error.


Missing numbers in arithmetic sum Challenge

Giving a valid arithmetic sum with some missing numbers, output the full expression.

Example:

    1#3                 123
+   45#     =>     +    456
--------            --------
    579                 579

Input

Expression format can be an array ["1#3", "45#", "579"], a string "1#3+45#=579", or 3 inputs f("1#3","45#","579")

Output

Same as input
You don't need to output the result

Notes

The missing numbers are going to be represented using # or any other constant non-numeric character you want
Assume result wont have a missing number
Assume Input/Output consist in 2 terms and a final result
Assume both term > 0 and result >= 2
There might be multiple solutions. You can output anyone as long as the sum result match

Test Cases with possibly outputs (pretty format)

    #79                     879
+   44#         =>      +   444
--------                --------
    1323                   1323

    5#5                     555
+   3#3         =>      +   343
--------                --------
    898                     898

      #                       1
+     #         =>      +     1
--------                --------
      2                       2

    ###                     998
+   ###         =>      +     1     PD: there are a lot of possible outputs for this one
--------                --------
    999                     999

    123                     123
+     #         =>      +     1
--------                --------
    124                     124

      9                       9
+    #6         =>      +    46
--------                --------
     55                      55

    #123651                     1123651
+      #98#         =>      +      7981
------------                -----------
    1131632                     1131632

Standard code-golf rules apply

Brachylog, 22 16 bytes

{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t

Try it online!

-6 bytes thanks to @Fatelize

Explanation

{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t
{     }ᵐ²                   #   for each letter in each string
 Ṣ∧Ị∋                       #       if " " return a digit; else input
     |                      #
         ịᵐ                 #   cast each string to number
            k+              #   the sum of all but the last one
              ~t            #       is equal to the last one
           .                #   output that list