问:
Count sum of all digits
This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer.
Output, the sum of digits in that number and all smaller numbers.

Examples:

```<code>Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
</code>```

To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

```<code>Input: 12
Output: 78
</code>```

Another example, to show the difference:

```<code>Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
</code>```

A larger test case (CORRECT RESPONSE):

```<code>Input: 1000000
Output: 27000001
</code>```

Rules & Guidelines:

Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.

The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.

The code must be able to properly handle inputs at least up to (2^64)-1.

The code should only output the sum.

Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

-25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000

-50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.

The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.

-10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.

-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.

+300 Penalty if your code relies upon any web resources.

答:
Dyalog APL, 9 – 160* = -151

```<code>+/⍎¨∊⍕¨⍳⎕
</code>```

Try it online!

⎕ get evaluated input

 e.g. "7+5" gives 12

⍳ indices 1 ... n

 [1,2,3,4,5,6,7,8,9,10,12]

⍕¨ format each number into string

 ["1","2","3","4","5","6","7","8","9","10","11","12"]

∊ enlist (flatten)

 "123456789101112"

⍎¨ execute each character (yields list of single digit numbers numbers)

 [1,2,3,4,5,6,7,8,9,1,0,1,1,1,2]

+/ sum
 51

* Scoring

-50 bonus as it even accepts expressions as input. The expression must be valid APL, which is acceptable according to OP.

-10 bonus because because it also handles the ^ (* in APL).

-100 bonus because expression input is handled without explicit usage of eval (i.e. ⍎ in APL).

Title: Count sum of all digits

Body:
Dyalog APL, 9 – 160* = -151

+/⍎¨∊⍕¨⍳⎕

Try it online!

⎕ get evaluated input

 e.g. "7+5" gives 12

⍳ indices 1 ... n

 [1,2,3,4,5,6,7,8,9,10,12]

⍕¨ format each number into string

 ["1","2","3","4","5","6","7","8","9","10","11","12"]

∊ enlist (flatten)

 "123456789101112"

⍎¨ execute each character (yields list of single digit numbers numbers)

 [1,2,3,4,5,6,7,8,9,1,0,1,1,1,2]

+/ sum
 51

* Scoring

-50 bonus as it even accepts expressions as input. The expression must be valid APL, which is acceptable according to OP.

-10 bonus because because it also handles the ^ (* in APL).

-100 bonus because expression input is handled without explicit usage of eval (i.e. ⍎ in APL).


问:
Here's Bub. A not-so-world-class soccer player
This is Bub. Bub is a soccer player. However, he's not a very good one. He still can't kick the ball to the net! (If you haven't noticed, @ is the ball.

```<code>                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                                                   |  net   \
 / ─   @                                              |_________\
</code>```

To help develop his skills, he's developed a system to help evaluate his performance when he kicks the ball. He's called it the "10 point system."

However, he doesn't know what he needs to do to achieve x number of points. You need to help him visualize where the ball will be, so that he can set an expectation of how many points he wants to get. There are 10 points per round that he can achieve.

Therefore, this is your challenge.

Given a number x, the number of points Bub gets, output the location of the ball on the field. Here are some helpful markers:

Bub is exactly 50 spaces away from the net.

For each point that Bub gets, the ball moves 5 spaces closer to the net. Therefore, if Bub gets 3 points, the ball is 35 spaces away from the net.

For every 3 points that Bub gets, the ball begins to move in the air! It moves one space up.

If the number of points Bub gets would move the ball behind the net, you can put the ball anywhere inside the net.

Remember, you need to draw Bub, the ball, and the net.

To get you started, here's an example:

Number of Points: 5

```<code>                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                          @                        |        \
 / ─                                                  |_________\
</code>```

Standard rules apply. Code with the lowest number of bytes wins! Happy golfing!

ContentLicense: CC BY-SA 3.0

Body:
JavaScript (ES6), 189

f=n=>"       o \\|/ | / -".match(/.../g).map((v,r)=>(v=[...v+' '.repeat(50)+'| '[+!r]+' _'[+(!r|r>4)].repeat(r+4)+'\\_'[+!r]],y-r?0:v[x]='@',v.join``),n<11?0:n=11,x=3+n*5,y=5-(n/3|0)).join`
`

Test

f=n=>"       o \\|/ | / -".match(/.../g).map((v,r)=>(v=[...v+' '.repeat(50)+'| '[+!r]+' _'[+(!r|r>4)].repeat(r+4)+'\\_'[+!r]],y-r?0:v[x]='@',v.join``),n<11?0:n=11,x=3+n*5,y=5-(n/3|0)).join`
`
var n=0

setInterval(function(){
  N.textContent=n,O.textContent=f(n),n=(n+1)&15
},1000)

<pre id=O></pre><span id=N></span>


问:
Difference of the square of the sum
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

答:
Labyrinth, <s>28</s> 24 bytes

```<code>?:?:}+=-:(:(#{:**+**#2/!
</code>```

Try it online!

Explanation

Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code.

```<code>Cmd Explanation                 Stacks [ Main | Aux ]
?   Read M.                     [ M | ]
:   Duplicate.                  [ M M | ]
?   Read N.                     [ M M N | ]
:   Duplicate.                  [ M M N N | ]
}   Move copy to aux.           [ M M N | N ]
+   Add.                        [ M (M+N) | N ]
=   Swap tops of stacks.        [ M N | (M+N) ]
-   Subtract.                   [ (M-N) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-1) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) (M-N-2) | (M+N) ]
#   Push stack depth.           [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ]
{   Pull (M+N) over from aux.   [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ]
+   Add.                        [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ]
*   Multiply.                   [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
*   Multiply.                   [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
#   Push stack depth.           [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ]
2   Multiply by 10, add 2.      [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ]
/   Divide.                     [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ]
!   Print.                      [ | ]
</code>```

The instruction pointer then hits a dead end and has to turn around. When it now encounters / it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program.

ContentLicense: CC BY-SA 4.0

Title: Difference of the square of the sum

Body:
Labyrinth, <s>28</s> 24 bytes

?:?:}+=-:(:(#{:**+**#2/!

Try it online!

Explanation

Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code.

Cmd Explanation                 Stacks [ Main | Aux ]
?   Read M.                     [ M | ]
:   Duplicate.                  [ M M | ]
?   Read N.                     [ M M N | ]
:   Duplicate.                  [ M M N N | ]
}   Move copy to aux.           [ M M N | N ]
+   Add.                        [ M (M+N) | N ]
=   Swap tops of stacks.        [ M N | (M+N) ]
-   Subtract.                   [ (M-N) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-1) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) (M-N-2) | (M+N) ]
#   Push stack depth.           [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ]
{   Pull (M+N) over from aux.   [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ]
+   Add.                        [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ]
*   Multiply.                   [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
*   Multiply.                   [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
#   Push stack depth.           [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ]
2   Multiply by 10, add 2.      [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ]
/   Divide.                     [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ]
!   Print.                      [ | ]

The instruction pointer then hits a dead end and has to turn around. When it now encounters / it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program.


Title: Difference of the square of the sum

Body:
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

Body:
J, 29 bytes

Port of Doorknob's Jelly answer.

[:(+/@(^&2)-~2^~+/)[}.[:i.1+]

Usage

>> f = [:(+/@(^&2)-~2^~+/)[}.[:i.1+]
>> 91 f 123x
<< 12087152

Where >> is STDIN, << is STDOUT, and x is for extended precision.


答:
Pyth, 11 bytes

```<code>s*M-F#^}FQ2
</code>```

Try it online!

```<code>s*M-F#^}FQ2
       }FQ    Compute the range
      ^   2   Generate all pairs
   -F#        Remove those pairs who have identical elements
 *M           Product of all pairs
s             Sum.
</code>```

Title: Difference of the square of the sum

Body:
Pyth, 11 bytes

s*M-F#^}FQ2

Try it online!

s*M-F#^}FQ2
       }FQ    Compute the range
      ^   2   Generate all pairs
   -F#        Remove those pairs who have identical elements
 *M           Product of all pairs
s             Sum.


答:
JavaScript (ES7), 64 - (50 + 10) = 4

```<code>n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join``].join`+`)
</code>```

The syntax for exponentiation is ** in ES7. If not for the -10 bonus, this would be valid ES6.

Test Suite

f=n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join``].join`+`)
e=s=>`${s} => ${eval(s[0])}` // template tag for test formatting
console.log(e`f(5)`)
console.log(e`f(12)`)
console.log(e`f(10)`)
console.log(e`f(1000000)`)
console.log(e`f('55*96-12')`)```

Title: Count sum of all digits

Body:
This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer.
Output, the sum of digits in that number and all smaller numbers.

Examples:

```<code>Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
</code>```

To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

```<code>Input: 12
Output: 78
</code>```

Another example, to show the difference:

```<code>Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
</code>```

A larger test case (CORRECT RESPONSE):

```<code>Input: 1000000
Output: 27000001
</code>```

Rules & Guidelines:

Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.

The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.

The code must be able to properly handle inputs at least up to (2^64)-1.

The code should only output the sum.

Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

-25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000

-50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.

The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.

-10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.

-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.

+300 Penalty if your code relies upon any web resources.

Body:
JavaScript (ES7), 64 - (50 + 10) = 4

n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join``].join`+`)

The syntax for exponentiation is ** in ES7. If not for the -10 bonus, this would be valid ES6.

Test Suite

f=n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join``].join`+`)
e=s=>`${s} => ${eval(s[0])}` // template tag for test formatting
console.log(e`f(5)`)
console.log(e`f(12)`)
console.log(e`f(10)`)
console.log(e`f(1000000)`)
console.log(e`f('55*96-12')`)


答:
Haskell, 34 bytes

```<code>a#b=sum[a..b]^2-sum(map(^2)[a..b])
</code>```

Usage example: 91 # 123 -> 12087152.

Nothing to explain.

Title: Difference of the square of the sum

Body:
Haskell, 34 bytes

a#b=sum[a..b]^2-sum(map(^2)[a..b])

Usage example: 91 # 123 -> 12087152.

Nothing to explain.


答:
Java, 95 bytes

public int d(int a,int b){int i=a,j,s=0;for(;i<=b;i++)for(j=a;j<=b;j++)s+=i==j?0:i*j;return s;}
```

Ideone it!

Title: Difference of the square of the sum

Body:
Java, 95 bytes

public int d(int a,int b){int i=a,j,s=0;for(;i<=b;i++)for(j=a;j<=b;j++)s+=i==j?0:i*j;return s;}

Ideone it!


答:
Matlab, <s>30</s> <s>29</s> 28 bytes

Using Suever's idea of norm gives us 2 bytes less

```<code>@(x,y)sum(x:y)^2-norm(x:y)^2
</code>```

Old (simple) version:

```<code>@(x,y)sum(x:y)^2-sum((x:y).^2)
</code>```

Title: Difference of the square of the sum

Body:
Matlab, <s>30</s> <s>29</s> 28 bytes

Using Suever's idea of norm gives us 2 bytes less

@(x,y)sum(x:y)^2-norm(x:y)^2

Old (simple) version:

@(x,y)sum(x:y)^2-sum((x:y).^2)


答:
Actually, 11 bytes

```<code>u@x;♂²Σ@Σ²-
</code>```

Try it online!

Title: Difference of the square of the sum

Body:
Actually, 11 bytes

u@x;♂²Σ@Σ²-

Try it online!


答:
Octave, <s>27</s> 23 bytes

```<code>@(x,y)sum(z=x:y)^2-z*z'
</code>```

Creates an anonymous function named ans which accepts two inputs: ans(lower, upper)

Online Demo

Explanation

Creates a row vector from x to y (inclusive) and stores it in z. We then sum all the elements using sum and square it (^2). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two.

Title: Difference of the square of the sum

Body:
Octave, <s>27</s> 23 bytes

@(x,y)sum(z=x:y)^2-z*z'

Creates an anonymous function named ans which accepts two inputs: ans(lower, upper)

Online Demo

Explanation

Creates a row vector from x to y (inclusive) and stores it in z. We then sum all the elements using sum and square it (^2). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two.


答:
JavaScript (ES6), <s>50</s> 37 bytes

```<code>f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s)
</code>```

Now a port of @Dennis♦'s Python solution.

Title: Difference of the square of the sum

Body:
JavaScript (ES6), <s>50</s> 37 bytes

f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s)

Now a port of @Dennis♦'s Python solution.


Title: Difference of the square of the sum

Body:
Pyke, 11 bytes

h1:Ds]MXXs-

