问:
Greek Conversion Golf

Introduction

You must create a function to convert Arabic numerals into Greek numerals. The input will be an integer less than 1000 and more than 0.

Algorithm

Split number into digits (e.g. 123 -> 1, 2, 3)

Take each digit, and change to character found in table below, for letter symbol or letter name, (e.g. 123 -> 1, 2, 3 -> ΡΚΓ or RhoKappaGamma).

Specifications

No built-in number-system conversion

Result must be capitalized as in example.

Input will be in base 10.

Test Cases

```<code>123 -> RhoKappaGamma or ΡΚΓ
8 -> Eta or Η
777 -> PsiOmicronZeta or ΨΟΖ
100 -> Rho or Ρ
606 -> ChiDiGamma or ΧϜ
</code>```

Table

```<code>Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8
</code>```

答:
Pyth, <s>49</s> <s>48</s> <s>46</s> 44 bytes

```<code>_s.b@+kNsYc3mC+913d-.iU25smXm17hT4Cd"KGO"17_
</code>```

Try it here.

Still working on shortening the function to generate the alphabet... and yes, the generator is longer than hardcoding the alphabet by 4 characters, but not in bytes.

```<code>_s.b@+kNsYc3[...]_
                 _  get input (implicit) and reverse
            [...]   generate "ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ" (see below)
          c3        split into 3 equal chunks
  .b                map over each input digit (as Y) and chunk (as N)...
     +kN            prepend empty string to N (to support digits of 0)
    @   sY          get the Yth element of the empty-string-plus-digits array
 s                  concatenate all the digits
_                   reverse again to put digits back in the right order
</code>```

Here's how the alphabet-generating function works. Let's take all the codepoints and subtract 913 (the smallest value):

```<code>0 1 2 3 4 75 5 6 7 8 9 10 11 12 13 14 15 71 16 18 19 20 21 22 23 24 79
</code>```

Now let's pull out the ones that don't fit the pattern:

```<code>0 1 2 3 4    5 6 7 8 9 10 11 12 13 14 15    16 18 19 20 21 22 23 24
          75                             71                         79
</code>```