Try it here!

h1:         - inclusive_range(input)
   Ds]      -     [^, sum(^)]
      MX    -    deep_map(^, <--**2)
         s  -   ^[1] = sum(^[1])
          - -  ^[0]-^[1]


答:
R, 23 bytes

```<code>sum(i:j)^2-sum((i:j)^2)
</code>```

Does pretty much what you expect by taking i and j as inputs.

Title: Difference of the square of the sum

Body:
R, 23 bytes

sum(i:j)^2-sum((i:j)^2)

Does pretty much what you expect by taking i and j as inputs.


Title: Difference of the square of the sum

Body:
Haskell, 36 bytes

m#n=sum[2*i*j|i<-[m..n],j<-[i+1..n]]

λ> m # n = sum [ 2*i*j | i <- [m..n], j <- [i+1..n] ]
λ> 5 # 9
970
λ> 91 # 123
12087152
λ> 1 # 10
2640

Note that

$$\left( \sum_{k=m}^n k \right)^2 -  \sum_{k=m}^n k^2 = \cdots =  \sum_{k_1=m}^n  \sum_{k_2=m\\ k_2 \neq k_1}^n k_1 k_2 = \sum_{k_1=m}^n  \sum_{k_2=k_1+1}^n 2 \,k_1 k_2$$


答:
Python 2, 43 bytes

f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)
```

Test it on Ideone.

How it works

Call the function defined in the specification \$g(a, b)\$. We have that

$$
\newcommand{\sumab}[2]{\sum_{a \le #1 \le b} #2 \:}
\begin{align}
g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\
& = \sumab {i,j} {ij} - \sumab n {n^2} \\
& = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\
& = 2 \sumab {j<i} {ij} \\
& = 2 \sumab {i} {\sum_{a \le i < j} ij} \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)}
\end{align}
$$

Define the function \$f(x, y, s)\$ recursively as follows.

$$ f(x, y, s) =
\begin{cases}
2xs + f(x+1, y, s+x) & \text{ if } x \le y \\
0 & \text{ if} x > y
\end{cases}
$$

By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that:

$$
\begin{align}
f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\
& \vdots \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \\
& = g(a, b)
\end{align}
$$

This is the function f of the implementation. While b/a returns a non-zero integer, the code following and is executed, thus implementing the recursive definition of f.

Once b/a reaches 0, we have that b > a and the lambda returns False = 0, thus implementing the base case of the definition of f.

Title: Difference of the square of the sum

Body:
Python 2, 43 bytes

f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)

Test it on Ideone.

How it works

Call the function defined in the specification \$g(a, b)\$. We have that

$$
\newcommand{\sumab}[2]{\sum_{a \le #1 \le b} #2 \:}
\begin{align}
g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\
& = \sumab {i,j} {ij} - \sumab n {n^2} \\
& = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\
& = 2 \sumab {j<i} {ij} \\
& = 2 \sumab {i} {\sum_{a \le i < j} ij} \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)}
\end{align}
$$

Define the function \$f(x, y, s)\$ recursively as follows.

$$ f(x, y, s) =
\begin{cases}
2xs + f(x+1, y, s+x) & \text{ if } x \le y \\
0 & \text{ if} x > y
\end{cases}
$$

By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that:

$$
\begin{align}
f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\
& \vdots \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \\
& = g(a, b)
\end{align}
$$

This is the function f of the implementation. While b/a returns a non-zero integer, the code following and is executed, thus implementing the recursive definition of f.

Once b/a reaches 0, we have that b > a and the lambda returns False = 0, thus implementing the base case of the definition of f.


答:
Java, <s>84</s> 77 characters, <s>84</s> 77 bytes

7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you.

public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}

Using the three test cases in the original post: http://ideone.com/q9MZSZ

Ungolfed:

```<code>public int g(int b, int c) {
    int e = 0, f = 0;
    for (; b <= c; e += b, f += b * b++);
    return e*e-f;
}
</code>```

Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference.

Title: Difference of the square of the sum

Body:
Java, <s>84</s> 77 characters, <s>84</s> 77 bytes

7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you.

public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}

Using the three test cases in the original post: http://ideone.com/q9MZSZ

Ungolfed:

public int g(int b, int c) {
    int e = 0, f = 0;
    for (; b <= c; e += b, f += b * b++);
    return e*e-f;
}

Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference.


问:
Bit-Reversal Permutations
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

答:
05AB1E, 8 bytes

Code:

```<code>¾)IF·D>«
</code>```

Explanation:

```<code>¾         # Constant for 0.
 )        # Wrap it up into an array.
  IF      # Do the following input times.
    ·     # Double every element.
     D    # Duplicate it.
      >   # Increment by 1.
       «  # Concatenate the first array.
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Bit-Reversal Permutations

Body:
05AB1E, 8 bytes

Code:

¾)IF·D>«

Explanation:

¾         # Constant for 0.
 )        # Wrap it up into an array.
  IF      # Do the following input times.
    ·     # Double every element.
     D    # Duplicate it.
      >   # Increment by 1.
       «  # Concatenate the first array.

Uses the CP-1252 encoding. Try it online!.


问:
Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

答:
Python, <s>485, 479, 442, 438, 431, 429, 418, 402, 395, 391</s>, 370 bytes.

Saved 19 bytes thank to Cᴏɴᴏʀ O'Bʀɪᴇɴ reminding me that I can assign functions to a letter.

Saved 6 bytes thanks to FryAmTheEggman's suggestion to clean up the bitmask filter.

Saved 21 bytes thanks to W0lf's awesome Ruby answer forcing me to golf this down some more. ;)

This is an absolute monster. Pretty sure I can cut it down a bit more, but it's getting pretty close to being golfed out.

```<code>a=input()
j=''.join
n=lambda v:int(v,2)
f=j('RO H S VL SD A'.split()[i]for i in range(6)if n(a[88:96])&2**i)
print(j(chr(n(a[x:x+8])).strip()+'.'*(x==56)for x in range(0,88,8)).strip('.'),f,j('%02d:%02d:%02d'%(n(a[b-11:b-6]),n(a[b-6:b]),n(a[b:b+6]))+' %d/%d/%d '%(n(a[b+6:b+12])+1980,n(a[b+12:b+16]),n(a[b+16:b+21]))for b in[123,187]),n(a[208:])*(1-('V'in f or'D'in f)))
</code>```

Body:
Python, <s>485, 479, 442, 438, 431, 429, 418, 402, 395, 391</s>, 370 bytes.

Saved 19 bytes thank to Cᴏɴᴏʀ O'Bʀɪᴇɴ reminding me that I can assign functions to a letter.

Saved 6 bytes thanks to FryAmTheEggman's suggestion to clean up the bitmask filter.

Saved 21 bytes thanks to W0lf's awesome Ruby answer forcing me to golf this down some more. ;)

This is an absolute monster. Pretty sure I can cut it down a bit more, but it's getting pretty close to being golfed out.

a=input()
j=''.join
n=lambda v:int(v,2)
f=j('RO H S VL SD A'.split()[i]for i in range(6)if n(a[88:96])&2**i)
print(j(chr(n(a[x:x+8])).strip()+'.'*(x==56)for x in range(0,88,8)).strip('.'),f,j('%02d:%02d:%02d'%(n(a[b-11:b-6]),n(a[b-6:b]),n(a[b:b+6]))+' %d/%d/%d '%(n(a[b+6:b+12])+1980,n(a[b+12:b+16]),n(a[b+16:b+21]))for b in[123,187]),n(a[208:])*(1-('V'in f or'D'in f)))


答:
J, <s>15</s> 11 bytes

```<code>2&(*,1+*)0:
</code>```

There is an alternative for 15 bytes that uses straight-forward binary conversion and reversal.

```<code>2|."1&.#:@i.@^]
</code>```

Usage

```<code>   f =: 2&(*,1+*)0:
   f 0
0
   f 1
0 1
   f 2
0 2 1 3
   f 3
0 4 2 6 1 5 3 7
   f 4
0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15
</code>```

Explanation

```<code>2&(*,1+*)0:  Input: n
         0:  The constant 0
2&(     )    Repeat n times starting with x = [0]
2      *       Multiply each in x by 2
     1+        Add 1 to each
    ,          Append that to
2  *           The list formed by multiplying each in x by 2
               Return that as the next value of x
             Return the final value of x
</code>```

Title: Bit-Reversal Permutations

Body:
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

Body:
J, <s>15</s> 11 bytes

2&(*,1+*)0:

There is an alternative for 15 bytes that uses straight-forward binary conversion and reversal.

2|."1&.#:@i.@^]

Usage

   f =: 2&(*,1+*)0:
   f 0
0
   f 1
0 1
   f 2
0 2 1 3
   f 3
0 4 2 6 1 5 3 7
   f 4
0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15

Explanation

2&(*,1+*)0:  Input: n
         0:  The constant 0
2&(     )    Repeat n times starting with x = [0]
2      *       Multiply each in x by 2
     1+        Add 1 to each
    ,          Append that to
2  *           The list formed by multiplying each in x by 2
               Return that as the next value of x
             Return the final value of x


答:
Pyth - 11 bytes

```<code>ushMByMGQ]0
</code>```

Test Suite.

Title: Bit-Reversal Permutations

Body:
Pyth - 11 bytes

ushMByMGQ]0

Test Suite.


问:
Write a program to elasticize strings
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

答:
PowerShell v2+, 36 bytes

```<code>-join([char[]]$args[0]|%{"$_"*++$i})
</code>```

Takes input $args[0], explicitly casts it as a char array, sends that into a loop |%{...}. Each iteration we take the current letter/character "$_" and use the * overloaded operator to concatenate the string pre-incremented $i times. The result of each loop iteration is encapsulated in parens to form an array and then -joined together to form a string. That string is left on the pipeline and output is implicit.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 Why
Whhyyy

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 SKype
SKKyyyppppeeeee

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 LobbY
LoobbbbbbbYYYYY

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 'a b'
a  bbb
</code>```

Title: Write a program to elasticize strings

Body:
PowerShell v2+, 36 bytes

-join([char[]]$args[0]|%{"$_"*++$i})

Takes input $args[0], explicitly casts it as a char array, sends that into a loop |%{...}. Each iteration we take the current letter/character "$_" and use the * overloaded operator to concatenate the string pre-incremented $i times. The result of each loop iteration is encapsulated in parens to form an array and then -joined together to form a string. That string is left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 Why
Whhyyy

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 SKype
SKKyyyppppeeeee

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 LobbY
LoobbbbbbbYYYYY

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 'a b'
a  bbb


答:
MATL, <s>13</s> <s>12</s> <s>10</s> <s>9</s> 8 bytes

```<code>0i:"EtQh
</code>```

Try it Online

Explanation

```<code>0       % Push number literal 0 to the stack
i:"     % Loop n times
    E   % Multiply by two
    t   % Duplicate
    Q   % Add one
    h   % Horizontally concatenate the result
        % Implicit end of loop, and implicitly display the result

</code>```

For the sake of completeness, here was my old answer using the non-recursive approach  (9 bytes).

```<code>W:qB2&PXB
</code>```

Try it Online

Explanation

```<code>W       % Compute 2 to the power% ofImplicitly thegrab input (n) and compute 2^n
:       % Create an array from [1...2^n]
q       % Subtract 1 to get [0...(2^n - 1)]
B       % Convert to binary where each row is the binary representation of a number
2&P     % Flip this 2D array of binary numbers along the second dimension
XB      % Convert binary back to decimal
        % Implicitly display the result
</code>```

Title: Bit-Reversal Permutations

Body:
MATL, <s>13</s> <s>12</s> <s>10</s> <s>9</s> 8 bytes

0i:"EtQh

Try it Online

Explanation

0       % Push number literal 0 to the stack
i:"     % Loop n times
    E   % Multiply by two
    t   % Duplicate
    Q   % Add one
    h   % Horizontally concatenate the result
        % Implicit end of loop, and implicitly display the result

For the sake of completeness, here was my old answer using the non-recursive approach  (9 bytes).

W:qB2&PXB

Try it Online

Explanation

W       % Compute 2 to the power% ofImplicitly thegrab input (n) and compute 2^n
:       % Create an array from [1...2^n]
q       % Subtract 1 to get [0...(2^n - 1)]
B       % Convert to binary where each row is the binary representation of a number
2&P     % Flip this 2D array of binary numbers along the second dimension
XB      % Convert binary back to decimal
        % Implicitly display the result


答:
APL (8)

```<code>{⍵/⍨⍳⍴⍵}
</code>```

I.e.:

```<code>      {⍵/⍨⍳⍴⍵} ¨  'Why' 'SKype' 'LobbY'
┌──────┬───────────────┬───────────────┐
│Whhyyy│SKKyyyppppeeeee│LoobbbbbbbYYYYY│
└──────┴───────────────┴───────────────┘
</code>```

Explanation:

⍴⍵: length of given vector

⍳: numbers 1..N

⍵/⍨: replicate each element in ⍵ N times.

Title: Write a program to elasticize strings

Body:
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

Body:
APL (8)

{⍵/⍨⍳⍴⍵}

I.e.:

      {⍵/⍨⍳⍴⍵} ¨  'Why' 'SKype' 'LobbY'
┌──────┬───────────────┬───────────────┐
│Whhyyy│SKKyyyppppeeeee│LoobbbbbbbYYYYY│
└──────┴───────────────┴───────────────┘

Explanation:

⍴⍵: length of given vector

⍳: numbers 1..N

⍵/⍨: replicate each element in ⍵ N times.


答:
Haskell, 29 bytes

```<code>concat.zipWith replicate[1..]
</code>```

Usage example: concat.zipWith replicate[1..] $ "SKype" -> "SKKyyyppppeeeee".

replicate n c makes n copies of c and concat makes a single list out of all the sublists.

Title: Write a program to elasticize strings

Body:
Haskell, 29 bytes

concat.zipWith replicate[1..]

Usage example: concat.zipWith replicate[1..] $ "SKype" -> "SKKyyyppppeeeee".

replicate n c makes n copies of c and concat makes a single list out of all the sublists.


答:
Pyth - 5 bytes

1 byte saved thanks to @FryAmTheEggman.

```<code>s*VSl
</code>```

Test Suite.

Title: Write a program to elasticize strings

Body:
Pyth - 5 bytes

1 byte saved thanks to @FryAmTheEggman.

s*VSl

Test Suite.


答:
05AB1E, 6 bytes

```<code>vN>Fy?
</code>```

Explained

```<code>v       # for each char in string
 N>F    # index+1 number of times do
    y?  # print current char