Okay, so the strategy is forming: generate the range 0 to 24 (we'll deal with the missing 17 later), and then insert 75, 71, and 79 at the correct locations.

How can we insert the outliers? Pyth has an .interleave function that takes ex. [1,2,3] and [4,5,6] and results in [1,4,2,5,3,6]. We're going to have to add some placeholders, though, since obviously the outliers are far apart. Let's represent the placeholder with X:

```<code>0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
X X X X 75 X X X X X  X  X  X  X  X 71  X  X  X  X  X  X  X 79
</code>```

Right, so the bottom outlier array starts with four Xs. Can we group the outliers to each be preceded by four Xs and see what remains?

```<code>0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75 X X X X X  X [  four X  ]71  X  X  X [  four X  ]79
</code>```

Now we make another key observation: since 79 comes at the very end, there can be any number of Xs preceding it, and any number of Xs following it as well! This is because interleaving [1,2,3] and [4,5,6,7,8,9] results in [1,4,2,5,3,6,7,8,9]—note that the extra elements in the second array end up at the end, and since they're going to be removed anyway, we can safely allow that.

That means we can normalize this such that every outlier is preceding by four Xs and succeeded by 6:

```<code>0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75[   six X   ] [  four X  ]71[     six X      ] [four X]79[six X]
</code>```

Great! Now we can simply take the array [75, 71, 79], insert four placeholder values before each element and six after, and then interleave it with the range 0..24.

But wait, what happened to 17? Remember, the top line in all of these examples has been missing 17. We can simply remove the 17 after interleaving; but this leaves another delightfully evil possibility open. You guessed it—the placeholder value we've been referring to as X will be 17. This allows us to remove both the extraneous 17 and all the placeholder values in one fell swoop.

Finally! Here's the code used to implement this:

```<code>mC+913d-.iU25smXm17hT4Cd"KGO"17
              m         "KGO"    for each char in the string "KGO"...
                      Cd         take its ASCII value ("KGO" -> 75,71,79)
                m17hT            generate an 11-element array filled with 17
               X     4           replace the 5th element with the ASCII value ^^
             s                   concatenate all of these together
        .iU25                    interleave with range(25)
       -                     17  remove all the 17s
m     d                          for each value in the resulting array...
  +913                           add 913 (to get the real character value)
 C                               convert to character
</code>```

Title: Greek Conversion Golf

Body:
Pyth, <s>49</s> <s>48</s> <s>46</s> 44 bytes

_s.b@+kNsYc3mC+913d-.iU25smXm17hT4Cd"KGO"17_

Try it here.

Still working on shortening the function to generate the alphabet... and yes, the generator is longer than hardcoding the alphabet by 4 characters, but not in bytes.

_s.b@+kNsYc3[...]_
                 _  get input (implicit) and reverse
            [...]   generate "ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ" (see below)
          c3        split into 3 equal chunks
  .b                map over each input digit (as Y) and chunk (as N)...
     +kN            prepend empty string to N (to support digits of 0)
    @   sY          get the Yth element of the empty-string-plus-digits array
 s                  concatenate all the digits
_                   reverse again to put digits back in the right order

Here's how the alphabet-generating function works. Let's take all the codepoints and subtract 913 (the smallest value):

0 1 2 3 4 75 5 6 7 8 9 10 11 12 13 14 15 71 16 18 19 20 21 22 23 24 79

Now let's pull out the ones that don't fit the pattern:

0 1 2 3 4    5 6 7 8 9 10 11 12 13 14 15    16 18 19 20 21 22 23 24
          75                             71                         79

Okay, so the strategy is forming: generate the range 0 to 24 (we'll deal with the missing 17 later), and then insert 75, 71, and 79 at the correct locations.

How can we insert the outliers? Pyth has an .interleave function that takes ex. [1,2,3] and [4,5,6] and results in [1,4,2,5,3,6]. We're going to have to add some placeholders, though, since obviously the outliers are far apart. Let's represent the placeholder with X:

0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
X X X X 75 X X X X X  X  X  X  X  X 71  X  X  X  X  X  X  X 79

Right, so the bottom outlier array starts with four Xs. Can we group the outliers to each be preceded by four Xs and see what remains?

0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75 X X X X X  X [  four X  ]71  X  X  X [  four X  ]79

Now we make another key observation: since 79 comes at the very end, there can be any number of Xs preceding it, and any number of Xs following it as well! This is because interleaving [1,2,3] and [4,5,6,7,8,9] results in [1,4,2,5,3,6,7,8,9]—note that the extra elements in the second array end up at the end, and since they're going to be removed anyway, we can safely allow that.

That means we can normalize this such that every outlier is preceding by four Xs and succeeded by 6:

0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75[   six X   ] [  four X  ]71[     six X      ] [four X]79[six X]

Great! Now we can simply take the array [75, 71, 79], insert four placeholder values before each element and six after, and then interleave it with the range 0..24.

But wait, what happened to 17? Remember, the top line in all of these examples has been missing 17. We can simply remove the 17 after interleaving; but this leaves another delightfully evil possibility open. You guessed it—the placeholder value we've been referring to as X will be 17. This allows us to remove both the extraneous 17 and all the placeholder values in one fell swoop.

Finally! Here's the code used to implement this:

mC+913d-.iU25smXm17hT4Cd"KGO"17
              m         "KGO"    for each char in the string "KGO"...
                      Cd         take its ASCII value ("KGO" -> 75,71,79)
                m17hT            generate an 11-element array filled with 17
               X     4           replace the 5th element with the ASCII value ^^
             s                   concatenate all of these together
        .iU25                    interleave with range(25)
       -                     17  remove all the 17s
m     d                          for each value in the resulting array...
  +913                           add 913 (to get the real character value)
 C                               convert to character


答:
Julia, 138 bytes

f(x,d=digits(x))=reverse(join([d[i]>0?[["ΑΒΓΔΕϜΖΗΘ","ΙΚΛΜΝΞΟΠϘ","ΡΣΤΥΦΧΨΩϠ"][i]...][d[i]]:""for i=1:endof(d)]))
```

This is a function that accepts an integer and returns a string.

For each digit in the input in reversed order, we get the character corresponding to that digit from the appropriate string then combine the characters and reverse the result. For any digits that are 0, we simply use the empty string.

ContentLicense: CC BY-SA 3.0

Title: Greek Conversion Golf

Body:
Introduction

You must create a function to convert Arabic numerals into Greek numerals. The input will be an integer less than 1000 and more than 0.

Algorithm

Split number into digits (e.g. 123 -> 1, 2, 3)

Take each digit, and change to character found in table below, for letter symbol or letter name, (e.g. 123 -> 1, 2, 3 -> ΡΚΓ or RhoKappaGamma).

Specifications

No built-in number-system conversion

Result must be capitalized as in example.

Input will be in base 10.

Test Cases

```<code>123 -> RhoKappaGamma or ΡΚΓ
8 -> Eta or Η
777 -> PsiOmicronZeta or ΨΟΖ
100 -> Rho or Ρ
606 -> ChiDiGamma or ΧϜ
</code>```

Table

```<code>Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8
</code>```

Body:
Julia, 138 bytes

f(x,d=digits(x))=reverse(join([d[i]>0?[["ΑΒΓΔΕϜΖΗΘ","ΙΚΛΜΝΞΟΠϘ","ΡΣΤΥΦΧΨΩϠ"][i]...][d[i]]:""for i=1:endof(d)]))

This is a function that accepts an integer and returns a string.

For each digit in the input in reversed order, we get the character corresponding to that digit from the appropriate string then combine the characters and reverse the result. For any digits that are 0, we simply use the empty string.


答:
JavaScript (ES6), <s>120</s> 115 bytes

n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")
```

<p>Byte count is using UTF-8. It's 88 characters long. Input is a number.</p>

<h2>Test</h2>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var solution = n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")
var testCases = [ 123, 8, 777, 100, 606, 700, 803 ];
document.write("```"+testCases.map(c=>c+": "+solution(c)).join("\n"));```

Title: Greek Conversion Golf

Body:
JavaScript (ES6), <s>120</s> 115 bytes

n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")

Byte count is using UTF-8. It's 88 characters long. Input is a number.

Test

var solution = n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")
var testCases = [ 123, 8, 777, 100, 606, 700, 803 ];
document.write("<pre>"+testCases.map(c=>c+": "+solution(c)).join("\n"));


答:
Ruby, 134 bytes

Basic lookup dealie using modulus. It probably can be optimized somewhere, but Ruby won't coerce strings into integers the way Javascript can, haha

```<code>->n{((0<d=n/100)?"ΡΣΤΥΦΧΨΩϠ"[d-1]:"")+((0<d=n%100/10)?"ΙΚΛΜΝΞΟΠϘ"[d-1]:"")+((0<n%=10)?"ΑΒΓΔΕϜΖΗΘ"[n-1]:"")}
</code>```

Title: Greek Conversion Golf

Body:
Ruby, 134 bytes

Basic lookup dealie using modulus. It probably can be optimized somewhere, but Ruby won't coerce strings into integers the way Javascript can, haha

->n{((0<d=n/100)?"ΡΣΤΥΦΧΨΩϠ"[d-1]:"")+((0<d=n%100/10)?"ΙΚΛΜΝΞΟΠϘ"[d-1]:"")+((0<n%=10)?"ΑΒΓΔΕϜΖΗΘ"[n-1]:"")}


问:
Calculator that adds char values

Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```<code>Input
Hello World!

Output
1085
</code>```

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.

So I leave it as a bonus thing aswell.

The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```<code>q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
</code>```

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

答:
Factor, 3 bytes

```<code>sum
</code>```

Strings are sequences, arrays of char values. sum is basically 0 [ + ] reduce (or, equivalently, [ + ] foldl), so this sums the chars in a string.

Title: Calculator that adds char values

Body:
Factor, 3 bytes

sum

Strings are sequences, arrays of char values. sum is basically 0 [ + ] reduce (or, equivalently, [ + ] foldl), so this sums the chars in a string.


答:
Actually, 7 bytes

```<code>√K1|3@█
</code>```

Try it online!

Also for 7 bytes:

```<code>3,√K1|█
</code>```

Try it online!

This uses the same formula as in Dennis's Jelly answer.

Explanation:

```<code>√K1|3@█
√K       push ceil(sqrt(n))
  1|     bitwise-OR with 1
    3@█  x C 3
</code>```

Title: Sum the odd square numbers less than N

Body:
Write a program or function to output the sum of the odd square numbers (OEIS #A016754) less than an input n.

The first 44 numbers in the sequence are:

```<code>1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
</code>```

The formula for the sequence is a(n) = ( 2n + 1 ) ^ 2.

Notes

Your program's behaviour may be undefined for n < 1 (that is, all valid inputs are >= 1.)

Test cases

```<code>1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
</code>```

Body:
Actually, 7 bytes

√K1|3@█

Try it online!

Also for 7 bytes:

3,√K1|█

Try it online!

This uses the same formula as in Dennis's Jelly answer.

Explanation:

√K1|3@█
√K       push ceil(sqrt(n))
  1|     bitwise-OR with 1
    3@█  x C 3


问:
Driftsort an array
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

This is a code-golf, so the shortest program in bytes.

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

答:
Java 175

prints out the output as space separated values, or prints f for a falsey value.

```<code>void d(int[]a){String s;for(int v,w,x=-1,y,z=a.length;++x<z;){v=a[x];s=""+v;for(y=0;++y<z;v=w){w=a[(x+y)%z];if(v>w){s="f";break;}s+=" "+w;}if(y==z)break;}System.out.print(s);}
</code>```

goes through all the combinations of the array of integers until it finds the valid sequence or runs out of combinations. the array isn't modified, but instead the driftsorted sequence is stored as a space delimited string.

a bit more readable:

```<code>void driftsort(int[]array){
    String str;
    for(int previous,current,x=-1,y,len=array.length;++x<len;){
        previous=array[x];
        s=""+previous;
        for(y=0;++y<len;previous=current){
            current=array[(y+x)%len];
            if(previous>current){
                str="false";
                break;
            }
            str+=" "+current;
        }
        if(y==len)break;
    }
    System.out.print(str);
}
</code>```

try it online

Title: Driftsort an array

Body:
Java 175

prints out the output as space separated values, or prints f for a falsey value.

void d(int[]a){String s;for(int v,w,x=-1,y,z=a.length;++x<z;){v=a[x];s=""+v;for(y=0;++y<z;v=w){w=a[(x+y)%z];if(v>w){s="f";break;}s+=" "+w;}if(y==z)break;}System.out.print(s);}

goes through all the combinations of the array of integers until it finds the valid sequence or runs out of combinations. the array isn't modified, but instead the driftsorted sequence is stored as a space delimited string.

a bit more readable:

void driftsort(int[]array){
    String str;
    for(int previous,current,x=-1,y,len=array.length;++x<len;){
        previous=array[x];
        s=""+previous;
        for(y=0;++y<len;previous=current){
            current=array[(y+x)%len];
            if(previous>current){
                str="false";
                break;
            }
            str+=" "+current;
        }
        if(y==len)break;
    }
    System.out.print(str);
}

try it online


问:
Molecules to Atoms

The Challenge

Write a program that can break down an input chemical formula (see below), and output its respective atoms in the form element: atom-count.

Input

Sample input:

```<code>H2O
</code>```

Your input will always contain at least one element, but no more than ten. Your program should accept inputs that contain parentheses, which may be nested.

Elements in the strings will always match [A-Z][a-z]*, meaning they will always start with an uppercase letter. Numbers will always be single digits.

Output

Sample output (for the above input):

```<code>H: 2
O: 1
</code>```

Your output can be optionally followed by a newline.

Breaking Down Molecules

Numbers to the right of a set of parentheses are distributed to each element inside:

```<code>Mg(OH)2
</code>```

Should output:

```<code>Mg: 1
O: 2
H: 2
</code>```

The same principle applies to individual atoms:

```<code>O2
</code>```

Should output:

```<code>O: 2
</code>```

And also chaining:

```<code>Ba(NO2)2
</code>```

Should output:

```<code>Ba: 1
N: 2
O: 4
</code>```

Testcases

```<code>Ba(PO3)2
->
Ba: 1
P: 2
O: 6

C13H18O2
->
C: 13
H: 18
O: 2

K4(ON(SO3)2)2
->
K: 4
O: 14
N: 2
S: 4

(CH3)3COOC(CH3)3
->
C: 8
H: 18
O: 2

(C2H5)2NH
->
C: 4
H: 11
N: 1

Co3(Fe(CN)6)2
->
Co: 3
Fe: 2
C: 12
N: 12
</code>```

Scoreboard

For your score to appear on the board, it should be in this format:

```<code># Language, Score
</code>```

Or if you earned a bonus:

```<code># Language, Score (Bytes - Bonus%)
</code>```

function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58469,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Scores

	User	Language	Score

{{RANK}}	{{NAME}}	{{LANGUAGE}}	{{SCORE}}

```

Edit: Square brackets are no longer a part of the question. Any answers posted before 3AM UTC time, September 23, are safe and will not be affected by this change.

答:
Pip, <s>85</s> 77 + 1 = 78 bytes

Non-competing answer because it uses language features that are newer than the challenge. Takes the formula as a command-line argument, and uses the -n flag for proper output formatting.

```<code>Y(VaRl:`([A-Z][a-z]*)``"&"`R`\d+``X&`R`(?<=\d|")[("]``.&`l)u:UQyu.": ".Y_NyMu
</code>```

Try it online!

The main trick is to transform the formula via regex replacements into a Pip expression. This, when eval'd, will do the repetition and resolve parentheses for us. We then post-process a bit to get the atom counts and format everything correctly.

Ungolfed, with comments:

```<code>                         a is command-line arg (implicit)
l:`([A-Z][a-z]*)`        Regex matching element symbols
aR:l `"&"`               Replace each symbol in a with symbol wrapped in quotes
aR:`\d+` `X&`            Add X before each number
aR:`(?<=\d|")[("]` `.&`  Add . before ( or " if it's preceded by a digit or "
Y (Va)@l                 Eval result, findall matches of l, and yank resulting list into y
u:UQy                    Remove duplicates and store in u
u.": ".(_Ny M u)         Map function {a IN y} to u, returning list of element counts;
                           append this (with colon & space) itemwise to list of symbols
                         Print that list, newline-separated (implicit, -n flag)
</code>```

Here's how the input Co3(Fe(CN)6)2 is transformed:

```<code>Co3(Fe(CN)6)2
"Co"3("Fe"("C""N")6)2
"Co"X3("Fe"("C""N")X6)X2
"Co"X3.("Fe".("C"."N")X6)X2
CoCoCoFeCNCNCNCNCNCNFeCNCNCNCNCNCN
</code>```

Then:

```<code>["Co" "Co" "Co" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N"]
["Co" "Fe" "C" "N"]
[3 2 12 12]
["Co: 3" "Fe: 2" "C: 12" "N: 12"]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Molecules to Atoms

Body:
Pip, <s>85</s> 77 + 1 = 78 bytes

Non-competing answer because it uses language features that are newer than the challenge. Takes the formula as a command-line argument, and uses the -n flag for proper output formatting.

Y(VaRl:`([A-Z][a-z]*)``"&"`R`\d+``X&`R`(?<=\d|")[("]``.&`l)u:UQyu.": ".Y_NyMu

Try it online!

The main trick is to transform the formula via regex replacements into a Pip expression. This, when eval'd, will do the repetition and resolve parentheses for us. We then post-process a bit to get the atom counts and format everything correctly.

Ungolfed, with comments:

                         a is command-line arg (implicit)
l:`([A-Z][a-z]*)`        Regex matching element symbols
aR:l `"&"`               Replace each symbol in a with symbol wrapped in quotes
aR:`\d+` `X&`            Add X before each number
aR:`(?<=\d|")[("]` `.&`  Add . before ( or " if it's preceded by a digit or "
Y (Va)@l                 Eval result, findall matches of l, and yank resulting list into y
u:UQy                    Remove duplicates and store in u
u.": ".(_Ny M u)         Map function {a IN y} to u, returning list of element counts;
                           append this (with colon & space) itemwise to list of symbols
                         Print that list, newline-separated (implicit, -n flag)

Here's how the input Co3(Fe(CN)6)2 is transformed:

Co3(Fe(CN)6)2
"Co"3("Fe"("C""N")6)2
"Co"X3("Fe"("C""N")X6)X2
"Co"X3.("Fe".("C"."N")X6)X2
CoCoCoFeCNCNCNCNCNCNFeCNCNCNCNCNCN

Then:

["Co" "Co" "Co" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "Fe" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N" "C" "N"]
["Co" "Fe" "C" "N"]
[3 2 12 12]
["Co: 3" "Fe: 2" "C: 12" "N: 12"]


答:
Retina, 57 bytes

11 bytes saved thanks to @Martin Büttner.

Simple transliterate with appropriate character ranges and 0 deletion on each digit.

```<code>T`d`_ΡΣ-ΩϠ`.(?=..)
T`d`_Ι-ΠϘ`.\B
T`d`_Α-ΕϜΖ-Θ
</code>```

Try it online. (First line added to allow all testcases to run together.)

Martin also suggested this one for the same score:

```<code>T`d`_J-R`.(?=..)
T`d`_L`.\B
T`dL`_Α-ΕϜΖ-ΠϘΡΣ-ΩϠ
</code>```

Title: Greek Conversion Golf

Body:
Retina, 57 bytes

11 bytes saved thanks to @Martin Büttner.

Simple transliterate with appropriate character ranges and 0 deletion on each digit.

T`d`_ΡΣ-ΩϠ`.(?=..)
T`d`_Ι-ΠϘ`.\B
T`d`_Α-ΕϜΖ-Θ

Try it online. (First line added to allow all testcases to run together.)

Martin also suggested this one for the same score:

T`d`_J-R`.(?=..)
T`d`_L`.\B
T`dL`_Α-ΕϜΖ-ΠϘΡΣ-ΩϠ


答:
C, 105 bytes

```<code>i,s;main(c,v)char**v;{c--;while(i++<c)if(atoi(v[i])>atoi(v[i%c+1]))c*=!s,s=i;while(--i)puts(v[s++%c+1]);}
</code>```

This accepts the input integers as separate command-line arguments and prints the output list as one integer per line.

If the list isn't driftsortable, the program exits prematurely due to a floating point exception, so its empty output represents an empty list.

Verification

```<code>$ gcc -o driftsort driftsort.c 2>&-
$ ./driftsort 1 | cat
1
$ ./driftsort 5 0 5 | cat
0
5
5
$ ./driftsort 3 2 1 | cat
$ ./driftsort 0 9 3 | cat
$ ./driftsort 1 2 3 4 | cat
1
2
3
4
$ ./driftsort 4 1 2 3 | cat
1
2
3
4
$ ./driftsort 0 2 0 2 | cat
$ ./driftsort 5 3 9 2 6 7 | cat
$ ./driftsort 0 0 0 0 0 0 0 | cat
0
0
0
0
0
0
0
$ ./driftsort 75 230 30 42 50 | cat
30
42
50
75
230
$ ./driftsort 255 255 200 200 203 | cat
200
200
203
255
255
</code>```

Title: Driftsort an array

Body:
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

This is a code-golf, so the shortest program in bytes.

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

Body:
C, 105 bytes

i,s;main(c,v)char**v;{c--;while(i++<c)if(atoi(v[i])>atoi(v[i%c+1]))c*=!s,s=i;while(--i)puts(v[s++%c+1]);}

This accepts the input integers as separate command-line arguments and prints the output list as one integer per line.

If the list isn't driftsortable, the program exits prematurely due to a floating point exception, so its empty output represents an empty list.

Verification

$ gcc -o driftsort driftsort.c 2>&-
$ ./driftsort 1 | cat
1
$ ./driftsort 5 0 5 | cat
0
5
5
$ ./driftsort 3 2 1 | cat
$ ./driftsort 0 9 3 | cat
$ ./driftsort 1 2 3 4 | cat
1
2
3
4
$ ./driftsort 4 1 2 3 | cat
1
2
3
4
$ ./driftsort 0 2 0 2 | cat
$ ./driftsort 5 3 9 2 6 7 | cat
$ ./driftsort 0 0 0 0 0 0 0 | cat
0
0
0
0
0
0
0
$ ./driftsort 75 230 30 42 50 | cat
30
42
50
75
230
$ ./driftsort 255 255 200 200 203 | cat
200
200
203
255
255


问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Implicit Input

Most functions accept some number of input. These inputs are taken from the top of the stack. If the top of the stack does not contain enough arguments, it will draw the remaining argument from the input. (See Section 7.3 in the documentation) I'd like to cite the original explanation:

Implicit inputs can be viewed as follows: the stack is indefinitely extended below
the bottom, that is, at positions 0, −1, −2, ...with values that are not initially
defined, but are resolved on the fly via implicit input. These inputs are asked from
the user only when they are needed, in the order in which they are needed. If
several inputs are required at the same time they follow the normal stack order,
that is, the input that is deepest in the (extended) stack is entered first.

Title: Tips for golfing in MATL


答:
Python 3, 118 bytes

```<code>f=lambda n,i=3:i*"_"and f(n//10,i-1)+"   ΡΙΑΣΚΒΤΛΓΥΜΔΦΝΕΧΞϜΨΟΖΩΠΗϠϘΘ"[i-1::3][n%10].strip()
</code>```

Title: Greek Conversion Golf

Body:
Python 3, 118 bytes

f=lambda n,i=3:i*"_"and f(n//10,i-1)+"   ΡΙΑΣΚΒΤΛΓΥΜΔΦΝΕΧΞϜΨΟΖΩΠΗϠϘΘ"[i-1::3][n%10].strip()


问:
Substitution cipher
A substitution cipher is an encoding method where each letter in the alphabet is replaced with a fixed, different one; for example, given the following substitution map:

```<code>abcdefghijklmnopqrstuvwxyz
            ||
qwertyuiopasdfghjklzxcvbnm
</code>```

The phrase "we all love cryptography" would be encoded as "vt qss sgct eknhzgukqhin".

The program will continuously read its input, one line at time; the first line will contain the substitution map, in the form of all 26 letters, in any order, without repetitions, missing letters or extraneous characters; it will be interpreted as "the first letter is the substitution for A, the second letter is the substitution for B [...] the 26th letter is the substitution for Z"; no output will be provided after reading it.
For each subsequent line, the program will output the encoded text corresponding to the line. Only letters will be encoded; numbers, symbols and whitespaces will be simply copied to the output.

For simplicity, all input (including the substitution map) will only contain lowercase characters.

Sample input:

```<code>qwertyuiopasdfghjklzxcvbnm
hello
bye!
i don't know.
</code>```

Sample output:

```<code>itssg
wnt!
o rgf'z afgv.
</code>```

As usual, the shortest solution wins.

Additional clarifications on input:

The program must read its input stream (I thought that was clear); command line parameters, files, named pipes, network sockets, quantum entanglement or extra sensorial perceptions are not allowed.

The input must include only the actual text to be processed; quotes, brackets, commas or any other symbol, if found, should simply be copied to the output as they are.

No additional characters should be required in the input. If your program requires the input text to be placed in quotes, brackets, commas or any other delimiter, then You Are Doing It Wrong (TM).

"Line" is defined as a string of characters followed by a newline; the actual implementation of "newline" if usually left to the OS, but if you need to go into its details, just use whatever you prefer.

An empty line is no special case; the program could either print an empty line or do nothing, but it should not print any actual text, crash, exit, destroy the operating system, set fire to the house, collapse the Sun in a black hole, summon demons from other planes of existence or replace your toothpaste with mayonnaise.

There is no requirement for the program to run interactively; it's free to suck all its input in and then print all its output; there is also not any time limit on its execution, although it would be definitely preferable for it to terminate before the heat death of the universe.

答:
C++, 154 Bytes

#include <iostream.h>
#include "string.h"
using namespace std;

void encript_string() {
char en[26],in[1024];
string s=cin.getline();
strcpy(en,s.c_str());
while(1){
 s=cin.get_line();
 strcpy(in,s.c_str());
 int i=0,m=0;
 while(in[i] != 10) {
  m=in[i]-97;
  cout<<en[m];
 }
 cout<<"\n";
}
}
```

Title: Substitution cipher


问:
CamelCase2snake_case()
Write a function to convert CamelCased text to snake_case: FunctionForHTMLManipulation becomes function_for_html_manipulation

The input text will be a single suitable identifier in many languages. It must start with an English letter, then be followed by any number of English letters or digits. No other characters (spaces, symbols, etc.) are allowed.

Each "word" within the CamelCased text will start with a capital letter unless at the beginning of the text or immediately after a digit, and be followed by zero or more letters, all of the same case. Groups of digits will be considered as separate words but pass through unchanged.

In other words, a lowercase letter followed by an uppercase letter indicates a word break. Any letter and digit next to each other indicates a word break. An uppercase letter followed by another uppercase letter and a lowercase letter indicates a word break.

...lU... => ...l_u...

...l9... => ...l_9...

...U9... => ...u_9...

...9l... => ...9_l...

...9U... => ...9_u...

...UUl... => ...u_ul...

Both Buy24Beers and buy24beers become buy_24_beers.

MacDonaldAndObrian becomes mac_donald_and_obrian.

MACDonaldAndOBrian becomes mac_donald_and_o_brian.

Title: CamelCase2snake_case()

Body:
JavaScript (ES6), 89 bytes

s=>s.replace(/\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])/g,"$&_").toLowerCase()


答:
Oracle SQL 11.2, 97 bytes

SELECT NVL(SUM(v),0)FROM(SELECT POWER((LEVEL-1)*2+1,2)v FROM DUAL CONNECT BY LEVEL<:1)WHERE v<:1;
```

Title: Sum the odd square numbers less than N


答:
Mathcad, 13 "bytes"

Uses built-in vector summation operator and string-to-vectorOfCharacterCodes function. Definition operator ":=" entered by single key ":", summation operator by ctl-4.

Title: Calculator that adds char values

Body:
Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```<code>Input
Hello World!

Output
1085
</code>```

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.

So I leave it as a bonus thing aswell.

The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```<code>q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
</code>```

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(


问:
Create a sudoku solution CHECKER

Create a Sudoku solution CHECKER

There are oodles of Sudoku SOLVERS here, but I want you to create a solution CHECKER as small as humanly possible (code-golf).

A valid entry will be able to either take a 9x9 array as an argument (passed by reference, serialized on the command line, or however you want to take it) or accept an input file that is nine lines of nine numbers for the final grid.  See examples of input below.

Valid input should be base-10 numbers (1-9)

Missing, empty, extra, non-numeric positions, or positions with numbers outside of 1-9 should be rejected as invalid input by returning a non-zero result, printing an error, or both.

Your program needs to test whether each number appears once per column, once per line, and once per 3x3 sub-grid.  If it passes, return "0" and if not, return a non-zero result.

Use of external resources (websites, etc.) is to be avoided.

If your solution is a stand-alone program, exiting with a exit status of, or printing, "0" or non-zero for "Pass" or "Fail", respectively, is ok.

Let the smallest answer win!

Input Examples:

c array:

```<code>int input[9][9]={{1,2,3,4,5,6,7,8,9},
                 {4,5,6,7,8,9,1,2,3},
                 {7,8,9,1,2,3,4,5,6},
                 {2,3,1,5,6,4,8,9,7},
                 {5,6,4,8,9,7,2,3,1},
                 {8,9,7,2,3,1,5,6,4},
                 {3,1,2,6,4,5,9,7,8},
                 {6,4,5,9,7,8,3,1,2},
                 {9,7,8,3,1,2,6,4,5}
                };
</code>```

file:

```<code>123456789
456789123
789123456
231564897
564897231
897231564
312645978
645978312
978312645
</code>```

The 9 sub-grids:

```<code>+---+---+---+
|123|456|789|
|456|789|123|
|789|123|456|
+---+---+---+
|231|564|897|
|564|897|231|
|897|231|564|
+---+---+---+
|312|645|978|
|645|978|312|
|978|312|645|
+---+---+---+
</code>```

Title: Create a sudoku solution CHECKER

Body:
Javascript ES6, 150 chars

Takes input as a 81-char string without any delimeters.

s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))

Function returns null as negative answer and an array with original string in first element as a positive one. Can change to bool by adding !! to the function begining.

Test (see related challenge for more detais):

f=s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))
;`123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298`
.split`
`.every(f)
&&
`519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825`
.split`
`.every(s => !f(s))


问:
A Numpad's Knight Numbers
For the non-zero digits on a standard numpad

```<code>789
456
123
</code>```

consider placing a chess knight at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?

One of them is 38, since the knight could start on the 3 and move left and up to the 8. 381 and 383 are also possible.

3 itself is possible if no jumps are taken (which is allowed). 5 is as well, but no other digits can be reached from the 5, so it is the only number where the digit 5 appears.

Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a truthy value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a falsy value.

The shortest code in bytes wins. Tiebreaker is earlier answer

Examples

Truthy:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
</code>```

Falsy:

```<code>10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
</code>```

答:
C, <s>78</s> 85 bytes

char*a="9614397052";f(x){int b=x/10;return!b||b*x%5&&abs(a[x%10]-a[b%10])%6==1&f(b);}
```

Since everyone else has taken the input as a string, I tried doing it in integers.  It works recursively from the least-significant digit (a%10); if it's the only digit, then return true.  Otherwise, return true only if the tens digit (b%10) can't be reached from the units digit, and (recursively), the rest of the input satisfies the same test.

The test for reachability works by encoding the knight's tour linearly, and converting each digit to its position (zero to seven) on the tour.  For digits 0 and 5, we assign position nine, which is disconnected from the other positions. Then, mutually reachable numbers differ by one (mod eight); i.e. a[x%10]-a[b%10] is either ±1 or ±7.  So we test the absolute difference (mod 6) against 1.

This solution works for any character encoding that is valid for C (i.e. digits have contiguous codes from 0 to 9).

Title: A Numpad's Knight Numbers

Body:
C, <s>78</s> 85 bytes

char*a="9614397052";f(x){int b=x/10;return!b||b*x%5&&abs(a[x%10]-a[b%10])%6==1&f(b);}

Since everyone else has taken the input as a string, I tried doing it in integers.  It works recursively from the least-significant digit (a%10); if it's the only digit, then return true.  Otherwise, return true only if the tens digit (b%10) can't be reached from the units digit, and (recursively), the rest of the input satisfies the same test.

The test for reachability works by encoding the knight's tour linearly, and converting each digit to its position (zero to seven) on the tour.  For digits 0 and 5, we assign position nine, which is disconnected from the other positions. Then, mutually reachable numbers differ by one (mod eight); i.e. a[x%10]-a[b%10] is either ±1 or ±7.  So we test the absolute difference (mod 6) against 1.

This solution works for any character encoding that is valid for C (i.e. digits have contiguous codes from 0 to 9).


答:
C#, <s>125</s> 117 bytes

```<code>int[]d(int[] m){int r=0;for(int i=0;i<m.Length-1;i++)if(m[i+1]<m[i])r++;if(r<2){Array.Sort(m);return m;}return null;}
</code>```

ungolfed:

```<code>int[] driftsort(int[] m)
    {
        int r = 0;
        for (int i = 0; i < m.Length - 1; i++)
            if (m[i + 1] < m[i])
                r++;

        if (r < 2) { Array.Sort(m); return m; }
        return null;
    }
</code>```

there is much to get smaller here, advice would be appreciated

thanks to Erik Konstantopoulos for -8

Title: Driftsort an array

Body:
C#, <s>125</s> 117 bytes

int[]d(int[] m){int r=0;for(int i=0;i<m.Length-1;i++)if(m[i+1]<m[i])r++;if(r<2){Array.Sort(m);return m;}return null;}

ungolfed:

int[] driftsort(int[] m)
    {
        int r = 0;
        for (int i = 0; i < m.Length - 1; i++)
            if (m[i + 1] < m[i])
                r++;

        if (r < 2) { Array.Sort(m); return m; }
        return null;
    }

there is much to get smaller here, advice would be appreciated

thanks to Erik Konstantopoulos for -8


答:
bash + bc, 86 bytes

```<code>s=0
for((n=0;;n++));{
w=`bc<<<"(2*$n+1)^2"`
[ $w -ge $1 ]&&break;
s=$((s+w))
}
echo $s
</code>```

This piece of code is quite self explaining, as it simply sums up the values. It is not quite a magic code, as formatting it properly helps... The stop condition is not in the header of the loop, but after evaluating the step and before adding, since here we have all the values we need without initalising them beforehand.

Title: Sum the odd square numbers less than N

Body:
bash + bc, 86 bytes

s=0
for((n=0;;n++));{
w=`bc<<<"(2*$n+1)^2"`
[ $w -ge $1 ]&&break;
s=$((s+w))
}
echo $s

This piece of code is quite self explaining, as it simply sums up the values. It is not quite a magic code, as formatting it properly helps... The stop condition is not in the header of the loop, but after evaluating the step and before adding, since here we have all the values we need without initalising them beforehand.


问:
Determine if a move exists in a Bejeweled/match 3 game

Background

In Bejeweled and similar games, the player must swap any two adjacent gems (no diagonals) in an 8x8 grid of gems in order to match three of the same color in a row. The gems can be matched horizontally or vertically. Gameplay continues until there no move exists that can be made resulting in three in a row, at which point the game is over.

Task

The goal is to write a program that determines whether a game of Bejeweled is not over yet. In other words, it must check to see if there is a possible move that makes at least three in a row. There can be more than three gems in a row and it is still a valid move.

Input

Your program must accept via standard input an 8x8 representation of a Bejeweled grid. Each of the seven gem colors will be represented by a digit from 1 to 7. Each line will contain one row, and 8 lines, each consisting of 8 digits, will be input. See the examples. You can assume that the input will always follow this format, and will never already contain three in a row.

Output

The program must then output (to standard output) yes or no depending on whether or not at least one valid move exists that would result in three or more gems in a row. Your program must not output anything other than a single instance of either yes or no.

Rules

Your program must not use any external files or resources, command-line arguments, or require a certain file name. The program with the least number of bytes in its source code wins.

Examples

Input:

```<code>12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656
</code>```

Output: yes

Input:

```<code>35261546
76421754
15743271
62135642
35617653
64565476
54427254
15635465
</code>```

Output: no

See MT0's answer below for additional test cases.

答:
Perl, <s>114</s> <s>96</s> <s>95</s> <s>93</s> <s>92</s> <s>87</s> <s>86</s> 85 bytes

Includes + for -a0p

Run with the input on STDIN:

```<code>bejeweled.pl
12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656
^D
</code>```

bejeweled.pl:

```<code>#!/usr/bin/perl -a0p
$i/s%.%chop$F[$i++&7]%eg>3|/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/||redo;$_=$1?yes:n.o
</code>```

This combines a single direction horizontal regex solution with rotations

Explanation:

In this solution I will repeatedly rotate and do the following 4 tests:

```<code>/(.).\1\1/,      // 3-in-a-row horizontally after left-most shifts right
/(.)\C{9}\1\1/,  // 3-in-a-row horizontally after left-most shifts down
/(.)\C{7}\1.\1/, // 3-in-a-row horizontally after middle shifts down
/(.)\C{6}\1\1/,  // 3-in-a-row horizontally after right-most shifts down
</code>```

Where \C is "any character" (unlike . this includes newline). Except that \C is deprecated and leads to warnings, so I use \H (non-horizontal space) instead which is good enough to capture all digits and newline.

After 4 rotation this will have done all 16 tests that are needed

```<code>-p                            Read lines from STDIN, print $_ at the end
-0                            No line ending => slurp ALL of STDIN
-a                            Split $_ into @F. Since there are no spaces
                              on the rows this means each element of @F is
                              1 row

    s%.%chop$F[$i++&7]%eg     Replace each row by the removed last column
                              This is therefore a left rotation. Very short
                              but at the cost of using @F. To make sure that
                              @F gets refilled from $_ each time I won't be
                              able to use while, until, eval or do$0 for the
                              loops but have to use redo. That costs a few
                              bytes but less than having to do my own split
$i/                      >3   The previous regex replacement always
                              returns 64 and each time through the loop $i is
                              increased by 64. So if this division reaches
                              4 all rotations have been done

/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/ This is the 4 regexes mentioned above
  ||redo                      Stop the loop if the regex matches or we
                              rotated 4 times
$_=$1?yes:n.o                If the regex matched $1 will be one of the
                              color digits (which cannot be 0) and this will
                              assign "yes" to $_. If the regex didn't match
                              in 4 times $1 will get its value from the last
                              succesful regex in scope which will be the one
                              from the rotation, but that one doesn't have
                              any () so $1 will be unset. So in case there
                              is no move $_ will be set to "no" (which needs
                              to be constructed because "no" is a keyword)
</code>```

Body:
Perl, <s>114</s> <s>96</s> <s>95</s> <s>93</s> <s>92</s> <s>87</s> <s>86</s> 85 bytes

Includes + for -a0p

Run with the input on STDIN:

bejeweled.pl
12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656
^D

bejeweled.pl:

#!/usr/bin/perl -a0p
$i/s%.%chop$F[$i++&7]%eg>3|/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/||redo;$_=$1?yes:n.o

This combines a single direction horizontal regex solution with rotations

Explanation:

In this solution I will repeatedly rotate and do the following 4 tests:

/(.).\1\1/,      // 3-in-a-row horizontally after left-most shifts right
/(.)\C{9}\1\1/,  // 3-in-a-row horizontally after left-most shifts down
/(.)\C{7}\1.\1/, // 3-in-a-row horizontally after middle shifts down
/(.)\C{6}\1\1/,  // 3-in-a-row horizontally after right-most shifts down

Where \C is "any character" (unlike . this includes newline). Except that \C is deprecated and leads to warnings, so I use \H (non-horizontal space) instead which is good enough to capture all digits and newline.

After 4 rotation this will have done all 16 tests that are needed

-p                            Read lines from STDIN, print $_ at the end
-0                            No line ending => slurp ALL of STDIN
-a                            Split $_ into @F. Since there are no spaces
                              on the rows this means each element of @F is
                              1 row

    s%.%chop$F[$i++&7]%eg     Replace each row by the removed last column
                              This is therefore a left rotation. Very short
                              but at the cost of using @F. To make sure that
                              @F gets refilled from $_ each time I won't be
                              able to use while, until, eval or do$0 for the
                              loops but have to use redo. That costs a few
                              bytes but less than having to do my own split
$i/                      >3   The previous regex replacement always
                              returns 64 and each time through the loop $i is
                              increased by 64. So if this division reaches
                              4 all rotations have been done

/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/ This is the 4 regexes mentioned above
  ||redo                      Stop the loop if the regex matches or we
                              rotated 4 times
$_=$1?yes:n.o                If the regex matched $1 will be one of the
                              color digits (which cannot be 0) and this will
                              assign "yes" to $_. If the regex didn't match
                              in 4 times $1 will get its value from the last
                              succesful regex in scope which will be the one
                              from the rotation, but that one doesn't have
                              any () so $1 will be unset. So in case there
                              is no move $_ will be set to "no" (which needs
                              to be constructed because "no" is a keyword)


答:
Ruby, 28

```<code>->a{(a*2*?,)[a.sort!*?,]&&a}
</code>```

Returns either the sorted array, or nil (which is a falsy value) if the input is not drift-sortable.

Title: Driftsort an array

Body:
Ruby, 28

->a{(a*2*?,)[a.sort!*?,]&&a}

Returns either the sorted array, or nil (which is a falsy value) if the input is not drift-sortable.


问:
Regex Golf: Verify a Sudoku Solution
Write a regex which matches any valid sudoku solution and doesn't match any invalid sudoku solution. The input is an unrolled version of the sudoku, i.e. there are no line delimiters. E.g. the following board:

```<code>7 2 5 8 9 3 4 6 1
8 4 1 6 5 7 3 9 2
3 9 6 1 4 2 7 5 8
4 7 3 5 1 6 8 2 9
1 6 8 4 2 9 5 3 7
9 5 2 3 7 8 1 4 6
2 3 4 7 6 1 9 8 5
6 8 7 9 3 5 2 1 4
5 1 9 2 8 4 6 7 3
</code>```

would be given as:

```<code>725893461841657392396142758473516829168429537952378146234761985687935214519284673
</code>```

The rules are probably common knowledge by now, but just in case... a sudoku board is valid if and only if:

Each row contains the digits from 1 to 9 exactly once.

Each column contains the digits from 1 to 9 exactly once.

Each of the nine 3x3 subgrids contains the digits from 1 to 9 exactly once.

Rules

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's e modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly. E.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex does not need to match the entire string. It just needs to match at least one substring (which may be empty) for valid solutions and yield no matches for invalid solutions.

You may assume that the input will always be a string of 81 positive digits.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually /.../) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

Test Cases

Valid boards:

```<code>123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298
243561789819327456657489132374192865926845317581673294162758943735914628498236571
243156789519847326687392145361475892724918653895263471152684937436729518978531264
498236571735914628162758943581673294926845317374192865657489132819327456243561789
978531264436729518152684937895263471724918653361475892687392145519847326243156789
341572689257698143986413275862341957495726831173985426519234768734869512628157394
</code>```

Invalid boards:

```<code>519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825
243561789829317456657489132374192865916845327581673294162758943735924618498236571
243156789529847316687392145361475892714928653895263471152684937436719528978531264
498236571735924618162758943581673294916845327374192865657489132829317456243561789
978531264436719528152684937895263471714928653361475892687392145529847316243156789
342571689257698143986413275861342957495726831173985426519234768734869512628157394
345678192627319458892451673468793521713524986951862347179246835534187269286935714
341572689257698143986413275862341957495726831173985426519234768734869512628517394
</code>```

For further test cases, you can use this CJam script which takes a valid board as input and randomly shuffles it to give a new valid board (input format irrelevant as long as it contains only digits and optionally whitespace).

If your regex is compatible with the .NET flavour, you can test it online using Retina. A valid solution should print 0 for invalid boards and some positive integer for valid boards. To run all test cases at once, use this template and insert the regex on the second line. If you need regex modifiers, prepend a ` to the regex and put the standard modifier letters in front of it.

答:
.NET regex, 121 bytes

```<code>^(?!(.{27})*(.{9})?(...){0,2}.?.?(.).?.?(?=(...)*$)(.{9})?.{6,8}\4.{0,17}(.{27})*$|.*(?=(.))((.{9})+|(.(?!(.{9})*$))+)\8)
</code>```

Explanation:

```<code>^(?!                     Invert match (because we're excluding duplicates)
 (.{27})*                Skip 0, 3 or 6 rows
 (.{9})?                 Optionally skip another row
 (...){0,2}              Skip 0, 3 or 6 columns
 .?.?(.).?.?(?=(...)*$)  Choose any of the next three cells
 (.{9})?                 Optionally skip another row
 .{6,8}\4                Match any of the three cells below
 .{0,17}(.{27})*$        As long as they're from the same square
|                        OR
 .*(?=(.))(              Choose any cell
  (.{9})+                Skip at least one row
 |                       or
  (.                     Skip cells
   (?!(.{9})*$)          Without reaching the end of the row
  )+                     For at least one cell (i.e. the cell chosen above)
 )\8)                    Match the chosen cell to the next cell
)
</code>```

Title: Regex Golf: Verify a Sudoku Solution

Body:
.NET regex, 121 bytes

^(?!(.{27})*(.{9})?(...){0,2}.?.?(.).?.?(?=(...)*$)(.{9})?.{6,8}\4.{0,17}(.{27})*$|.*(?=(.))((.{9})+|(.(?!(.{9})*$))+)\8)

Explanation:

^(?!                     Invert match (because we're excluding duplicates)
 (.{27})*                Skip 0, 3 or 6 rows
 (.{9})?                 Optionally skip another row
 (...){0,2}              Skip 0, 3 or 6 columns
 .?.?(.).?.?(?=(...)*$)  Choose any of the next three cells
 (.{9})?                 Optionally skip another row
 .{6,8}\4                Match any of the three cells below
 .{0,17}(.{27})*$        As long as they're from the same square
|                        OR
 .*(?=(.))(              Choose any cell
  (.{9})+                Skip at least one row
 |                       or
  (.                     Skip cells
   (?!(.{9})*$)          Without reaching the end of the row
  )+                     For at least one cell (i.e. the cell chosen above)
 )\8)                    Match the chosen cell to the next cell
)


答:
JavaScript (ES6), 83 characters, 110 bytes

```<code>n=>`${1e3+n}`.replace(/./g,(d,i)=>i--&&d--?"ΡΣΤΥΦΧΨΩϠΙΚΛΜΝΞΟΠϘΑΒΓΔΕϜΖΗΘ"[d+9*i]:"")
</code>```

Title: Greek Conversion Golf

Body:
Introduction

You must create a function to convert Arabic numerals into Greek numerals. The input will be an integer less than 1000 and more than 0.

Algorithm

Split number into digits (e.g. 123 -> 1, 2, 3)

Take each digit, and change to character found in table below, for letter symbol or letter name, (e.g. 123 -> 1, 2, 3 -> ΡΚΓ or RhoKappaGamma).

Specifications

No built-in number-system conversion

Result must be capitalized as in example.

Input will be in base 10.

Test Cases

```<code>123 -> RhoKappaGamma or ΡΚΓ
8 -> Eta or Η
777 -> PsiOmicronZeta or ΨΟΖ
100 -> Rho or Ρ
606 -> ChiDiGamma or ΧϜ
</code>```

Table

```<code>Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8
</code>```

Body:
JavaScript (ES6), 83 characters, 110 bytes

n=>`${1e3+n}`.replace(/./g,(d,i)=>i--&&d--?"ΡΣΤΥΦΧΨΩϠΙΚΛΜΝΞΟΠϘΑΒΓΔΕϜΖΗΘ"[d+9*i]:"")


问:
Tips for golfing in PARI/GP
PARI/GP is a free computer algebra system. It is designed for (algebraic) number theory, not golfing, but that's part of the attraction. Unsurprisingly, it fares best at mathematical tasks; its support for string manipulation is primitive. (Having said that, advice for golfing non-mathematical tasks is also welcome.)

As usual, please post one tip per answer.

These tips should be at least somewhat specific to PARI/GP; advice which applies to 'most' languages belongs at Tips for golfing in <all languages>. Some general tips which don't need to be included:

Compress whitespace. (In GP all whitespace outside of strings is optional.)

Use single-character variables. (There are 50 choices, a-z and A-Z except I and O.)

Use < and > rather than <= and >= when possible.

Chain assignments. (a=b=c or a+=b*=c)

答:
Use set-builder notation to replace apply and select.

apply(x->thing1(x)&&thing2(x),select(condition,v)) → [thing1(x)&&thing2(x)|x<-v,condition(x)]

or

apply(x->thing1(x)&&thing2(x),v) → [thing1(x)&&thing2(x)|x<-v]

but if you're applying a named function, apply is better, since the arguments are implicit:

[functionName(x)|x<-v] → apply(functionName,v)

Title: Tips for golfing in PARI/GP


答:
Mathcad, TBD

In Mathcad, 0 (scalar) == false.

(Equivalent) byte count is TBD until counting method agreed.  Approx 52 bytes using a byte = operator / symbol keyboard equivalence.

Title: Driftsort an array


答:
Perl 5, <s>51</s> 50 bytes

-1 byte thanks to TuukkaX.

Not sure if I can golf this more...

```<code>$s=0;map{$_%2?$s+=$_**2:()}(1..(<>-1)**.5);print$s
</code>```

map checks whether the current value in the array [1.. sqrt(input-1)] is odd or even. If it's odd, increase $s with the odd number squared.

Title: Sum the odd square numbers less than N

Body:
Write a program or function to output the sum of the odd square numbers (OEIS #A016754) less than an input n.

The first 44 numbers in the sequence are:

```<code>1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
</code>```

The formula for the sequence is a(n) = ( 2n + 1 ) ^ 2.

Notes

Your program's behaviour may be undefined for n < 1 (that is, all valid inputs are >= 1.)

Test cases

```<code>1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
</code>```

Body:
Perl 5, <s>51</s> 50 bytes

-1 byte thanks to TuukkaX.

Not sure if I can golf this more...

$s=0;map{$_%2?$s+=$_**2:()}(1..(<>-1)**.5);print$s

map checks whether the current value in the array [1.. sqrt(input-1)] is odd or even. If it's odd, increase $s with the odd number squared.


答:
Retina, 62 bytes

Shamelessly translated from the JavaScript solution.

```<code>\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])
$&_
T`L`l
</code>```

Try it online!

Title: CamelCase2snake_case()

Body:
Write a function to convert CamelCased text to snake_case: FunctionForHTMLManipulation becomes function_for_html_manipulation

The input text will be a single suitable identifier in many languages. It must start with an English letter, then be followed by any number of English letters or digits. No other characters (spaces, symbols, etc.) are allowed.

Each "word" within the CamelCased text will start with a capital letter unless at the beginning of the text or immediately after a digit, and be followed by zero or more letters, all of the same case. Groups of digits will be considered as separate words but pass through unchanged.

In other words, a lowercase letter followed by an uppercase letter indicates a word break. Any letter and digit next to each other indicates a word break. An uppercase letter followed by another uppercase letter and a lowercase letter indicates a word break.

...lU... => ...l_u...

...l9... => ...l_9...

...U9... => ...u_9...

...9l... => ...9_l...

...9U... => ...9_u...

...UUl... => ...u_ul...

Both Buy24Beers and buy24beers become buy_24_beers.

MacDonaldAndObrian becomes mac_donald_and_obrian.

MACDonaldAndOBrian becomes mac_donald_and_o_brian.

Body:
Retina, 62 bytes

Shamelessly translated from the JavaScript solution.

\d(?=\D)|\D(?=\d)|[a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z])
$&_
T`L`l

Try it online!


Title: CamelCase2snake_case()

Body:
JavaScript (ES6), 79 bytes

s=>s.match(/[A-Z]+(?=[A-Z][a-z]|\d|$)|[A-Z]?[a-z]+|\d+/g).join`_`.toLowerCase()


问:
Can Gravity Guy Make It?
Gravity Guy is a game where the only user input is a single key that flips the direction of gravity. Given an ASCII art level, determine if it is possible for Gravity Guy to reach the end.

Rules

The initial direction of gravity is down.

The first column of the input will always contain only one #, which Gravity Guy starts on top of.

Each iteration, he moves to the character directly on his right.

If his path is blocked and he moves into a #, the player loses.

After moving, the player can optionally switch gravity from down to up, or up to down.

Gravity Guy then falls on to the next # (in the current direction of gravity).

If there is no # to fall on to and he falls off the grid, the player loses.

If Gravity Guy moves off the right side of the input grid, the player wins.

Example

If this was the input grid:

```<code>  ###

#  # #
 ###
</code>```

Gravity Guy would start at the x and the be at these positions after each iteration. ^ = switch gravity to up and v = switch gravity to down.

```<code>v                        ^                               v
-------------------------------------------------------------
  ###   |    ###   |    ###   |    ###   |    ###   |    ###
x       |          |    x     |     x    |      x   |
#  #    |  #x #    |  #  #    |  #  #    |  #  #    |  #  # x
 ### #  |   ### #  |   ### #  |   ### #  |   ### #  |   ### #
</code>```

As you can see, by switching gravity at these times Gravity Guy reaches the end, so this input would return a truthy value.

Specifications

Input grid can be in any appropriate "grid" format (multiline string padded with spaces, array of line strings, array of array of characters, etc).

If it is possible for the player to win the level, output a truthy value. If not, output a falsey value.

The width and height of the grid will be 50 characters at most.

This is code-golf, may the shortest code in bytes win!

Test Cases

(each case separated by ----------, any blank lines should also be padded with spaces)

True

```<code> #########   ########      ######     ######
          #  #       #    #      #   #      #
###    #   # #    #   #  #       #  #        #
  #    ##  # #    ##  # #     # #  #      ##
  #    #   # #    #   # #    #     #     #######
  #       #  #       #  #     ###  #          #
  #    ##    #    ##     #       #  #         #
  #    #          #              #        #   #
  #    ####################################   #
  #                                           #
  #############################################

----------

###

----------

   #####

####

----------

 #####
 # # #

# # #
 #####

----------

   ############

######      ######

   ############

----------

  ###   ###
     # #
####  #  ####
    #   #
     # #
      #

----------

    ######
   #
 ##
     #######
###     #
   #    #
    #####

----------

    #####
   #    #
 ##     #
     #######
###
   #
    ######

----------

  ###

#  # #
 ###

----------

  ###  ###

###     ##
   #    #
    #####

----------

  #
     #   #
       #
#   #     #
        #
   #
      #
 #

----------

    ##### ####
   #     #    #
  #   # #  ##  #
             #  #
#####  ####   #
               #
     #########

----------

 ###########################
 #   #   #   #     #   #   #
 # # # #   #   # #   #   # #
 # # # ######### ###########
 # # # #  #       #     #  #
   # # # ## ##### ### #
## #   #    #          ## ###
 # ##### #### ###########  #
 # #     #  #     #     ## #
 # # #####  ### # # # # #  #
 #              #   # #   ##
 ###########################
</code>```

False

```<code> ###
   #
####

----------

### ###

----------

    #
 ### ###

#### ###
    #

----------

  ###     ###
     # # #
####  # #  ####
    #     #
     #   #
      # #
       #

----------

  #######
  #     #
 ## #####

### ######
  #     #
  #######

----------

 ###########################
 #   #   #   #  #  #   #   #
 # # # #   #   # #   #   # #
 # # # ######### ###########
 # # # #  #       #     #  #
   # # # ## ##### ### #
## #   #    #          ## ###
 # ##### #### ###########  #
 # #     #  #     #     ## #
 # # #####  ### # # # # #  #
 #              #   # #   ##
 ###########################
</code>```

答:
Snails, 15 bytes

Try it online?

```<code>^
\ n\ ,=\#r}+~
</code>```

     0. ^ is an option that requires the pattern to start at the top left.

\ : match space

n: Turn 90 degrees in either direction

\ ,: match space zero or more times

=\# check that there is a # in front of us

r: set the direction to right

}+: do all of the preceding one or more times