</code>```

Try it online

Title: Write a program to elasticize strings

Body:
05AB1E, 6 bytes

vN>Fy?

Explained

v       # for each char in string
 N>F    # index+1 number of times do
    y?  # print current char

Try it online


答:
Julia, 25 bytes

```<code>f(a,b,x=a:b)=sum(x)^2-x'x
</code>```

This is a function that accepts two integers and returns a 1x1 integer array.

The approach is simple: Construct a UnitRange from the endpoints a and b and call it x, then sum x, square it, and subtract its norm, which is computed as transpose(x) * x.

Try it online! (includes all test cases)

Title: Difference of the square of the sum

Body:
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

Body:
Julia, 25 bytes

f(a,b,x=a:b)=sum(x)^2-x'x

This is a function that accepts two integers and returns a 1x1 integer array.

The approach is simple: Construct a UnitRange from the endpoints a and b and call it x, then sum x, square it, and subtract its norm, which is computed as transpose(x) * x.

Try it online! (includes all test cases)


答:
Java, 158 121 bytes

Saved a whopping 37 bytes thanks to Kevin Cruijssen!

```<code>interface a{static void main(String[]A){int b=0,B;for(char c:A[0].toCharArray())for(B=b+++2;--B>0;)System.out.print(c);}}
</code>```

As a bonus, this program can handle all Unicode characters in the existence, including the control characters located at the very end of Basic Multilingual Plane.

Title: Write a program to elasticize strings

Body:
Java, 158 121 bytes

Saved a whopping 37 bytes thanks to Kevin Cruijssen!

interface a{static void main(String[]A){int b=0,B;for(char c:A[0].toCharArray())for(B=b+++2;--B>0;)System.out.print(c);}}

As a bonus, this program can handle all Unicode characters in the existence, including the control characters located at the very end of Basic Multilingual Plane.


答:
Actually, 7 bytes

```<code>' +ñ♂πΣ
</code>```

Try it online!

Explanation:

```<code>' +ñ♂πΣ
' +      prepend a space
   ñ     enumerate ("abc" -> [[0, 'a'], [1, 'b'], [2, 'c']])
    ♂π   map: for each character, repeat it n times
      Σ  concatenate
</code>```

Title: Write a program to elasticize strings

Body:
Actually, 7 bytes

' +ñ♂πΣ

Try it online!

Explanation:

' +ñ♂πΣ
' +      prepend a space
   ñ     enumerate ("abc" -> [[0, 'a'], [1, 'b'], [2, 'c']])
    ♂π   map: for each character, repeat it n times
      Σ  concatenate


答:
Python 3, <s>48</s> 47 bytes

Thanks to mego for saving a byte with the -~i trick.

```<code>lambda s:''.join(c*-~i for i,c in enumerate(s))
</code>```

This is mostly self-explanatory. One thing for those not versed in Python: The * operator is overloaded to act like Perl's x operator, repeating its string argument the number of times specified by its numeric argument. E.g. 'foo' * 3 == 'foofoofoo'

Title: Write a program to elasticize strings

Body:
Python 3, <s>48</s> 47 bytes

Thanks to mego for saving a byte with the -~i trick.

lambda s:''.join(c*-~i for i,c in enumerate(s))

This is mostly self-explanatory. One thing for those not versed in Python: The * operator is overloaded to act like Perl's x operator, repeating its string argument the number of times specified by its numeric argument. E.g. 'foo' * 3 == 'foofoofoo'


答:
Jelly, 3 bytes

Code:

```<code>ĖP€
</code>```

Explanation:

```<code>Ė     # Enumerate.
 P€   # Product of each.
      # Implicit joining of everything.
</code>```

Uses the Jelly encoding. Try it online!.

Title: Write a program to elasticize strings

Body:
Jelly, 3 bytes

Code:

ĖP€

Explanation:

Ė     # Enumerate.
 P€   # Product of each.
      # Implicit joining of everything.

Uses the Jelly encoding. Try it online!.


答:
MATLAB, 45 bytes

```<code>g=@(m)sort(m(m>0));@(s)s(g(hankel(1:nnz(s))))
</code>```

Explanation: The key is hankel, which produces a Hankel matrix of a given vector. From this matrix, we can extract a vector of indices, which defines which character of the string is at which position in the output. E.g. hankel(1:4) produces following matrix:

```<code> 1  2  3  4
 2  3  4  0
 3  4  0  0
 4  0  0  0
</code>```

From this matrix we can extrac the vector 1,2,2,3,3,3,4,4,4,4,4. This vector allows us to output the first character of the string once, the second one twice e.t.c.

Title: Write a program to elasticize strings

Body:
MATLAB, 45 bytes

g=@(m)sort(m(m>0));@(s)s(g(hankel(1:nnz(s))))

Explanation: The key is hankel, which produces a Hankel matrix of a given vector. From this matrix, we can extract a vector of indices, which defines which character of the string is at which position in the output. E.g. hankel(1:4) produces following matrix:

 1  2  3  4
 2  3  4  0
 3  4  0  0
 4  0  0  0

From this matrix we can extrac the vector 1,2,2,3,3,3,4,4,4,4,4. This vector allows us to output the first character of the string once, the second one twice e.t.c.


答:
Javascript ES6, <s>42</s> 41 bytes

```<code>s=>[,...s].map((e,i)=>e.repeat(i)).join``
</code>```

Example runs:

```<code>f=s=>[,...s].map((e,i)=>e.repeat(i)).join``

f("Why")   => "Whhyyy"
f("SKype") => "SKKyyyppppeeeee"
f("LobbY") => "LoobbbbbbbYYYYY"
</code>```

Title: Write a program to elasticize strings

Body:
Javascript ES6, <s>42</s> 41 bytes

s=>[,...s].map((e,i)=>e.repeat(i)).join``

Example runs:

f=s=>[,...s].map((e,i)=>e.repeat(i)).join``

f("Why")   => "Whhyyy"
f("SKype") => "SKKyyyppppeeeee"
f("LobbY") => "LoobbbbbbbYYYYY"


答:
Octave, 37 bytes

```<code>@(n)bin2dec(fliplr(dec2bin(0:2^n-1)))
</code>```

Creates an anonymous function named ans that can simply be called with ans(n).

Online Demo

Title: Bit-Reversal Permutations

Body:
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

Body:
Octave, 37 bytes

@(n)bin2dec(fliplr(dec2bin(0:2^n-1)))

Creates an anonymous function named ans that can simply be called with ans(n).

Online Demo


答:
Actually, 10 bytes

```<code>u@x;;*@Σ²-
</code>```

Try it online!

Explanation:

```<code>u@x;;*@Σ²-
u@x         range(a, b+1)
   ;;       two copies
     *      dot product with itself (equal to sum of squares)
      @Σ²   sum remaining copy, square sum
         -  subtract
</code>```

Title: Difference of the square of the sum

Body:
Actually, 10 bytes

u@x;;*@Σ²-

Try it online!

Explanation:

u@x;;*@Σ²-
u@x         range(a, b+1)
   ;;       two copies
     *      dot product with itself (equal to sum of squares)
      @Σ²   sum remaining copy, square sum
         -  subtract


Title: Bit-Reversal Permutations

Body:
Javascript ES6, <s>65</s> <s>53</s> 51 bytes

f=(n,m=1)=>n?[...n=f(n-1,m+m),...n.map(i=>i+m)]:[0]

Uses the recursive double-increment-concat algorithm.

Example runs:

f(0) => [0]
f(1) => [0, 1]
f(2) => [0, 2, 1, 3]
f(4) => [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]


答:
CJam, <s>9</s> <s>8</s> 7 bytes

Thanks to jimmy23013 for saving 1 byte.

```<code>Sl+eee~
</code>```

Test it here.

Explanation

Using the LobbY example:

```<code>                                      Stack:
S    e# Push space.                   [" "]
l    e# Read input.                   [" " "LobbY"]
+    e# Append.                       [" LobbY"]
ee   e# Enumerate.                    [[[0 ' ] [1 'L] [2 'o] [3 'b] [4 'b] [5 'Y]]]
e~   e# Run-length decode.            ["LoobbbbbbbYYYYY"]
</code>```

Title: Write a program to elasticize strings

Body:
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

Body:
CJam, <s>9</s> <s>8</s> 7 bytes

Thanks to jimmy23013 for saving 1 byte.

Sl+eee~

Test it here.

Explanation

Using the LobbY example:

                                      Stack:
S    e# Push space.                   [" "]
l    e# Read input.                   [" " "LobbY"]
+    e# Append.                       [" LobbY"]
ee   e# Enumerate.                    [[[0 ' ] [1 'L] [2 'o] [3 'b] [4 'b] [5 'Y]]]
e~   e# Run-length decode.            ["LoobbbbbbbYYYYY"]


答:
Brachylog, 13 bytes

```<code>:ImC,0:Ie,Cw\
</code>```

This prints the result to STDOUT.

Explanation

This is a good example of exploiting backtracking to loop.

```<code>:ImC            C is the Ith character of the Input
    ,
     0:Ie       Unify an implicit variable with an integer between 0 and I
         ,
          Cw    Write C to STDOUT
            \   False, trigger backtracking. It will go back to 0:Ie and unify the implicit
                variable with another integer, until all integers were used. After that, it
                will backtrack to :ImC and unify I and C with the next character.
</code>```

Title: Write a program to elasticize strings

Body:
Brachylog, 13 bytes

:ImC,0:Ie,Cw\

This prints the result to STDOUT.

Explanation

This is a good example of exploiting backtracking to loop.

:ImC            C is the Ith character of the Input
    ,
     0:Ie       Unify an implicit variable with an integer between 0 and I
         ,
          Cw    Write C to STDOUT
            \   False, trigger backtracking. It will go back to 0:Ie and unify the implicit
                variable with another integer, until all integers were used. After that, it
                will backtrack to :ImC and unify I and C with the next character.


答:
Jelly, <s>7</s> 6 bytes

```<code>Ḥ;‘$$¡
</code>```

Thanks to @EriktheOutgolfer for golfing off 1 byte!

Try it online!

How it works

```<code>Ḥ;‘$$¡  Main link. No arguments.
        Implicit argument / initial return value: 0

     ¡  Read an integer n from STDIN and call the link to the left n times.
    $   Combine the two links to the left into a monadic chain, to be called
        with argument A (initially 0, later an array).
Ḥ         Unhalve; yield 2A.
   $      Combine the two links to the left into a monadic chain, to be called
          with argument 2A.
  ‘         Increment; yield 2A + 1
 ;          Concatenate 2A and 2A + 1.
</code>```

Title: Bit-Reversal Permutations

Body:
Jelly, <s>7</s> 6 bytes

Ḥ;‘$$¡

Thanks to @EriktheOutgolfer for golfing off 1 byte!

Try it online!

How it works

Ḥ;‘$$¡  Main link. No arguments.
        Implicit argument / initial return value: 0

     ¡  Read an integer n from STDIN and call the link to the left n times.
    $   Combine the two links to the left into a monadic chain, to be called
        with argument A (initially 0, later an array).
Ḥ         Unhalve; yield 2A.
   $      Combine the two links to the left into a monadic chain, to be called
          with argument 2A.
  ‘         Increment; yield 2A + 1
 ;          Concatenate 2A and 2A + 1.


答:
C#, 81 Bytes

```<code>void f(string s){for(int i=0;i<s.Length;i++)Console.Write(new String(s[i],i+1));}
</code>```

Title: Write a program to elasticize strings

Body:
C#, 81 Bytes

void f(string s){for(int i=0;i<s.Length;i++)Console.Write(new String(s[i],i+1));}


答:
Mathematica, <s>56</s> 33 bytes

Byte count assumes an ISO 8859-1 encoded source.

```<code>±0={0};±x_:=Join[y=±(x-1)2,y+1]
</code>```

This uses the recursive definition to define a unary operator ±.

Title: Bit-Reversal Permutations

Body:
Mathematica, <s>56</s> 33 bytes

Byte count assumes an ISO 8859-1 encoded source.

±0={0};±x_:=Join[y=±(x-1)2,y+1]

This uses the recursive definition to define a unary operator ±.


Title: Difference of the square of the sum

Body:
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

Body:
JavaScript (ES6), 46 bytes

f=(x,y,s=0,p=0)=>x<=y?f(x+1,y,s+x,p+x*x):s*s-p


答:
PHP, 76 bytes

I'm sure this can be improved...

```<code><?php for($i=0;$i<strlen($argv[1]);$i++)echo str_repeat($argv[1]{$i},$i+1);
</code>```

Run from command line:

```<code>$ php [file] "Testing"
</code>```

Title: Write a program to elasticize strings

Body:
PHP, 76 bytes

I'm sure this can be improved...

<?php for($i=0;$i<strlen($argv[1]);$i++)echo str_repeat($argv[1]{$i},$i+1);

Run from command line:

$ php [file] "Testing"


答:
MATL, 5 bytes

```<code>tn:Y"
</code>```

Try it Online

Explanation

```<code>    % Implictly grab input as a string
tn  % Duplicate and compute the length (N)
:   % Create an array from [1...N]
Y"  % Perform run-length decoding to elacticize the string
    % Implicitly display the result
</code>```

Title: Write a program to elasticize strings

Body:
MATL, 5 bytes

tn:Y"

Try it Online

Explanation

    % Implictly grab input as a string
tn  % Duplicate and compute the length (N)
:   % Create an array from [1...N]
Y"  % Perform run-length decoding to elacticize the string
    % Implicitly display the result


答:
MATLAB, 23 bytes

```<code>@(x)repelem(x,1:nnz(x))
</code>```

Creates an anonymous function ans that can be called using ans('stringtoelacticize')

Title: Write a program to elasticize strings

Body:
MATLAB, 23 bytes

@(x)repelem(x,1:nnz(x))

Creates an anonymous function ans that can be called using ans('stringtoelacticize')


答:
J, 4 bytes

```<code>#~#\
</code>```

Usage

```<code>   f =: #~#\
   f 'Why'
Whhyyy
   f 'SKype'
SKKyyyppppeeeee
   f 'LobbY'
LoobbbbbbbYYYYY
   f 'A and B'
A  aaannnnddddd      BBBBBBB
</code>```

Explanation

```<code>#~#\  Input: s
  #\  Computes the length of each prefix of s
      This forms the range [1, 2, ..., len(s)]
#~    For each value in the range, copy the character at the
      corresponding index that many times
      Return the created string
</code>```

Title: Write a program to elasticize strings

Body:
J, 4 bytes

#~#\

Usage

   f =: #~#\
   f 'Why'
Whhyyy
   f 'SKype'
SKKyyyppppeeeee
   f 'LobbY'
LoobbbbbbbYYYYY
   f 'A and B'
A  aaannnnddddd      BBBBBBB

Explanation

#~#\  Input: s
  #\  Computes the length of each prefix of s
      This forms the range [1, 2, ..., len(s)]
#~    For each value in the range, copy the character at the
      corresponding index that many times
      Return the created string


答:
Julia, <s>23</s> 22 bytes

!n=n>0&&[t=2*!~-n;t+1]
```

Rather straightforward implementation of the process described in the challenge spec.

Try it online!

Title: Bit-Reversal Permutations

Body:
Julia, <s>23</s> 22 bytes

!n=n>0&&[t=2*!~-n;t+1]

Rather straightforward implementation of the process described in the challenge spec.

Try it online!


答:
Javascript ES6, 39 bytes

x=>x.replace(/./g,(y,i)=>y+y.repeat(i))
```

<p><strong>Same length, but more fun:</strong></p>

<pre class="lang-js prettyprint-override"><code>x=>x.replace(i=/./g,y=>y.repeat(i=-~i))
</code>```

Snippet demo:

f= x=>x.replace(/./g,(y,i)=>y+y.repeat(i))
run.onclick=_=>output.textContent=f(input.value)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input" value="SKype">
<button id="run">Go</button>
<pre id="output">``````

Title: Write a program to elasticize strings

Body:
Javascript ES6, 39 bytes

x=>x.replace(/./g,(y,i)=>y+y.repeat(i))

Same length, but more fun:

x=>x.replace(i=/./g,y=>y.repeat(i=-~i))

Snippet demo:

f= x=>x.replace(/./g,(y,i)=>y+y.repeat(i))
run.onclick=_=>output.textContent=f(input.value)

<input id="input" value="SKype">
<button id="run">Go</button>
<pre id="output"></pre>


答:
APL (dzaima/APL), <s>6</s> 5 bytes

⍳∘≢⌿⊢
```

Try it online!

⍳∘≢ enumeration of the argument... (indices of its length)

⌿ replicates the elements of...

⊢ the unmodified argument

Title: Write a program to elasticize strings

Body:
APL (dzaima/APL), <s>6</s> 5 bytes

⍳∘≢⌿⊢

Try it online!

⍳∘≢ enumeration of the argument... (indices of its length)

⌿ replicates the elements of...

⊢ the unmodified argument


答:
Python 2, <s>56</s> <s>55</s> 54 bytes

f=lambda n:[0][n:]or[i+j*2for i in 0,1for j in f(n-1)]
```

Test it on Ideone.

Thanks to @xnor for golfing off 1 byte!

Title: Bit-Reversal Permutations

Body:
Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the bit-reversal permutation of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence A030109. This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a challenge for computing the FFT for sequences where the length is a power of 2.

This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits.

For example, if \$n = 3\$, the range of integers is [0, 1, 2, 3, 4, 5, 6, 7]. These are

```<code>i  Regular  Bit-Reversed  j
0    000        000       0
1    001        100       4
2    010        010       2
3    011        110       6
4    100        001       1
5    101        101       5
6    110        011       3
7    111        111       7
</code>```

where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is [0, 4, 2, 6, 1, 5, 3, 7].

The output for \$n\$ from 0 thru 4 are

```<code>n    Bit-Reversed Permutation
0    [0]
1    [0, 1]
2    [0, 2, 1, 3]
3    [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show,

```<code>[0, 2, 1, 3] * 2 = [0, 4, 2, 6]
[0, 4, 2, 6] + 1 = [1, 5, 3, 7]
[0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7]
</code>```

where \$⊕\$ represents concatenation.

You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results.

Rules

This is code-golf so the shortest solution wins.

Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations.

Your solution must be, at the least, valid for \$n\$ from 0 to 31.

Body:
Python 2, <s>56</s> <s>55</s> 54 bytes

f=lambda n:[0][n:]or[i+j*2for i in 0,1for j in f(n-1)]

Test it on Ideone.

Thanks to @xnor for golfing off 1 byte!


答:
Retina, 62 bytes

It wasn't as easy or short as I thought it'd be. Note that the code contains no spaces. They are all tabs (which are rendered incorrectly here), and the last line is blank.

```<code>.*
$0¶ ¶
{+`^(.)(.*)¶    (.*¶.*)
$1$2    ¶$3$1
(   +)¶
¶   $1
}`^.

    |¶

</code>```

Try it online

Title: Write a program to elasticize strings

Body:
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

Body:
Retina, 62 bytes

It wasn't as easy or short as I thought it'd be. Note that the code contains no spaces. They are all tabs (which are rendered incorrectly here), and the last line is blank.

.*
$0¶ ¶
{+`^(.)(.*)¶    (.*¶.*)
$1$2    ¶$3$1
(   +)¶
¶   $1
}`^.

    |¶

Try it online


答:
Python 3, <s>67</s> 59 bytes

Thanks to @Dennis for -8 bytes

```<code>lambda n:[int(bin(i+2**n)[:1:-1],2)//2for i in range(2**n)]
</code>```

We may as well have a (modified) straightforward implementation in Python, even if this is quite long.

An anonymous function that takes input by argument and returns the bit-reversed permutation as a list.

How it works

```<code>lambda n                 Anonymous function with input n
...for i in range(2**n)  Range from 0 to 2**n-1
bin(i+2**n)[:1:-1]       Convert i+2**n to binary string, giving 1 more digit than needed,
                         remove '0b' from start, and reverse
int(...,2)               Convert back to decimal
...//2                   The binary representation of the decimal value has one trailing
                         bit that is not required. This is removed by integer division by 2
:[...]                   Return as list
</code>```

Try it on Ideone

Title: Bit-Reversal Permutations

Body:
Python 3, <s>67</s> 59 bytes

Thanks to @Dennis for -8 bytes

lambda n:[int(bin(i+2**n)[:1:-1],2)//2for i in range(2**n)]

We may as well have a (modified) straightforward implementation in Python, even if this is quite long.

An anonymous function that takes input by argument and returns the bit-reversed permutation as a list.

How it works

lambda n                 Anonymous function with input n
...for i in range(2**n)  Range from 0 to 2**n-1
bin(i+2**n)[:1:-1]       Convert i+2**n to binary string, giving 1 more digit than needed,
                         remove '0b' from start, and reverse
int(...,2)               Convert back to decimal
...//2                   The binary representation of the decimal value has one trailing
                         bit that is not required. This is removed by integer division by 2
:[...]                   Return as list

Try it on Ideone


问:
Reverse Bit Order of 32-bit Integers
Write the shortest code to reverse the bit order of a 32-bit integer.

Rules:

Input is assumed to be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).

Output must be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).

Standard library only.

It may be a function or a complete program.

Input may be either from stdin or as a function argument.

Output must be either stdout or as a returned value.

If your language has a built-in or standard library function that does this in one step (e.g. rbit in ARM assembly), that cannot be used.

Examples:

Key:

decimal

binary

(reverse)

reversed binary

decimal output

Examples:

-90 (8-bit example for demonstration)

10100110b

(reverse)

01100101b

101

486

00000000000000000000000111100110b

(reverse)

01100111100000000000000000000000b

1736441856

-984802906

11000101010011010001100110100110b

(reverse)

01100101100110001011001010100011b

1704506019

Note: Omissions are free game. If I didn't say it, and it's not one of the standard loopholes, then it's completely allowed.

答:
JavaScript (ES6), 32 bytes

```<code>(n,m=32)=>(--m&&f(n,m)*2)|n>>m&1
</code>```

Wrote this while trying to solve Bit-Reversal Permutations - it didn't help there, but it works fine here!

Title: Reverse Bit Order of 32-bit Integers

Body:
JavaScript (ES6), 32 bytes

(n,m=32)=>(--m&&f(n,m)*2)|n>>m&1

Wrote this while trying to solve Bit-Reversal Permutations - it didn't help there, but it works fine here!


答:
Perl, 16 bytes

```<code>s/./$&x$+[0]/ge
</code>```

+1 byte for the -p flag.

```<code>s/./        /    find every character
             g   globally
              e  and replace with the eval'd result of
    $&           the matched string
      x          repeated
       $+[0]     by the index of the character after the match
</code>```

Title: Write a program to elasticize strings

Body:
Perl, 16 bytes

s/./$&x$+[0]/ge

+1 byte for the -p flag.

s/./        /    find every character
             g   globally
              e  and replace with the eval'd result of
    $&           the matched string
      x          repeated
       $+[0]     by the index of the character after the match


问:
Rotate a hypercube

Introduction

A hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then – using the 4th dimension – folding it into a hypercube. It's basically a cube, where each side is a cube.

To create a hypercube, you need 16 4d vectors (a vector with an x, a y, a z and a w component). These vectors are the following:

```<code>A(0, 0, 0, 0); B(1, 0, 0, 0); C(1, 0, 1, 0); D(0, 0, 1, 0); E(0, 1, 0, 0); F(1, 1, 0, 0); G(1, 1, 1, 0); H(0, 1, 1, 0);
I(0, 0, 0, 1); J(1, 0, 0, 1); K(1, 0, 1, 1); L(0, 0, 1, 1); M(0, 1, 0, 1); N(1, 1, 0, 1); O(1, 1, 1, 1); P(0, 1, 1, 1);
</code>```

The hypercube has 24 faces. The following list contains all of them (every group marks a quad):

```<code>ABFE, CDHG, BCGF, DAEH, DCBA, FEHG
IJNM, KLPO, JKON, LIMP, LKJI, PMNO
ABJI, DCKL, BCKJ, DAIL, FEMN, GHPO, FGON, EHPM, EAIM, BFNJ, CGOK, HDLP
</code>```

With all this information, you technically have a hypercube in code. To rotate this, you need 6 different matrices for each rotational plane, one for the YZ, XZ, XY, XW, YW and ZW planes. After you have every matrix, you need to multiply the cube's vertices with them.

The following images show the structure of each matrix:

For the rotation on the YZ plane:

For the rotation on the XZ plane:

For the rotation on the XY plane:

For the rotation on the XW plane:

For the rotation on the YW plane:

For the rotation on the ZW plane:

The rotations get applied in this order.

After all this, you have a rotated hypercube. Now you need to draw it. You should use an orthogonal projection combined with a perspective projection to send (x, y, z, w) to (2x/(2+z), 2y/(2+z)).

Input

Your input is 6 integers between 0 (inclusively) and 360 (exclusively). These represent the rotations in degrees on the different rotational planes of the hypercube.

Output

Your output should be a single image containing the hypercube. The display can be a rasterized image, a vector image or an ASCII art. The output image should be at least 100 * 100 pixels, and the cube needs to take up at least 50% of the screen. Any default image output format is allowed.

Test cases

```<code>0 0 0 0 0 0
</code>```

```<code>0 0 0 0 0 30
</code>```

```<code>30 0 0 0 0 30
</code>```

```<code>0 0 0 30 30 30
</code>```

```<code>45 45 45 0 0 0
</code>```

```<code>45 45 45 45 45 45
</code>```

Open the images in a new tab, to see them in full size.

Rules

Default rules apply

Standard loopholes are forbidden

Shortest code in bytes wins

答:
C# + Unity, <s>1060</s> <s>845</s> 835 bytes

C# ≈ Java

Assumes that this function is in a script placed on MainCamera.

Edit:

Thanks to @TuukkaX for the suggestions to save 19 bytes
Saved ~200 bytes using the Eulerian cycle.

Golfed:

```<code>void d(float[]r){transform.position=Vector3.back*2;GetComponent<Camera>().backgroundColor=Color.black;Vector4[]p=new Vector4[16];Matrix4x4[]m=new Matrix4x4[6];int i=0;for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f);int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}};for(i=0;i<6;i++){m[i]=Matrix4x4.identity;r[i]=Mathf.Deg2Rad*r[i];float c=Mathf.Cos(r[i]),s=Mathf.Sin(r[i]);m[i][X[1,i]]=c;m[i][X[2,i]]=c;m[i][X[0,i]]=s;m[i][X[0,i]%4*4+X[0,i]/4]=-s;}for(i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i];int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0};LineRenderer l=new GameObject().AddComponent<LineRenderer>();l.SetVertexCount(33);l.material=new Material(Shader.Find("Sprites/Default"));l.SetWidth(.03f,.03f);for(i=0;i<33;i++)l.SetPosition(i,p[F[i]]);
</code>```

Newlines + indentation + Full shell:

```<code>using UnityEngine;
using System.Collections;