~ match a cell which is out of the grid bounds

Title: Can Gravity Guy Make It?

Body:
Snails, 15 bytes

<a href="http://snails.tryitonline.net/#code=XgpcIG5cICw9XCNyfSt-&input=ICMjIyMjIyMjIyAgICMjIyMjIyMjICAgICAgIyMjIyMjICAgICAjIyMjIyMgICAgCiAgICAgICAgICAjICAjICAgICAgICMgICAgIyAgICAgICMgICAjICAgICAgIyAgIAojIyMgICAgIyAgICMgIyAgICAjICAgIyAgIyAgICAgICAjICAjICAgICAgICAjICAKICAjICAgICMjICAjICMgICAgIyMgICMgIyAgICAgIyAjICAjICAgICAgIyMgICAgCiAgIyAgICAjICAgIyAjICAgICMgICAjICMgICAgIyAgICAgIyAgICAgIyMjIyMjIwogICMgICAgICAgIyAgIyAgICAgICAjICAjICAgICAjIyMgICMgICAgICAgICAgIyAKICAjICAgICMjICAgICMgICAgIyMgICAgICMgICAgICAgIyAgIyAgICAgICAgICMgCiAgIyAgICAjICAgICAgICAgICMgICAgICAgICAgICAgICMgICAgICAgICMgICAjIAogICMgICAgIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjICAgIyAKICAjICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICMgCiAgIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIA" rel="noreferrer">Try it online?

^
\ n\ ,=\#r}+~

     0. ^ is an option that requires the pattern to start at the top left.

\ : match space

n: Turn 90 degrees in either direction

\ ,: match space zero or more times

=\# check that there is a # in front of us

r: set the direction to right

}+: do all of the preceding one or more times

~ match a cell which is out of the grid bounds


问:
Simulate Cookie Clicker

Intro

Cookie Clicker is a popular browser game in which the player has to click a cookie to gain... Cookies!

The player can buy upgrades which will automatically farm cookies for you. Sometimes a golden cookie will enter the screen, which will provide a bonus upon clicking it.

Challenge

This challenge will not be about clicking a cookie. It will be about automating the cookie.

The player starts off with 0 cookies, and will gain cookies on every game tick. The goal of the challenge is to calculate the amount of ticks it takes to reach a certain amount of cookies.

Input

Your program or function will have 2 input parameters.

The first parameter is the goal, which is simply the amount of cookies you need to finish.

The second parameter is a list of upgrades the player can buy. The format of the list will be explained in further detail in the paragraph Upgrades - List format.

For sake of convenience, you may assume that the input is always in the correct format. You don't have to deal with bad input.

Output

Your program or function should print or return the amount of ticks it takes before the player has reached the goal amount of cookies.

Upgrades