public class h : MonoBehaviour {

    void d(float[]r)
    {
        transform.position=Vector3.back*2.5f;
        GetComponent<Camera>().backgroundColor=Color.black;
        Vector4[]p=new Vector4[16];
        Matrix4x4[]m=new Matrix4x4[6];
        int i=0;
        for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f);
        int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}};
        for (i=0;i<6;i++){
            m[i]=Matrix4x4.identity;
            r[i]=Mathf.Deg2Rad*r[i];
            float c=Mathf.Cos(r[i]);
            float s=Mathf.Sin(r[i]);
            m[i][X[1,i]]=c;
            m[i][X[2,i]]=c;
            m[i][X[0,i]]=s;
            m[i][X[0,i]%4*4+X[0,i]/4]=-s;
        }
        for (i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i];
        int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0};
        LineRenderer l=new GameObject().AddComponent<LineRenderer>();
        l.SetVertexCount(33);
        l.material=new Material(Shader.Find("Sprites/Default"));
        l.SetWidth(.03f,.03f);
        for (i=0;i<33;i++)
            l.SetPosition(i,p[F[i]]);
        l.gameObject.tag = "Player";
    }
    public float[] input;
    void Start()
    {
        d(input);
    }
}
</code>```

<s>I couldn't figure out a simple formula for constructing the rotation matrices nor the "faces" which to draw, so that cost a lot of bytes to hard-code.</s> I borrowed the Eulerian cycle from @beaker. Also, Unity built-ins are extremely verbose.

You can verify all test cases online.

Title: Rotate a hypercube

Body:
C# + Unity, <s>1060</s> <s>845</s> 835 bytes

C# ≈ Java

Assumes that this function is in a script placed on MainCamera.

Edit:

Thanks to @TuukkaX for the suggestions to save 19 bytes
Saved ~200 bytes using the Eulerian cycle.

Golfed:

void d(float[]r){transform.position=Vector3.back*2;GetComponent<Camera>().backgroundColor=Color.black;Vector4[]p=new Vector4[16];Matrix4x4[]m=new Matrix4x4[6];int i=0;for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f);int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}};for(i=0;i<6;i++){m[i]=Matrix4x4.identity;r[i]=Mathf.Deg2Rad*r[i];float c=Mathf.Cos(r[i]),s=Mathf.Sin(r[i]);m[i][X[1,i]]=c;m[i][X[2,i]]=c;m[i][X[0,i]]=s;m[i][X[0,i]%4*4+X[0,i]/4]=-s;}for(i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i];int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0};LineRenderer l=new GameObject().AddComponent<LineRenderer>();l.SetVertexCount(33);l.material=new Material(Shader.Find("Sprites/Default"));l.SetWidth(.03f,.03f);for(i=0;i<33;i++)l.SetPosition(i,p[F[i]]);

Newlines + indentation + Full shell:

using UnityEngine;
using System.Collections;

public class h : MonoBehaviour {

    void d(float[]r)
    {
        transform.position=Vector3.back*2.5f;
        GetComponent<Camera>().backgroundColor=Color.black;
        Vector4[]p=new Vector4[16];
        Matrix4x4[]m=new Matrix4x4[6];
        int i=0;
        for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f);
        int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}};
        for (i=0;i<6;i++){
            m[i]=Matrix4x4.identity;
            r[i]=Mathf.Deg2Rad*r[i];
            float c=Mathf.Cos(r[i]);
            float s=Mathf.Sin(r[i]);
            m[i][X[1,i]]=c;
            m[i][X[2,i]]=c;
            m[i][X[0,i]]=s;
            m[i][X[0,i]%4*4+X[0,i]/4]=-s;
        }
        for (i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i];
        int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0};
        LineRenderer l=new GameObject().AddComponent<LineRenderer>();
        l.SetVertexCount(33);
        l.material=new Material(Shader.Find("Sprites/Default"));
        l.SetWidth(.03f,.03f);
        for (i=0;i<33;i++)
            l.SetPosition(i,p[F[i]]);
        l.gameObject.tag = "Player";
    }
    public float[] input;
    void Start()
    {
        d(input);
    }
}

<s>I couldn't figure out a simple formula for constructing the rotation matrices nor the "faces" which to draw, so that cost a lot of bytes to hard-code.</s> I borrowed the Eulerian cycle from @beaker. Also, Unity built-ins are extremely verbose.

You can verify all test cases online.


Title: Decode a Microsoft MS-DOS 5.0 FAT directory entry

Body:
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

Body:
Verilog, <s>513</s> <s>670</s> 617 bytes

Runs using IVerilog. No special compile flags needed.

This is a monster of nested definitions, bit-twiddling, and the annoyance of having to flip bit order due to the endianness (otherwise either the string doesn't print, or the number bit order is wrong). The input is taken through the i port, which is the usual way of taking input into a Verilog module. $display is used to print to standard out. 6 bytes could be saved if leading zeros were not required for the timestamp.

`define r(o,b)wire[3:0]o;assign o={i[b],i[b+1],i[b+2],i[b+3]};
`define R(t,a,b,c,d,s)`r(a,s)`r(b,s+4)`r(c,s+8)`r(d,s+12)wire[15:0]t;assign t={a,b,c,d};
`define p(m,k)i[90+m]?"k":"",
`define F(a,b)"a a a b\t b%d"
module f(input[0:255]i);`R(d,q,w,e,r,112)`R(D,Q,W,E,R,128)`R(s,z,x,c,v,224)`R(S,Z,X,C,V,240)`R(p,t,y,u,o,176)`R (A,b,n,m,l,192)always@(i)$display(`F(%s%s%s,%02d:%02d:%02d%d/%d/%d),i[0:63],i[64:87]=="   "?" ":".",i[64:87],`p(5,RO)`p(4,H)`p(3,S)`p(2,VL)`p(1,SD)`p(0,A)d[15:11],d[10:5],d[4:0]*2,D[15:9]+1980,D[8:5],D[4:0],p[15:11],p[10:5],p[4:0]*2,A[15:9]+1980,A[8:5],A[4:0],|i[91:92]?0:{s,S});endmodule

Demo

Testbench (Not scored):