Every game-tick will earn the player some cookies. These are based on the upgrades of the player. If a player has no upgrades, the cookie production will be 1 cookie per tick. Once the player reaches enough cookies to buy an upgrade, he will automatically purchase it (before the next tick happens).

When the player has enough cookies after a tick to buy multiple upgrades, he will attempt to buy all possible upgrades, starting with the cheapest.

List format

[[100, '+', 1],[1000, '*', 2],[10000, '*', 10]

This is an unordered list which contains 3 upgrades. The first parameter of an upgrade is the price of the upgrade. The second parameter is the effect of the upgrade and the third parameter is the effect amount.

The input list will contain no upgrades with the same price.

The only possible effects are + (addition) and * (multiplication).

[100, '+', 1] means that the cookie production will increase by 1 at a cost of 100 cookies.

Golden cookies

Every 1000 ticks, the player will find a golden cookie. When this happens, the player will receive a bonus of 10% (rounded down) of his cookie amount. If the player has 1000 cookies at tick 1000, he will have 1100 cookies before tick 1001 happens.

Order of events

After every tick a couple of actions can occur.

If the player has enough cookies, end the game

If the player has enough cookies, purchase upgrades

If the amount of ticks is a multiple of 1000; Golden cookie

Example input + output

```<code>(0    , [])                              -> 0
(100  , [])                              -> 100
(1    , [[10, '+', 1]])                  -> 1
(10   , [[10, '+', 1]])                  -> 10
(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310
(10000, [[10, '+', 1], [100, '*', 2]])   -> 2263
</code>```

Detailed example

```<code>(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310

ticks: 8, cookies: 8, production: 1
ticks: 9, cookies: 9, production: 1
ticks: 10, cookies: 0, production: 2
ticks: 11, cookies: 2, production: 2
ticks: 58, cookies: 96, production: 2
ticks: 59, cookies: 98, production: 2
ticks: 60, cookies: 0, production: 4
ticks: 61, cookies: 4, production: 4
ticks: 70, cookies: 40, production: 4
ticks: 80, cookies: 80, production: 4
ticks: 260, cookies: 800, production: 4
ticks: 280, cookies: 880, production: 4
ticks: 300, cookies: 960, production: 4
ticks: 309, cookies: 996, production: 4
ticks: 310, cookies: 1000, production: 4 -- done
</code>```

Disclaimer

I will not be held responsible for any addictions caused by this challenge.

Happy golfing!

答:
Javascript ES6, 138 bytes

```<code>f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t
</code>```

Ungolfed:

```<code>p = 1;  // production
c = -1; // cookies, -1 to account for the first tick
t = 0;  // ticks
f = function(g, s, p, c, t) { // goal, upgrades, production, cookies, ticks
    c += p;        // add production to cookies
    if (c < g) {   // cookies < goal
        b = 0;     // reset buy flag to false

        var upgradeArray;
        if (s[0]) { // our upgrade array isn't empty
            var sortedArray = s.sort();
            var upgrade = sortedArray[0];
            b = upgrade[0] <= c;       // price <= cookies
            upgradeArray = s.slice(b); // if we buy something, we remove the upgrade from the array because [1,2,3].slice(1) -> [2,3]
        } else {                       // our upgrade list is empty
            upgradeArray = s;
        }

        var newProduction;
        if (b) {    // we buy something
            newProduction = eval('p' + upgrade[1] + upgrade[2]) // evaluate p+10 for example
        } else {
            newProduction = p; // production is unchanged
        }

        var newCookies;
        if (b) {    // we buy something
            newCookies = c - upgrade[0]; // substract price from cookies
        } else {
            newCookies = c;
        }

        if (t % 1e3 == 0) {    // ticks % 1000 == 0
            newCookies *= 1.1; // golden cookie
        }

        return f(  // recursive call
            g,     // the goal doesn't change
            upgradeArray,
            newProduction,
            newCookies,
            t+1    // add a tick
        )
    } else {       // we have enough cookies, so we
        return t;  // return the amount of ticks
    }
}
</code>```

Try it here

f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t

D.innerHTML= [
    f(0    , []),
    f(100  , []),
    f(1    , [[10, '+', 1]]),
    f(10   , [[10, '+', 1]]),
    f(1000 , [[100, '*', 2], [10, '+', 1]]),
    f(10000, [[10, '+', 1], [100, '*', 2]])
].join(`<br>`)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=D></code>```

Title: Simulate Cookie Clicker

Body:
Javascript ES6, 138 bytes

f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t

Ungolfed:

p = 1;  // production
c = -1; // cookies, -1 to account for the first tick
t = 0;  // ticks
f = function(g, s, p, c, t) { // goal, upgrades, production, cookies, ticks
    c += p;        // add production to cookies
    if (c < g) {   // cookies < goal
        b = 0;     // reset buy flag to false

        var upgradeArray;
        if (s[0]) { // our upgrade array isn't empty
            var sortedArray = s.sort();
            var upgrade = sortedArray[0];
            b = upgrade[0] <= c;       // price <= cookies
            upgradeArray = s.slice(b); // if we buy something, we remove the upgrade from the array because [1,2,3].slice(1) -> [2,3]
        } else {                       // our upgrade list is empty
            upgradeArray = s;
        }

        var newProduction;
        if (b) {    // we buy something
            newProduction = eval('p' + upgrade[1] + upgrade[2]) // evaluate p+10 for example
        } else {
            newProduction = p; // production is unchanged
        }

        var newCookies;
        if (b) {    // we buy something
            newCookies = c - upgrade[0]; // substract price from cookies
        } else {
            newCookies = c;
        }

        if (t % 1e3 == 0) {    // ticks % 1000 == 0
            newCookies *= 1.1; // golden cookie
        }

        return f(  // recursive call
            g,     // the goal doesn't change
            upgradeArray,
            newProduction,
            newCookies,
            t+1    // add a tick
        )
    } else {       // we have enough cookies, so we
        return t;  // return the amount of ticks
    }
}

Try it here

f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t

D.innerHTML= [
    f(0    , []),
    f(100  , []),
    f(1    , [[10, '+', 1]]),
    f(10   , [[10, '+', 1]]),
    f(1000 , [[100, '*', 2], [10, '+', 1]]),
    f(10000, [[10, '+', 1], [100, '*', 2]])
].join(`<br>`)

<div id=D>


问:
How many minimum days will he take to complete N units of work?
A person has to complete N units of work; the nature of work is the same.

In order to get the hang of the work, he completes only one unit of work in the first day.

He wishes to celebrate the completion of work, so he decides to complete one unit of work in the last day.

He is only allowed to complete x, x+1 or x-1 units of work in a day, where x is the units of work completed on the previous day.

Your task is to create a program or function that will compute the minimum number of days will he take to complete N units of work.

Sample Input and Ouput:

```<code>input -> output (corresponding work_per_day table)
-1    -> 0      []
0     -> 0      []
2     -> 2      [1,1]
3     -> 3      [1,1,1]
5     -> 4      [1,1,2,1] or [1,2,1,1]
9     -> 5      [1,2,3,2,1]
13    -> 7      [1,2,2,2,3,2,1]
</code>```

Input may be taken through STDIN or as function argument, or in any appropriate way.

Output may be printed or as the result of a function, or in any appropriate way.

This is code-golf. Shortest solution wins.

答:
Pyth, 8 bytes

```<code>tfg/*TT4
</code>```

How it works:

```<code>tfg/*TT4   Q is implicitly assigned to the input.
 f         test for T=1,2,3,... returning the first successful case
   /*TT4   whether T * T / 4
  g     Q  is greater than or equal to the input (second argument implied)
t          and subtract 1 from the first successful case
</code>```

Try it online!

In pseudo-code:

```<code>for(int T=1;;T++)
    if(T*T/4 >= Q)
        return T-1;
</code>```

bonus, 22 bytes

"should return 7 for -1"

```<code>+tfg/*TT4?>Q0Q-2Q1*4g1
</code>```

Try it online!

Body:
Pyth, 8 bytes

tfg/*TT4

How it works:

tfg/*TT4   Q is implicitly assigned to the input.
 f         test for T=1,2,3,... returning the first successful case
   /*TT4   whether T * T / 4
  g     Q  is greater than or equal to the input (second argument implied)
t          and subtract 1 from the first successful case

Try it online!

In pseudo-code:

for(int T=1;;T++)
    if(T*T/4 >= Q)
        return T-1;

bonus, 22 bytes

"should return 7 for -1"

+tfg/*TT4?>Q0Q-2Q1*4g1

Try it online!


答:
Jelly, <s>42</s> 40 bytes

```<code>“#'nn(2jj33556;r”Or2/F+878Ọ
ṚĖ’ḅ9‘xṚQṚị¢
</code>```

Try it online! or verify all test cases.

Title: Greek Conversion Golf

Body:
Jelly, <s>42</s> 40 bytes

“#'nn(2jj33556;r”Or2/F+878Ọ
ṚĖ’ḅ9‘xṚQṚị¢

Try it online! or verify all test cases.


问:
Calculate average characters of string

Task

Your task is to produce string that contains average characters of string.
First character of result would be average character of first character (which is first character) and second character average of two first characters and so on.

What is average character?

Strings are arrays of bytes. Average character of string can be found by calculating the average of the ASCII values of characters in string and taking corresponding ASCII character.

For example string "Hello!" can be written as byte sequence 72 101 108 108 111 33. Average of ascii values is 533/6 = 88.833... and when it's rounded to nearest integer we get 89 which is ascii code for captial letter Y.

Rules

You can assume that input contains only printable ASCII characters

Input can be read from stdin or as command line arguments or as function arguments

Output must be stdout. If your program is function, you can also return the string you would otherwise print.

It must be whole program or function, not snippet

Standard loopholes apply

Integers are rounded by function floor(x+0.5) or similar function.

How do I win?

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

Examples

Hello! → HW^adY

test → tmop

42 → 43

StackExchange → Sdccd_ccccddd

答:
Factor, 80 bytes

```<code>[ cum-sum [ dup zero? 1 0 ? + / ] map-index [ .5 + floor >fixnum ] map >string ]
</code>```

Title: Calculate average characters of string

Body:
Factor, 80 bytes

[ cum-sum [ dup zero? 1 0 ? + / ] map-index [ .5 + floor >fixnum ] map >string ]


答:
JavaScript, 32 31 bytes

f=(q,t=1)=>q>t*t/4?f(q,t+1):t-1
```

<p><strong>Ungolfed code:</strong></p>

<pre class="lang-js prettyprint-override"><code>function f(q, t = 1) {
  return q > t * t / 4
    ? f(q, t + 1)
    : t - 1
}
</code>```

It uses the same algorithm as Kenny Lau's anwser but it is implemented as recursive closure to save some bytes.

Usage:

f(-1)  // 0
f(0)   // 0
f(2)   // 2
f(3)   // 3
f(5)   // 4
f(9)   // 5
f(13)  // 7
```

<p><strong>REPL solution, 23 bytes</strong></p>

<pre class="lang-js prettyprint-override"><code>for(t=1;t*t++/4<q;);t-2
</code>```

Prepend q= to run the snippet:

q=-1;for(t=1;t*t++/4<q;);t-2 // 0
q=9;for(t=1;t*t++/4<q;);t-2  // 5
q=13;for(t=1;t*t++/4<q;);t-2 // 7
```

Title: How many minimum days will he take to complete N units of work?

Body:
A person has to complete N units of work; the nature of work is the same.

In order to get the hang of the work, he completes only one unit of work in the first day.

He wishes to celebrate the completion of work, so he decides to complete one unit of work in the last day.

He is only allowed to complete x, x+1 or x-1 units of work in a day, where x is the units of work completed on the previous day.

Your task is to create a program or function that will compute the minimum number of days will he take to complete N units of work.

Sample Input and Ouput:

```<code>input -> output (corresponding work_per_day table)
-1    -> 0      []
0     -> 0      []
2     -> 2      [1,1]
3     -> 3      [1,1,1]
5     -> 4      [1,1,2,1] or [1,2,1,1]
9     -> 5      [1,2,3,2,1]
13    -> 7      [1,2,2,2,3,2,1]
</code>```

Input may be taken through STDIN or as function argument, or in any appropriate way.

Output may be printed or as the result of a function, or in any appropriate way.

This is code-golf. Shortest solution wins.

Body:
JavaScript, 32 31 bytes

f=(q,t=1)=>q>t*t/4?f(q,t+1):t-1

Ungolfed code:

function f(q, t = 1) {
  return q > t * t / 4
    ? f(q, t + 1)
    : t - 1
}

It uses the same algorithm as Kenny Lau's anwser but it is implemented as recursive closure to save some bytes.

Usage:

f(-1)  // 0
f(0)   // 0
f(2)   // 2
f(3)   // 3
f(5)   // 4
f(9)   // 5
f(13)  // 7

REPL solution, 23 bytes

for(t=1;t*t++/4<q;);t-2

Prepend q= to run the snippet:

q=-1;for(t=1;t*t++/4<q;);t-2 // 0
q=9;for(t=1;t*t++/4<q;);t-2  // 5
q=13;for(t=1;t*t++/4<q;);t-2 // 7


问:
Death By Shock Probe: That's a lot of dice
In the webcomic Darths & Droids, Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, once claims (warning: potential spoilers in the linked comic) that, with the Lost Orb of Phanastacoria rigged up to his shock probe, he can now dish out a whopping 1048576d4 of damage. (The GM has neither confirmed nor denied this.) Since it should be reasonably obvious that almost no one will actually have the patience to roll that many dice, write a computer program to do it for him, outputting the total value rolled in some reasonable format. Entries will be ranked by program size (shortest program, by byte count, wins), both overall and per-language, with run time breaking ties. Answer may be either a full program or a function definition.

Scores Per-Language

Pyth

Maltysen - 8 bytes*

Jakube - 10 bytes

APL

Alex A - 10 bytes

CJam

Optimizer - 11 bytes

J

ɐɔıʇǝɥʇuʎs - 12 bytes **

Clip10

Ypnypn - 12 bytes **

K

JohnE - 13 bytes

Ti-84 BASIC

SuperJedi224 - 17 bytes*

R

MickyT - 23 bytes

OCTAVE/MATLAB

Oebele - 24 bytes

PARI/GP

Charles - 25 bytes **

Wolfram/Mathematica

LegionMammal978 - 27 bytes

Perl

Nutki - 29 bytes

AsciiThenAnsii - 34 bytes

Ruby

Haegin - 32 bytes **

ConfusedMr_C - 51 bytes **

Commodore Basic

Mark - 37 bytes **

PHP

Ismael Miguel - 38 bytes

VBA

Sean Cheshire - 40 bytes **

PowerShell

Nacht - 41 bytes **

Javascript

Ralph Marshall - 41 bytes

edc65 - 54 bytes (Requires ES6 functionality not available in all browsers.)

Lua

cryptych - 51 bytes

Java

RobAu - 52 bytes **

Geobits - 65 bytes

C

Functino - 57 bytes

Python

CarpetPython - 58 bytes

Postgre/SQL

Andrew - 59 bytes **

Swift

Skrundz - 69 bytes

GoatInTheMachine - 81 bytes

Haskell

Zeta - 73 bytes **

ActionScript

Brian - 75 bytes **

><>

ConfusedMr_C - 76 bytes

GO

Kristoffer Sall-Storgaard - 78 bytes

C#

Brandon - 91 bytes **

Andrew - 105 bytes

Ewan - 148 bytes

Scratch

SuperJedi224 - 102 bytes

C++

Michelfrancis Bustillos - 154 bytes

Polyglots

Ismael Miguel (Javascript/ActionScript2) - 67 bytes

Top 10 Overall

```
Maltysen
Alex A
Jakube
Optimizer
ɐɔıʇǝɥʇuʎs/Ypnypn (order uncertain)
JohnE
SuperJedi224
MickyT
Oebele
```

Warning- entries marked with a * are VERY SLOW.

Programmed marked ** I have not yet been able to properly test

答:
Python 2, <s>69</s> 67 Bytes

import random
print sum([random.randint(1,4)for _ in range(4**10)])
```

<s>11</s> 9 bytes more that the existing Python 2 answer :( I'm sure I can find some places to shave off a few bytes though.

Body:
Python 2, <s>69</s> 67 Bytes

import random
print sum([random.randint(1,4)for _ in range(4**10)])

<s>11</s> 9 bytes more that the existing Python 2 answer :( I'm sure I can find some places to shave off a few bytes though.


答:
UGL, <s>30</s> 25 bytes

```<code>i$+$+dc^l_u^^$*%/%_c=:_do
</code>```

Try it online!

Does not work for negative inputs.

How it works:

```<code>i$+$+dc^l_u^^$*%/%_c=:_do
i$+$+d                     #n = 4*input-1
      c                    #i=0
       ^l_     %/%_c=:_    #while      > n:
           ^^$*            #      i**2
          u                #                i = i+1
                       do  #print(i)
</code>```

Previous 30-byte solution:

```<code>iuc^l_u^^$*cuuuu/%_u%/%_c=:_do
</code>```

Online interpreter here.

Does not work for negative inputs.

How it works:

```<code>iuc^l_u^^$*cuuuu/%_u%/%_c=:_do
iuc                             #push input; inc; i=0;
   ^l_u             %/%_c=:_    #while        > input:
       ^^$*cuuuu/%_             #      i**2/4
                   u            #                      i = i+1
                            do  #print(i)
</code>```

Body:
UGL, <s>30</s> 25 bytes

i$+$+dc^l_u^^$*%/%_c=:_do

Try it online!

Does not work for negative inputs.

How it works:

i$+$+dc^l_u^^$*%/%_c=:_do
i$+$+d                     #n = 4*input-1
      c                    #i=0
       ^l_     %/%_c=:_    #while      > n:
           ^^$*            #      i**2
          u                #                i = i+1
                       do  #print(i)

Previous 30-byte solution:

iuc^l_u^^$*cuuuu/%_u%/%_c=:_do

Online interpreter here.

Does not work for negative inputs.

How it works:

iuc^l_u^^$*cuuuu/%_u%/%_c=:_do
iuc                             #push input; inc; i=0;
   ^l_u             %/%_c=:_    #while        > input:
       ^^$*cuuuu/%_             #      i**2/4
                   u            #                      i = i+1
                            do  #print(i)


问:
Print your code backwards - reverse quine
Write a program that prints its own source code out backwards, in other words an eniuq.

Scoring:

+50 if you use pull data from the Internet.

+25 if you read your own source code.

+1 point per character

Lowest score wins.

Rules:

No using other files (e.g. reverse.txt)

Minimum code length is two characters.

Your program cannot be a palindrome.

答:
><>, 25 bytes

I was surprised to find this hadn't been done yet. :)

```<code>...yhsif sllems gnihtemoS
</code>```

Paste code here and run it.

. is the Jump command, popping x and y off the stack, and moving the IP to (x, y) in the code box. In this case, the stack is empty, so the language's only error message is printed:

```<code>Something smells fishy...
</code>```

Body:
><>, 25 bytes

I was surprised to find this hadn't been done yet. :)

...yhsif sllems gnihtemoS

Paste code here and run it.

. is the Jump command, popping x and y off the stack, and moving the IP to (x, y) in the code box. In this case, the stack is empty, so the language's only error message is printed:

Something smells fishy...