`timescale 1ns / 1ps

module ftest;
reg [0:255] i;
f uut (
.i(i)
);
initial begin
    i=256'b0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000;
    #100;
i=256'b0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001;
end

endmodule

Example run:

$ iverilog design.sv testbench.sv  && vvp a.out
programm.ing   HS      20:18:08       2016/ 6/20      53248
    ppcg        S  SD  11:43:24       2010/12/31          0


问:
Can my 4-note music box play that song?
I have a crank-operated music box that can play a series of four notes. When I turn the crank, it plucks one of four strings, depending on the position of the crank and the direction of the turn. When the crank is turned due north, the box (with its strings numbered 1 through 4) looks like this:

```<code>1  |  2
   |
   O

4     3
</code>```

From there, I can turn the crank clockwise to pluck the #2 string and point the crank east:

```<code>1     2

   O---

4     3
</code>```

Alternatively, I could have also turned the crank counterclockwise from north to play the #1 string and end with a crank pointing west:

```<code>1     2

---O

4     3
</code>```

At any given time, then, the box can play one of two notes: the next note available in the clockwise direction or the next note in the counterclockwise direction.

Challenge

Your challenge is to write a program or function that accepts a non-empty string of note values (i.e., numerals 1 through 4) and determine if it is ever possible to play that sequence of notes on the music box. Produce a truthy or falsy result to indicate the playability or non-playability of the input.

Some notes:

The input makes no assumptions about initial start position. The inputs 214 (starting east and moving strictly counterclockwise) and 234 (starting north and moving strictly clockwise) and both valid.

The crank may move freely in either direction after each note. A series of the same note is possible (e.g., 33333) by moving back and forth across one string. The series 1221441 is perfectly playable (starting west, moving clockwise two steps, then counterclockwise three steps, then clockwise two steps).

Samples

Some true cases:

```<code>1
1234
1221
3333
143332
22234
2234
22214
1221441
41233
</code>```

Some false cases:

```<code>13     (note 3 is never available after note 1)
1224   (after `122`, the crank must be north, so 4 is not playable)
121    (after `12` the crank is east; 1 is not playable)
12221  (as above, after `1222` the crank is east)
43221
</code>```

Title: Can my 4-note music box play that song?

Body:
Thue, 203 bytes

I can't think of how to golf this farther.

0::=:::
>11::=>1
>22::=>2
>33::=>3
>44::=>4
>12::=b
>21::=d
>14::=c
>41::=a
>23::=c
>32::=a
>34::=d
>43::=b
a1::=d
a2::=b
b2::=a
b3::=c
c3::=b
c4::=d
d4::=c
d1::=a
a<::=~n
b<::=~e
c<::=~s
d<::=~w
::=
>0<

If the note sequence is possible, will output ending direction, otherwise the output will be empty.


答:
K/Kona, 14 bytes

```<code>{,/(1+!#x)#'x}
</code>```

Usage:

```<code>k){,/(1+!#x)#'x}"A and B"
"A  aaannnnddddd      BBBBBBB"
</code>```

Title: Write a program to elasticize strings

Body:
K/Kona, 14 bytes

{,/(1+!#x)#'x}

Usage:

k){,/(1+!#x)#'x}"A and B"
"A  aaannnnddddd      BBBBBBB"


答:
Python, 40 bytes

f=lambda s,i=1:s and s[0]*i+f(s[1:],i+1)
```

Title: Write a program to elasticize strings


答:
Python, 39 bytes

f=lambda s:s and f(s[:-1])+s[-1]*len(s)
```

Test it on Ideone.

Title: Write a program to elasticize strings

Body:
Python, 39 bytes

f=lambda s:s and f(s[:-1])+s[-1]*len(s)

Test it on Ideone.


问:
Calculate the relativistic velocity
In special relativity, the velocity of a moving object relative to another object that is moving in the opposite direction is given by the formula:

\begin{align}s = \frac{v+u}{1+vu/c^2}.\end{align}

```<code>s = ( v + u ) / ( 1 + v * u / c ^ 2)
</code>```

In this formula, \$v\$ and \$u\$ are the magnitudes of the velocities of the objects, and \$c\$ is the speed of light (which is approximately \$3.0 \times 10^8 \,\mathrm m/\mathrm s\$, a close enough approximation for this challenge).

For example, if one object was moving at v = 50,000 m/s, and another object was moving at u = 60,000 m/s, the velocity of each object relative to the other would be approximately s = 110,000 m/s. This is what you would expect under Galilean relativity (where velocities simply add). However, if v = 50,000,000 m/s and u = 60,000,000 m/s, the relative velocity would be approximately 106,451,613 m/s, which is significantly different than the 110,000,000 m/s predicted by Galilean relativity.

The Challenge

Given two integers v and u such that 0 <= v,u < c, calculate the relativistic additive velocity, using the above formula, with c = 300000000. Output must be either a decimal value or a reduced fraction. The output must be within 0.001 of the actual value for a decimal value, or exact for a fraction.

Test Cases

Format: v, u -> exact fraction (float approximation)

```<code>50000, 60000 -> 3300000000000/30000001 (109999.99633333346)
50000000, 60000000 -> 3300000000/31 (106451612.90322581)
20, 30 -> 7500000000000000/150000000000001 (49.999999999999666)
0, 20051 -> 20051 (20051.0)
299999999, 299999999 -> 53999999820000000000000000/179999999400000001 (300000000.0)
20000, 2000000 -> 4545000000000/2250001 (2019999.1022226212)
2000000, 2000000 -> 90000000000/22501 (3999822.2301231055)
1, 500000 -> 90000180000000000/180000000001 (500000.9999972222)
1, 50000000 -> 90000001800000000/1800000001 (50000000.972222224)
200000000, 100000000 -> 2700000000/11 (245454545.45454547)
</code>```

答:
Actually, 12 bytes

```<code>;8╤3*ì*πu@Σ/
</code>```

Try it online!

Explanation:

```<code>;8╤3*ì*πu@Σ/
;             dupe input
 8╤3*ì*       multiply each element by 1/(3e8)
       πu     product, increment
         @Σ/  sum input, divide sum by product
</code>```

Title: Calculate the relativistic velocity

Body:
Actually, 12 bytes

;8╤3*ì*πu@Σ/

Try it online!

Explanation:

;8╤3*ì*πu@Σ/
;             dupe input
 8╤3*ì*       multiply each element by 1/(3e8)
       πu     product, increment
         @Σ/  sum input, divide sum by product


答:
Perl 6, <s> 22 20 </s> 19 bytes

<s>{S:g/(.)/{$0 x$/.to}/}
{S:g[(.)]=$0 x$/.to}</s>
{[~] .comb Zx 1..*}```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{          # implicit parameter $_
  [~]      # string concatenate the following list
    .comb  # the NFG characters from $_
    Z[x]   # zip combined using the string repetition operator
    1 .. * # 1 to infinity
}
</code>```

Title: Write a program to elasticize strings

Body:
Perl 6, <s> 22 20 </s> 19 bytes

<s>{S:g/(.)/{$0 x$/.to}/}
{S:g[(.)]=$0 x$/.to}</s>
{[~] .comb Zx 1..*}

Explanation:

{          # implicit parameter $_
  [~]      # string concatenate the following list
    .comb  # the NFG characters from $_
    Z[x]   # zip combined using the string repetition operator
    1 .. * # 1 to infinity
}


答:
TI-BASIC, 19 bytes

```<code>Prompt N,M
randIntNoRep(N,M
sum(Ans)<sup>2</sup>-sum(Ans<sup>2</sup>
</code>```

randIntNoRep gets the range (shuffled). The rest is pretty self explanatory.

Title: Difference of the square of the sum

Body:
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

Body:
TI-BASIC, 19 bytes

Prompt N,M
randIntNoRep(N,M
sum(Ans)2-sum(Ans2

randIntNoRep gets the range (shuffled). The rest is pretty self explanatory.


答:
Brainfuck, 15 bytes

```<code>,[>+[->+<<.>],]
</code>```

Pretty straightforward implementation, shifting the memory space by 1 for each input char. Requires an interpreter that gives 0 on EOF, and 32-bit/arbitrary precision cells for inputs longer than 255 chars.

Try it online! (Note: TIO uses 8-bit cells)

Title: Write a program to elasticize strings

Body:
Brainfuck, 15 bytes

,[>+[->+<<.>],]

Pretty straightforward implementation, shifting the memory space by 1 for each input char. Requires an interpreter that gives 0 on EOF, and 32-bit/arbitrary precision cells for inputs longer than 255 chars.

Try it online! (Note: TIO uses 8-bit cells)


答:
Julia, 34 bytes

!s=s>""?!s[1:(e=end)-1]*s[e:e]^e:s
```

Try it online!

Title: Write a program to elasticize strings

Body:
Julia, 34 bytes

!s=s>""?!s[1:(e=end)-1]*s[e:e]^e:s

Try it online!