问:
Prove that a Number is Algebraic
Inspired by this answer (emphasis mine):

We will play a game. Suppose you have some number x. You start with x and then you can add, subtract, multiply, or divide by any integer, except zero. You can also multiply by x. You can do these things as many times as you want. If the total becomes zero, you win.

For example, suppose x is 2/3. Multiply by 3, then subtract 2. The result is zero. You win!

Suppose x is 7^(1/3). Multiply by x , then by x again, then subtract 7. You win!

Suppose x is √2+√3. Here it's not easy to see how to win. But it turns out that if you multiply by x, subtract 10, multiply by x twice, and add 1, then you win. (This is not supposed to be obvious; you can try it with your calculator.)

But if you start with x=π, you cannot win. There is no way to get from π to 0 if you add, subtract, multiply, or divide by integers, or multiply by π, no matter how many steps you take. (This is also not supposed to be obvious. It is a very tricky thing!)

Numbers like √2+√3 from which you can win are called algebraic. Numbers like π with which you can't win are called transcendental.

Why is this interesting? Each algebraic number is related arithmetically to the integers, and the winning moves in the game show you how so. The path to zero might be long and complicated, but each step is simple and there is a path. But transcendental numbers are fundamentally different: they are not arithmetically related to the integers via simple steps.

Essentially, you will use the steps used in the question quoted above to "win" the game for given input.

Given a real, algebraic constant x, convert the number to zero by using the following allowed operations:

Add or Subtract an integer.

Multiply or Divide by a non-zero integer.

Multiply by the original constant x.

Input is a string that may contain integers, addition, subtraction, multiplication, division, exponentiation (your choice of ** or ^, exponents are used to represent roots), and parentheses. Spaces in the input are optional, but not in the output. You should output the steps necessary to obtain a result of zero, so multiplying by 7 as one step would be output as *7. A trailing space and/or newline is allowed.

Examples

```<code>0               ->  +0 (or any other valid, or empty)
5/7 + 42        ->  -42 *7 -5 (or shorter: *7 -299)
2^(1/3)         ->  *x *x -2
5*(3**(1/4))    ->  *x *x *x -1875
2^(1/2)+3^(1/2) ->  *x -10 *x *x +1
</code>```

Shortest code wins.

答:
Mathematica, 194 224 192 bytes

```<code>""<>Cases[HornerForm@MinimalPolynomial[ToExpression@#,x]//.{Times->t,x^a_:>Fold[#2~t~#&,x~Table~a],a_~t~b_~t~c_:>a~t~t[b,c]},a_~b_~_:>{b/.t:>"*"/.Plus:>If[a>0,"+",""],ToString@a," "},{0,∞}]&
</code>```

Here ∞ is the three byte unicode character representing infinity in Mathematica.

Since input is a string, 13 bytes are lost on ToExpression@ which interprets the string input as an algebraic expression.

```<code>HornerForm@MinimalPolynomial[2^(1/2)+3^(1/2), x]
</code>```

Would return something like

```<code>1 + x^2 (-10 + x^2)
</code>```

The next replacement rule massages this into something that is structurally like

```<code>1 + (x * (x * (-10 + (x * (x)))))
</code>```

This Horner form can be visualized like a tree:

We, by the rules of OP start out with the deepest leaf on the right.

Cases goes through the expression, starting at the deepest level, taking each parent node and its left leaf and assembling this into a table such as

```<code>"*" "x"   " "
""  "-10" " "
"*" "x"   " "
"*" "x"   " "
"+" "1"   " "
</code>```

""<> concatenates everything with the empty string.

Title: Prove that a Number is Algebraic

Body:
Mathematica, 194 224 192 bytes

""<>Cases[HornerForm@MinimalPolynomial[ToExpression@#,x]//.{Times->t,x^a_:>Fold[#2~t~#&,x~Table~a],a_~t~b_~t~c_:>a~t~t[b,c]},a_~b_~_:>{b/.t:>"*"/.Plus:>If[a>0,"+",""],ToString@a," "},{0,∞}]&

Here ∞ is the three byte unicode character representing infinity in Mathematica.

Since input is a string, 13 bytes are lost on ToExpression@ which interprets the string input as an algebraic expression.

HornerForm@MinimalPolynomial[2^(1/2)+3^(1/2), x]

Would return something like

1 + x^2 (-10 + x^2)

The next replacement rule massages this into something that is structurally like

1 + (x * (x * (-10 + (x * (x)))))

This Horner form can be visualized like a tree:

We, by the rules of OP start out with the deepest leaf on the right.

Cases goes through the expression, starting at the deepest level, taking each parent node and its left leaf and assembling this into a table such as

"*" "x"   " "
""  "-10" " "
"*" "x"   " "
"*" "x"   " "
"+" "1"   " "

""<> concatenates everything with the empty string.


问:
Visualise long multiplication with ASCII art

The challenge

Write a program that takes two integers from standard input, separated by a comma, and then prints a visualisation of long multiplication of those two integers to standard output.

Eg:

Input

```<code>14, 11
</code>```

Program output

```<code>     14
    x11
   _____
     14
    14
  ______
    154
</code>```

Input

```<code>-7, 20
</code>```

Program output

```<code>     -7
    x20
   _____
     00
    14
   _____
   -140
</code>```

Assume always correct inputs and numbers in the range [-999, 999]

Winning criteria

Shortest code wins!

ContentLicense: CC BY-SA 3.0

Body:
Perl, 157 151 150 144 141 133 chars :

($x,$y)=<>=~/[-\d]+/g;map{$z=~s/z/ z/g;$z=(abs$x*$_)."z$z"}split//,abs$y;map{printf"%6s
",$_}$x,"x$y",$b="-"x6,(split/z/,$z),$b,$x*$y

Usage :

>echo "-123, 456" | perl mult.pl
   -123
   x456
-------
    738
   615
  492
-------
 -56088


问:
Illiteral Prime numbers
Your challenge is to write a program (full program, not a function), that will take an integer and output all prime numbers up to (including) the given integer. Output is any readable list containing all integer primes (array, string, 1 prime per line, whatever you want) and must run to stdout or equivalent.

Simple? Here's the twist:

You may not use literals in your program. These include:

Literal numbers (0 through 9)

Literal strings (in quotes)

You may not use built in prime checks

EDIT: A prime check is a built in function that

Returns if a number is a prime number

Returns a prime number

Returns a list of prime numbers

You may code your own functions that do the above

Prime factorisation functions are allowed

As this is code-golf, shortest answer in bytes wins

答:
Mathematica, 43 bytes

```<code>Select[Range@Input[],Tr@Rest@Divisors@#==#&]
</code>```

Selects from a range of integers between 1 and Input[] those, the sum of whose divisors, except the first one (in ascending order) is equal to the number itself.

Title: Illiteral Prime numbers

Body:
Mathematica, 43 bytes

Select[Range@Input[],Tr@Rest@Divisors@#==#&]

Selects from a range of integers between 1 and Input[] those, the sum of whose divisors, except the first one (in ascending order) is equal to the number itself.


问:
Calculate Euler's totient function

Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

答:
Python 2, 57 bytes

f=lambda n,k=1,m=1:n*(k>n)or f(n-(n%k<m%k)*n/k,k+1,m*k*k)
```

Test it on Ideone.

Background

By Euler's product formula,

where φ denotes Euler's totient function and p varies only over prime numbers.

To identify primes, we use a corollary of Wilson's theorem:

How it works

At all times, the variable m will be equal to the square of the factorial of k - 1. In fact, we named arguments default to k = 1 and m = 0!2 = 1.

As long as k ≤ n, n*(k>n) evaluates to 0 and the code following or gets executed.

Recall that m%k will yield 1 if m is prime and 0 if not. This means that x%k<m%k will yield True if and only if both k is a prime number and x is divisible by k.

In this case, (n%k<m%k)*n/k yields n / k, and subtracting it from n replaces its previous value with n(1 - 1/k), as in Euler's product formula. Otherwise, (n%k<m%k)*n/k yields 0 and n remains unchanged.

After computing the above, we increment k and multiply m by the "old" value of k2, thus maintaining the desired relation between k and m, then call f recursively with the updated arguments.

Once k exceeds n, n*(k>n) evaluates to n, which is returned by the function.

Title: Calculate Euler's totient function

Body:
Python 2, 57 bytes

f=lambda n,k=1,m=1:n*(k>n)or f(n-(n%k<m%k)*n/k,k+1,m*k*k)

Test it on Ideone.

Background

By Euler's product formula,

where φ denotes Euler's totient function and p varies only over prime numbers.

To identify primes, we use a corollary of Wilson's theorem:

How it works

At all times, the variable m will be equal to the square of the factorial of k - 1. In fact, we named arguments default to k = 1 and m = 0!2 = 1.

As long as k ≤ n, n*(k>n) evaluates to 0 and the code following or gets executed.

Recall that m%k will yield 1 if m is prime and 0 if not. This means that x%k<m%k will yield True if and only if both k is a prime number and x is divisible by k.

In this case, (n%k<m%k)*n/k yields n / k, and subtracting it from n replaces its previous value with n(1 - 1/k), as in Euler's product formula. Otherwise, (n%k<m%k)*n/k yields 0 and n remains unchanged.

After computing the above, we increment k and multiply m by the "old" value of k2, thus maintaining the desired relation between k and m, then call f recursively with the updated arguments.

Once k exceeds n, n*(k>n) evaluates to n, which is returned by the function.


问:
Derivative at the Edge
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

答:
Julia, 8 bytes

gradient
```

Inspired by @MartinEnder's Python answer. Try it online!

Title: Derivative at the Edge

Body:
Julia, 8 bytes

gradient

Inspired by @MartinEnder's Python answer. Try it online!


Title: Count Up, Replace, Repeat!

Body:
Definition

Define the nth array of the CURR sequence as follows.

Begin with the singleton array A = [n].

For each integer k in A, replace the entry k with k natural numbers, counting up from 1 to k.

Repeat the previous step n - 1 more times.

For example, if n = 3, we start with the array [3].

We replace 3 with 1, 2, 3, yielding [1, 2, 3].

We now replace 1, 2, and 3 with 1; 1, 2 and 1, 2, 3 (resp.), yielding [1, 1, 2, 1, 2, 3].

Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]. This is the third CURR array.

Task

Write a program of a function that, given a strictly positive integer n as input, computes the nth CURR array.

The output has to be a flat list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.).

This is code-golf. May the shortest code in bytes win!

Test cases

```<code> 1 -> [1]
 2 -> [1, 1, 2]
 3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
 4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
 5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
 6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]
</code>```

Body:
Perl 5, 53 bytes

A subroutine:

{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}

See it in action as

perl -e'print "$_ " for sub{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}->(3)'


问:
Rube Goldberg Hello World
For this golf, you will need to use more than one language.

The task

A Rube Goldberg machine is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output Rube Goldberg... but not directly.

The machine

Your "machine" is the source code that, once executed, will give another source code in another language that will output Rube Goldberg upon execution. Got it?

I rephrase: your initial code must give another code, that other code must output Rube Goldberg. Both codes must be written in different languages.

The bonus which is more like the only fun way to do it

There is a bonus if your code outputs a code that will output a code that will ... that will output Rube Goldberg.

NOTE: any sort of output can be used (stdout, stderr, dialog box, ...)

The points

The number of points is equal to the number of bytes used in your code, divided by the number of distinct, extra languages that you used.

NOTE: different languages use different encodings. The number of bytes is counted in the initial language with its own encoding.

Examples

Pyth -> J -> Javascript -> output in 30 bytes = 30/2 = 15 points (J and Javascript are the extra languages)

Java -> C# -> C++ -> PHP -> output in 36 bytes = 36/3 = 12 points (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes))

C -> output in 10 bytes = 10/0 = Infinity points (No extra languages)

Python -> Perl -> Ruby -> Python -> Ruby in 44 bytes = 44/2 = 22 points (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used)

NOTE: Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes.

The answer

Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language).

The winner

Of course, like usual, the lowest score wins.

NOTE: As usual, standard loopholes and "cheats" are not allowed.

ContentLicense: CC BY-SA 4.0

Title: Rube Goldberg Hello World

Body:
Java->Thue->Javascript->Batch->Microscript II->Brainf***, 236/5=47.2

interface J{static void main(String[]a){System.out.print("a::=~alert`echo \"+++++[>+A<-]>[>++>+++<<-]>++.>---.<++AA.+++.>>++++[>+A<-]>.[>++>+++>+++<<<-]>A.>+AA.---.>++++.--.+++.<<<<<---.>>>>>++.\"`\n::=\na".replaceAll("A","+++++++"));}}

Generated Thue program:

a::=~alert`echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."`
::=
a

Generated Javascript program:

alert`echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."`

Generated Batch program:

echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."

Generated Microscript II program:

"+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."

Generated Brainf*** program:

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


答:
Dyalog APL, 14 bytes

```<code>((⊢~∘.×⍨)≢↓⍳)⎕
</code>```

Fully parenthesised:

```<code>(⊢ ~ ((∘.×)⍨)) (≢ ↓ ⍳)
</code>```

Every triple of functions applies the right and left monadic functions separately to whatever is outside of the parenthesis, and then the two results become the arguments of the middle function, thus (f g h)A is (f A) g (h A). This repeat itself until the following tree structure:

```<code>    ┌──────┴──────┐
 ┌──┼────┐     ┌──┼──┐
┌┴┐┌┴┐┌──┴──┐ ┌┴┐┌┴┐┌┴┐
│⊢││~││∘.× ⍨│ │≢││↓││⍳│
└─┘└─┘└─────┘ └─┘└─┘└─┘
</code>```

⎕ prompt for numeric input

Let's assume the user inputs 6:

≢ tally the input (giving 1) and ⍳ indices until the input (giving 1 2 3 4 5 6)

1 ↓ 1 2 3 4 5 6 drop 1 from the list (giving 2 3 4 5 6)

⊢ pass through (2 3 4 5 6) and ∘.×⍨ multiplication table:

```<code> 4  6  8 10 12
 6  9 12 15 18
 8 12 16 20 24
10 15 20 25 30
12 18 24 30 36
</code>```

2 3 4 5 6 ~ 4 6 8 10 12 6 9… "without" (i.e. set difference), yielding 2 3 5

TryAPL!

Title: Illiteral Prime numbers

Body:
Your challenge is to write a program (full program, not a function), that will take an integer and output all prime numbers up to (including) the given integer. Output is any readable list containing all integer primes (array, string, 1 prime per line, whatever you want) and must run to stdout or equivalent.

Simple? Here's the twist:

You may not use literals in your program. These include:

Literal numbers (0 through 9)

Literal strings (in quotes)

You may not use built in prime checks

EDIT: A prime check is a built in function that

Returns if a number is a prime number

Returns a prime number

Returns a list of prime numbers

You may code your own functions that do the above

Prime factorisation functions are allowed

As this is code-golf, shortest answer in bytes wins

Body:
Dyalog APL, 14 bytes

((⊢~∘.×⍨)≢↓⍳)⎕

Fully parenthesised:

(⊢ ~ ((∘.×)⍨)) (≢ ↓ ⍳)

Every triple of functions applies the right and left monadic functions separately to whatever is outside of the parenthesis, and then the two results become the arguments of the middle function, thus (f g h)A is (f A) g (h A). This repeat itself until the following tree structure:

    ┌──────┴──────┐
 ┌──┼────┐     ┌──┼──┐
┌┴┐┌┴┐┌──┴──┐ ┌┴┐┌┴┐┌┴┐
│⊢││~││∘.× ⍨│ │≢││↓││⍳│
└─┘└─┘└─────┘ └─┘└─┘└─┘

⎕ prompt for numeric input

Let's assume the user inputs 6:

≢ tally the input (giving 1) and ⍳ indices until the input (giving 1 2 3 4 5 6)

1 ↓ 1 2 3 4 5 6 drop 1 from the list (giving 2 3 4 5 6)

⊢ pass through (2 3 4 5 6) and ∘.×⍨ multiplication table:

 4  6  8 10 12
 6  9 12 15 18
 8 12 16 20 24
10 15 20 25 30
12 18 24 30 36

2 3 4 5 6 ~ 4 6 8 10 12 6 9… "without" (i.e. set difference), yielding 2 3 5

TryAPL!


答:
Hoon, 56 bytes

```<code>|=
a/@
(lent (skim (gulf 1 a) |=(@ =(1 d:(egcd +< a)))))
</code>```

Measure the length of the list [1...a] after keeping all the elements where GCD(i, a) == 1

Title: Calculate Euler's totient function

Body:
Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

Body:
Hoon, 56 bytes

|=
a/@
(lent (skim (gulf 1 a) |=(@ =(1 d:(egcd +< a)))))

Measure the length of the list [1...a] after keeping all the elements where GCD(i, a) == 1


答:
J, 7 bytes

```<code>~.@q:@!
</code>```

~. unique @ of q: prime factors @ of ! factorial

Title: Illiteral Prime numbers

Body:
J, 7 bytes

~.@q:@!

~. unique @ of q: prime factors @ of ! factorial


问:
Generate a valid sequence of numbers with specific rules

The challenge

The program must return a valid sequence of numbers into some rules

Rules

x is the size of the sequence;

x cannot be less than 4 or greater than 9 (Thanks David Carraher);

Digits of the sentence can't repeat, each one must appear once;

All digits between 1 to x must be in the sequence;

A valid sequence never begins nor ends with 1 or x;

Into the sequence, numbers can never appear "together";

Examples

If x=4:

2413 valid

3142 valid

1423 not valid, because begins with 1 and 23 are "together".

2134 not valid, because ends with x and 34 are "together".

Still don't get it?
Other example:

If x=8:

28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)

Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.

Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;

Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;

The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

答:
Haskell 78

```<code>a 4=[3,1,4,2]
a x=let b=filter even [1..x]++filter odd[1..x]in tail b++[b!!0]
</code>```

This defines a function a that takes one parameter, the desired length of the sequence. This function returns a list of numbers in that sequence. I believe this works for x >= 4

This can probably be golfed further (I don't have that much experience in haskell)

Example (in ghci)

```<code>ghci> a 4
[3,1,4,2]
ghci> a 9
[4,6,8,1,3,5,7,9,2]
</code>```

Haskell 25

This version is from before a rule change that now requires that every digit from 1 to x be used exactly once in the sequence

This should work for any sequence of length > 2 (even though the rules only required 4 <= x <= 9)

```<code>putStrLn$take x$cycle"02"
</code>```

Input

The number of digits in the sequence is stored in x.

Output

x = 6 :: Int

```<code>020202
</code>```

x = 4 :: Int

```<code>0202
</code>```

Body:
Haskell 78

a 4=[3,1,4,2]
a x=let b=filter even [1..x]++filter odd[1..x]in tail b++[b!!0]

This defines a function a that takes one parameter, the desired length of the sequence. This function returns a list of numbers in that sequence. I believe this works for x >= 4

This can probably be golfed further (I don't have that much experience in haskell)

Example (in ghci)

ghci> a 4
[3,1,4,2]
ghci> a 9
[4,6,8,1,3,5,7,9,2]

Haskell 25

This version is from before a rule change that now requires that every digit from 1 to x be used exactly once in the sequence

This should work for any sequence of length > 2 (even though the rules only required 4 <= x <= 9)

putStrLn$take x$cycle"02"

Input

The number of digits in the sequence is stored in x.

Output

x = 6 :: Int

020202

x = 4 :: Int

0202


答:
Pyth, 14 bytes

```<code>.OM>L2._seB-Vt
</code>```

Try it online: Demonstration

Explanation:

```<code>.OM>L2._seB-VtQQ   implicitly add two Qs (input arrays) at the end
           -VtQQ   get all neighbored differences
        seB        get the last element of ^ and append it to ^
      ._           compute all prefixes
   >L2             reduce all prefixes to the last two elements
.OM                compute the average of each ^
</code>```

Title: Derivative at the Edge

Body:
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

Body:
Pyth, 14 bytes

.OM>L2._seB-Vt

Try it online: Demonstration

Explanation:

.OM>L2._seB-VtQQ   implicitly add two Qs (input arrays) at the end
           -VtQQ   get all neighbored differences
        seB        get the last element of ^ and append it to ^
      ._           compute all prefixes
   >L2             reduce all prefixes to the last two elements
.OM                compute the average of each ^


答:
J, 21 bytes

```<code>[:((,{:)+{.,])2-~/\-:
</code>```

Similar to the approach used in @David's solution.

Usage

```<code>   f =: [:((,{:)+{.,])2-~/\-:
   f 0.034 9.62 8.885 3.477 2.38
9.586 4.4255 _3.0715 _3.2525 _1.097
</code>```

Explanation

```<code>[:((,{:)+{.,])2-~/\-:  Input: list A
                   -:  Halve each value in A
              2   \    Select each overlapping sublist of size 2 in A
               -~/     Reduce it using subtraction to get the difference
[:(          )         Operate on the list of differences, call it D
            ]          Identity function, returns D
         {.            Get the head of D
           ,           Join them to get [head(D), D]
   ( {:)               Get the tail of D
    ,                  Join them to get [D, tail(D)]
        +              Add them together elementwise to get the derivatives and return
</code>```

Title: Derivative at the Edge

Body:
J, 21 bytes

[:((,{:)+{.,])2-~/\-:

Similar to the approach used in @David's solution.

Usage

   f =: [:((,{:)+{.,])2-~/\-:
   f 0.034 9.62 8.885 3.477 2.38
9.586 4.4255 _3.0715 _3.2525 _1.097

Explanation

[:((,{:)+{.,])2-~/\-:  Input: list A
                   -:  Halve each value in A
              2   \    Select each overlapping sublist of size 2 in A
               -~/     Reduce it using subtraction to get the difference
[:(          )         Operate on the list of differences, call it D
            ]          Identity function, returns D
         {.            Get the head of D
           ,           Join them to get [head(D), D]
   ( {:)               Get the tail of D
    ,                  Join them to get [D, tail(D)]
        +              Add them together elementwise to get the derivatives and return


问:
Convert YYYYMM to MMMYY
Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.

Last two digits will be between 01 and 12.

Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

```<code>MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC
</code>```

Examples:

```<code>Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
</code>```

答:
PowerShell, <s>49</s> <s>46</s> 40 bytes

date "$args".insert(4,'-')-U %b%y|% *per
```

<p>Try it online!</p>

<p><em>Thanks to @Joey for saving 3 bytes!</em></p>

<p>Takes input <code>$args</code> as an explicit string (e.g., <code>'201604'</code>) via command-line input. Uses the <code>string.Insert()</code> function to put a <code>-</code> in the appropriate space, and that resultant string forms input to the <code>Get-Date</code> cmdlet with the <code>-U</code>format parameter specifying the three-month shorthand plus two-digit year. We then tack on a <code>.ToUpper()</code> to make the output string capitalized. That string is left on the pipeline and printing is implicit.</p>

<p>Also, as pointed out, this is locale-sensitive. Here's the locale information that I'm using where this works correctly.</p>

<pre class="lang-powershell prettyprint-override"><code>PS C:\Tools\Scripts\golfing> get-culture

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)
</code>```

Title: Convert YYYYMM to MMMYY

Body:
PowerShell, <s>49</s> <s>46</s> 40 bytes

date "$args".insert(4,'-')-U %b%y|% *per

Try it online!

Thanks to @Joey for saving 3 bytes!

Takes input $args as an explicit string (e.g., '201604') via command-line input. Uses the string.Insert() function to put a - in the appropriate space, and that resultant string forms input to the Get-Date cmdlet with the -Uformat parameter specifying the three-month shorthand plus two-digit year. We then tack on a .ToUpper() to make the output string capitalized. That string is left on the pipeline and printing is implicit.

Also, as pointed out, this is locale-sensitive. Here's the locale information that I'm using where this works correctly.

PS C:\Tools\Scripts\golfing> get-culture

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)


答:
CJam, <s>50</s> 46 bytes

```<code>q2/1>~i("4H~0ë~³!ò²×¶7Ö"256b25b'Af+3/=\
</code>```

Try it online. Thanks to Martin Ender for compressing the string to save a few bytes.

Explanation

```<code>q2/  e# Get input and divide it into groups of 2, like ["20" "16" "04"]
1>~  e# Discard the first item and dump the remaining array to the stack
i(   e# Convert the top value (month) to an integer and decrement it, because
     e# arrays are zero-indexed
"..."256b25b e# Convert this string from base-256 to base-25
'Af+ e# "Add" a capital A to each number to get the letters
3/   e# Divide into groups of 3 to make an array of month names
=\   e# Get the requested month and swap the elements to put the year on
     e# top, so it is printed last
</code>```

Title: Convert YYYYMM to MMMYY

Body:
Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.

Last two digits will be between 01 and 12.

Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

```<code>MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC
</code>```

Examples:

```<code>Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
</code>```

Body:
CJam, <s>50</s> 46 bytes

q2/1>~i("4H~0ë~³!ò²×¶7Ö"256b25b'Af+3/=\

Try it online. Thanks to Martin Ender for compressing the string to save a few bytes.

Explanation

q2/  e# Get input and divide it into groups of 2, like ["20" "16" "04"]
1>~  e# Discard the first item and dump the remaining array to the stack
i(   e# Convert the top value (month) to an integer and decrement it, because
     e# arrays are zero-indexed
"..."256b25b e# Convert this string from base-256 to base-25
'Af+ e# "Add" a capital A to each number to get the letters
3/   e# Divide into groups of 3 to make an array of month names
=\   e# Get the requested month and swap the elements to put the year on
     e# top, so it is printed last


答:
05AB1E, <s>51</s> <s>42</s> 41 bytes

```<code>2ô¦`ï<•r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B3ôsèsJ
</code>```

Explanation

```<code>                                           # implicit input, 123405
2ô                                         # split input into pieces of 2, ['12','34','05']
  ¦`                                       # push last 2 elements to stack, '05', '34'
    ï<                                     # convert month to its int index, 4
      •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B        # get compressed string containing 3-letter months,
                                             JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC
                                   3ô      # split into pieces of 3
                                             ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
                                     sè    # get month at index retrieved earlier, MAY
                                       sJ  # join with 2-digit year and implicitly print, MAY34
</code>```

Try it online

9 bytes saved thanks to string compression, courtesy of @Adnan

Title: Convert YYYYMM to MMMYY

Body:
05AB1E, <s>51</s> <s>42</s> 41 bytes

2ô¦`ï<•r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B3ôsèsJ

Explanation

                                           # implicit input, 123405
2ô                                         # split input into pieces of 2, ['12','34','05']
  ¦`                                       # push last 2 elements to stack, '05', '34'
    ï<                                     # convert month to its int index, 4
      •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B        # get compressed string containing 3-letter months,
                                             JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC
                                   3ô      # split into pieces of 3
                                             ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
                                     sè    # get month at index retrieved earlier, MAY
                                       sJ  # join with 2-digit year and implicitly print, MAY34

Try it online

9 bytes saved thanks to string compression, courtesy of @Adnan


Title: Rube Goldberg Hello World

Body:
For this golf, you will need to use more than one language.

The task

A Rube Goldberg machine is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output Rube Goldberg... but not directly.

The machine

Your "machine" is the source code that, once executed, will give another source code in another language that will output Rube Goldberg upon execution. Got it?

I rephrase: your initial code must give another code, that other code must output Rube Goldberg. Both codes must be written in different languages.

The bonus which is more like the only fun way to do it

There is a bonus if your code outputs a code that will output a code that will ... that will output Rube Goldberg.

NOTE: any sort of output can be used (stdout, stderr, dialog box, ...)

The points

The number of points is equal to the number of bytes used in your code, divided by the number of distinct, extra languages that you used.

NOTE: different languages use different encodings. The number of bytes is counted in the initial language with its own encoding.

Examples

Pyth -> J -> Javascript -> output in 30 bytes = 30/2 = 15 points (J and Javascript are the extra languages)

Java -> C# -> C++ -> PHP -> output in 36 bytes = 36/3 = 12 points (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes))

C -> output in 10 bytes = 10/0 = Infinity points (No extra languages)

Python -> Perl -> Ruby -> Python -> Ruby in 44 bytes = 44/2 = 22 points (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used)

NOTE: Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes.

The answer

Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language).

The winner

Of course, like usual, the lowest score wins.

NOTE: As usual, standard loopholes and "cheats" are not allowed.

Body:
JS -> Cobol -> Python -> IBM 360 BAL

261 bytes/4 languages = 65.25 Points

Was aiming to use difficult languages, with more obfuscation. Javascript converts the string from base64 into Cobol, which produces Python that decodes the BAL code from hex.

Javascript

console.log(atob(' 1
    LH8T88d@05R850T8LT88!Q!R Cek*k{[~&vgm88yx9m4m6y6m8wx9m6}s}6Ovm9m6kg7m4m6x{m69x{6Ovm8wOxxg8Ovm9yOym4m6sv9x{6Ovm8km69Oxs}w}snxv86m69Ox7}m69x{49xyx}wws88wsg88oww}g4Ovkm4Oxyxww}}7g8{9swyyg9wyym6Ovm8Oxwxm6fm6gyxm8sox6m6gyxm6gkm6gLP');

Cobol

IDENTIFICATION DIVISION.
 PROGRAM-ID. Rube.
 ENVIRONMENT DIVISION.
 DATA DIVISION.
 PROCEDURE DIVISION.
    Display ' print bytearray.fromhex("202f2f204558454320415353454d424c5920092020535441525420204d41494e0942414c522020322c30200920205553494e47202a2c32200920204f50454e20205052494e54200920204d5643094255462c485720092020505554095052494e5420092020434c4f5345205052494e5420092020454f4a2020485709444309434c3133325c275255424520474f4c44424552475c27202042554609445309434c31333220205052494e5409445446505220494f41524541313d4255462c444556414444523d5359534c53542c424c4b53495a453d3133322c09092a2009094445564943453d333230332c434f4e54524f4c3d5945532c5052494e544f563d5945532020092020454e44094d41494e20202f2a20202f2f2045584543204c4e4b45445420202f2f204558454320202f2a20202f26").decode()'.
    STOP RUN.

Python

 print bytearray.fromhex("202f2f204558454320415353454d424c5920092020535441525420204d41494e0942414c522020322c30200920205553494e47202a2c32200920204f50454e20205052494e54200920204d5643094255462c485720092020505554095052494e5420092020434c4f5345205052494e5420092020454f4a2020485709444309434c3133325c275255424520474f4c44424552475c27202042554609445309434c31333220205052494e5409445446505220494f41524541313d4255462c444556414444523d5359534c53542c424c4b53495a453d3133322c09092a2009094445564943453d333230332c434f4e54524f4c3d5945532c5052494e544f563d5945532020092020454e44094d41494e20202f2a20202f2f2045584543204c4e4b45445420202f2f204558454320202f2a20202f26").decode()

IBM 360 BAL

 // EXEC ASSEMBLY
      START
 MAIN   BALR  2,0
      USING *,2
      OPEN  PRINT
      MVC   BUF,HW
      PUT   PRINT
      CLOSE PRINT
      EOJ
 HW DC  CL132'RUBE GOLDBERG'
 BUF    DS  CL132
 PRINT  DTFPR IOAREA1=BUF,DEVADDR=SYSLST,BLKSIZE=132,       *
        DEVICE=3203,CONTROL=YES,PRINTOV=YES
      END   MAIN
 /*
 // EXEC LNKEDT
 // EXEC
 /*
 /&

Output

RUBE GOLDBERG


答:
JavaScript, <s>87</s> <s>84</s> <s>80</s> 79 bytes

```<code>x=>(new Date(x.replace(/.{4}/,'$&-'))+'').slice(4,7).toUpperCase()+x.slice(2,4)
</code>```

To get the month, gets the date (which is formed of "YYYYMM" converted to "YYYY-MM") and retrieves the characters 5 to 8, that are exactly the first three letters of the month. But it costs much to convert it to upper case.

Demo:

function s(x) {
  return (new Date(x.replace(/.{4}/, '$&-')) + '').slice(4,7)
         .toUpperCase() + x.slice(2, 4)
}

console.log(s('201604'));
console.log(s('200001'));
console.log(s('000112'));
console.log(s('123405'));```

Title: Convert YYYYMM to MMMYY

Body:
JavaScript, <s>87</s> <s>84</s> <s>80</s> 79 bytes

x=>(new Date(x.replace(/.{4}/,'$&-'))+'').slice(4,7).toUpperCase()+x.slice(2,4)

To get the month, gets the date (which is formed of "YYYYMM" converted to "YYYY-MM") and retrieves the characters 5 to 8, that are exactly the first three letters of the month. But it costs much to convert it to upper case.

Demo:

function s(x) {
  return (new Date(x.replace(/.{4}/, '$&-')) + '').slice(4,7)
         .toUpperCase() + x.slice(2, 4)
}

console.log(s('201604'));
console.log(s('200001'));
console.log(s('000112'));
console.log(s('123405'));


答:
J, 70 bytes

```<code>4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]
</code>```

Usage

```<code>   f =: 4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]
   f '201604'
APR16
   f '200001'
JAN00
   f '000112'
DEC01
   f '123405'
MAY34
</code>```

Explanation

```<code>4(}.((,~(_3]\'...'){~1-~".)~2&}.){.)] Input: s
                                    ] Identity function, gets the value s
4                                     The constant 4
                                 {.   Take the first 4 chars from s
                            2&}.      Drop the first 2 (Take the last 2) to get the year
  }.                                  Drop the first 4 chars from s to get the month
                        ".            Parse the month substring as a number
                     1-~              Subtract 1 from it
             '...'                    List of MMM month names
         _3]\                         Split the list into nonoverlapping sublists of size 3
      ,~                              Join the MMM month name with the year and return
</code>```

Title: Convert YYYYMM to MMMYY

Body:
J, 70 bytes

4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]

Usage

   f =: 4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]
   f '201604'
APR16
   f '200001'
JAN00
   f '000112'
DEC01
   f '123405'
MAY34

Explanation

4(}.((,~(_3]\'...'){~1-~".)~2&}.){.)] Input: s
                                    ] Identity function, gets the value s
4                                     The constant 4
                                 {.   Take the first 4 chars from s
                            2&}.      Drop the first 2 (Take the last 2) to get the year
  }.                                  Drop the first 4 chars from s to get the month
                        ".            Parse the month substring as a number
                     1-~              Subtract 1 from it
             '...'                    List of MMM month names
         _3]\                         Split the list into nonoverlapping sublists of size 3
      ,~                              Join the MMM month name with the year and return


答:
JavaScript ES6, <s>77</s> 66 bytes

Saved 11 bytes thanks to @Bálint!

```<code>a=>(new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]
</code>```

Get's the date by extracting the string returned by the Date class. then capitalizes and adds the year.

ES5 version:

var a = prompt("Enter YYYYMM: ");
result = (new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]
alert(result);```

Title: Convert YYYYMM to MMMYY

Body:
JavaScript ES6, <s>77</s> 66 bytes

Saved 11 bytes thanks to @Bálint!

a=>(new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]

Get's the date by extracting the string returned by the Date class. then capitalizes and adds the year.

ES5 version:

var a = prompt("Enter YYYYMM: ");
result = (new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]
alert(result);


问:
Partition of a positive integer N
Find the number of partitions of a positive integer n. Hope someone uses the explicit finite formula for the partition function defined in Jan Hendrik Brunier and Ken Ono paper here.

```<code>Sample Input
8
Sample Output
22
</code>```

N is less than or equal to 1000.
Write the complete program. More than anything I would like to see the different approaches.

答:
Perl, 92 chars

Recursive solution using p(k,n) = number of partitions of n using numbers >= k. Uses dynamic programming and partitions 1000 in 2s on my machine.

```<code>sub p{my($k,$n)=@_;$c{$k,$n}||($c{$k,$n}=$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k)}print p(1,pop)
</code>```

Ungolfed:

```<code>sub p {
    my ( $k, $n ) = @_;
    $c{$k,$n}
    || (
        $c{$k,$n} =
        $k < $n
            ? p($k+1,$n) + p($k,$n-$k)
            : $n == $k
    )
}
print p( 1, pop );
</code>```

ContentLicense: CC BY-SA 2.5

Title: Partition of a positive integer N

Body:
Perl, 92 chars

Recursive solution using p(k,n) = number of partitions of n using numbers >= k. Uses dynamic programming and partitions 1000 in 2s on my machine.

sub p{my($k,$n)=@_;$c{$k,$n}||($c{$k,$n}=$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k)}print p(1,pop)

Ungolfed:

sub p {
    my ( $k, $n ) = @_;
    $c{$k,$n}
    || (
        $c{$k,$n} =
        $k < $n
            ? p($k+1,$n) + p($k,$n-$k)
            : $n == $k
    )
}
print p( 1, pop );


答:
Perl 96 chars (obsolete solution since the new rules)

For what I can understand from the rules, we can assume that X is predefined.
Then this solution should work :

```<code>for(2x$x..9x$x){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print;exit}}
</code>```

which is 96 characters long, although the algorithm is very naive.

It gives the following solutions :

```<code>2
30
240
2402
24020
240202
2402020
24020202
240202020
</code>```

Thus, it seems obvious than there is room to a much simpler program which directly computes a solution of this form...

The following program outputs all valid sequences with any given length X (takes X in STDIN)

```<code>$x=<>;$b=10**$x;for($b/10..$b-1){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}
</code>```

If you want to output ALL possible solutions (for any X), then the program becomes (102 chars) :

```<code>for(;;){$x=length$_++;if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}
</code>```

Title: Generate a valid sequence of numbers with specific rules

Body:
The challenge

The program must return a valid sequence of numbers into some rules

Rules

x is the size of the sequence;

x cannot be less than 4 or greater than 9 (Thanks David Carraher);

Digits of the sentence can't repeat, each one must appear once;

All digits between 1 to x must be in the sequence;

A valid sequence never begins nor ends with 1 or x;

Into the sequence, numbers can never appear "together";

Examples

If x=4:

2413 valid

3142 valid

1423 not valid, because begins with 1 and 23 are "together".

2134 not valid, because ends with x and 34 are "together".

Still don't get it?
Other example:

If x=8:

28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)

Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.

Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;

Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;

The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

Body:
Perl 96 chars (obsolete solution since the new rules)

For what I can understand from the rules, we can assume that X is predefined.
Then this solution should work :

for(2x$x..9x$x){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print;exit}}

which is 96 characters long, although the algorithm is very naive.

It gives the following solutions :

2
30
240
2402
24020
240202
2402020
24020202
240202020

Thus, it seems obvious than there is room to a much simpler program which directly computes a solution of this form...

The following program outputs all valid sequences with any given length X (takes X in STDIN)

$x=<>;$b=10**$x;for($b/10..$b-1){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}

If you want to output ALL possible solutions (for any X), then the program becomes (102 chars) :

for(;;){$x=length$_++;if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}


答:
Python, 83 bytes

```<code>from datetime import*
lambda x:datetime.strptime(x,'%Y%m').strftime('%b%y').upper()
</code>```

Title: Convert YYYYMM to MMMYY

Body:
Python, 83 bytes

from datetime import*
lambda x:datetime.strptime(x,'%Y%m').strftime('%b%y').upper()


问:
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.

答:
Factor, 48 bytes

```<code>[ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ]
</code>```

An anonymous function.

```<code>[
  [a,b] ! a range from a to b
  [
    [ sq ] map sum ! anonymous function: map sq over the range and sum the result
  ]
  [ sum sq ] ! the same thing, in reverse order
  bi - abs   ! apply both anon funcs to the range, subtract them and abs the result
]
</code>```

Title: Difference of the square of the sum

Body:
Factor, 48 bytes

[ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ]

An anonymous function.

[
  [a,b] ! a range from a to b
  [
    [ sq ] map sum ! anonymous function: map sq over the range and sum the result
  ]
  [ sum sq ] ! the same thing, in reverse order
  bi - abs   ! apply both anon funcs to the range, subtract them and abs the result
]


答:
Kotlin, 100 bytes

```<code>fun f(d:String)=SimpleDateFormat("MMMyy").format(SimpleDateFormat("yyyyMM").parse(d)).toUpperCase()
</code>```

Pretty straight forward use of Java SimpleDateFormat

Title: Convert YYYYMM to MMMYY

Body:
Kotlin, 100 bytes

fun f(d:String)=SimpleDateFormat("MMMyy").format(SimpleDateFormat("yyyyMM").parse(d)).toUpperCase()

Pretty straight forward use of Java SimpleDateFormat


答:
Python 3, 70 bytes

```<code>from time import*
lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper()
</code>```

This uses the built-in strftime and strptime functions.

For 1 byte more, here's a version which parses the string manually:

```<code>lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4]
</code>```

This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte).

Title: Convert YYYYMM to MMMYY

Body:
Python 3, 70 bytes

from time import*
lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper()

This uses the built-in strftime and strptime functions.

For 1 byte more, here's a version which parses the string manually:

lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4]

This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte).


答:
C → JS → Shell → ><>: 68 / 3 = 22.67

C

```<code>main(){puts("console.log(`echo '\"Rube Goldberg\"ar!;ooooooo|'`)");}
</code>```

Javascript

```<code>console.log(`echo '"Rube Goldberg"ar!;ooooooo|'`)
</code>```

Shell

```<code>echo '"Rube Goldberg"ar!;ooooooo|'
</code>```

><>

```<code>"Rube Goldberg"ar!;ooooooo|
</code>```

Result:

```<code>Rube Goldberg
</code>```

as required.

Title: Rube Goldberg Hello World

Body:
C → JS → Shell → ><>: 68 / 3 = 22.67

C

main(){puts("console.log(`echo '\"Rube Goldberg\"ar!;ooooooo|'`)");}

Javascript

console.log(`echo '"Rube Goldberg"ar!;ooooooo|'`)

Shell

echo '"Rube Goldberg"ar!;ooooooo|'

><>

"Rube Goldberg"ar!;ooooooo|

Result:

Rube Goldberg

as required.


问:
Lossy ASCII art compression

Background

PICASCII is a neat tool that converts images into ASCII art.

It achieves different degrees of brightness by using the following ten ASCII characters:

```<code>@#+';:,.`
</code>```

We'll say that these charxels (character elements) have brightnesses from 1 (at-sign) to 10 (space).

Below, you can see the results of converting a little code, the Welsh flag, an overhanded fractal, a large trout and a little golf, displayed with the correct font:

Your can see the images in this fiddle and download them from Google Drive.

Task

While the end results of PICASCII are visually pleasing, all five images combined weigh 153,559 bytes. How much could these images be compressed if we are willing to sacrifice part of their quality?

Your task is to write a program that accepts an ASCII art image such as the above ones and a minimum quality as input and prints a lossy compression of the image – in form of a full program or a function returning a single string – that satisfies the quality requirement.

This means that you do not get to write a separate decompressor; it must be built-in into each of the compressed images.

The original image will consist of charxels with brightnesses between 1 and 10, separated by linefeeds into lines of the same length. The compressed image must have the same dimensions and use the same set of characters.

For an uncompressed image consisting of n charxels, the quality of a compressed version of the image is defined as

where ci is the brightness of the ith charxel of the compressed image's output and ui the brightness of the ith charxel of the uncompressed image.

Scoring

Your code will be run with the five images from above as input and minimum quality settings of 0.50, 0.60, 0.70, 0.80 and 0.90 for each of the images.

Your score is the geometric mean of the sizes of all compressed images, i.e., the twenty-fifth root of the product of the lengths of all twenty-five compressed images.

The lowest score wins!

Additional rules

Your code has to work for arbitrary images, not just the ones used for scoring.

It is expected that you optimize your code towards the test cases, but a program that does not even attempt to compress arbitrary images won't get an upvote from me.

Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images.

Bulit-ins normally used in byte stream decompressors (e.g., base conversion, run-length decoding) are allowed.

Compressor and compressed images do not have to be in the same language.

However, you must pick a single language for all compressed images.

For each compressed image, standard code golf rules apply.

Verification

I've made a CJam script to easily verify all quality requirements and calculate a submission's score.

You can download the Java interpreter from here or here.

```<code>e# URLs of the uncompressed images.
e# "%s" will get replaced by 1, 2, 3, 4, 5.

"file:///home/dennis/codegolf/53199/original/image%s.txt"

e# URLs of the compressed images (source code).
e# "%s-%s" will get replaced by "1-50", "1-60", ... "5-90".

"file:///home/dennis/codegolf/53199/code/image%s-%s.php"

e# URLs of the compressed images (output).

"file:///home/dennis/codegolf/53199/output/image%s-%s.txt"

e# Code

:O;:C;:U;5,:)
{
    5,5f+Af*
    {
        C[IQ]e%g,X*:X;
        ISQS
        [U[I]e%O[IQ]e%]
        {g_W=N&{W<}&}%
        _Nf/::,:=
        {
            {N-"@#+';:,.` "f#}%z
            _::m2f#:+\,81d*/mq1m8#
            _"%04.4f"e%S
            @100*iQ<"(too low)"*
        }{
            ;"Dimension mismatch."
        }?
        N]o
    }fQ
}fI
N"SCORE: %04.4f"X1d25/#e%N
</code>```

Example

Bash → PHP, score 30344.0474

```<code>cat
</code>```

Achieves 100% quality for all inputs.

```<code>$ java -jar cjam-0.6.5.jar vrfy.cjam
1 50 1.0000
1 60 1.0000
1 70 1.0000
1 80 1.0000
1 90 1.0000
2 50 1.0000
2 60 1.0000
2 70 1.0000
2 80 1.0000
2 90 1.0000
3 50 1.0000
3 60 1.0000
3 70 1.0000
3 80 1.0000
3 90 1.0000
4 50 1.0000
4 60 1.0000
4 70 1.0000
4 80 1.0000
4 90 1.0000
5 50 1.0000
5 60 1.0000
5 70 1.0000
5 80 1.0000
5 90 1.0000

SCORE: 30344.0474
</code>```

答:
Java → CJam, score ≈4417.89

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.aditsu.cjam.CJam;

public class Compress {
    protected static final char[] DIGITS = "0123456789ABCDEFGHIJK".toCharArray();
    protected static final String CHARS = "@#+';:,.` ";
    protected static final char[] CHR = CHARS.toCharArray();

    private static class Img {
        public final int rows;
        public final int cols;
        public final int[][] a;

        public Img(final int rows, final int cols) {
            this.rows = rows;
            this.cols = cols;
            a = new int[rows][cols];
        }

        public Img(final List<String> l) {
            rows = l.size();
            cols = l.get(0).length();
            a = new int[rows][cols];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    a[i][j] = CHARS.indexOf(l.get(i).charAt(j));
                }
            }
        }

        public static Img read(final Reader r) {
            try {
                final BufferedReader br = new BufferedReader(r);
                final List<String> l = new ArrayList<>();
                while (true) {
                    final String s = br.readLine();
                    if (s == null || s.isEmpty()) {
                        break;
                    }
                    l.add(s);
                }
                br.close();
                return new Img(l);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public static Img read(final File f) {
            try {
                return read(new FileReader(f));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public Img scaleDown(final int fr, final int fc) {
            final int r1 = (rows + fr - 1) / fr;
            final int c1 = (cols + fc - 1) / fc;
            final Img x = new Img(r1, c1);
            final int[][] q = new int[r1][c1];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[i / fr][j / fc] += a[i][j];
                    q[i / fr][j / fc]++;
                }
            }
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] /= q[i][j];
                }
            }
            return x;
        }

        public Img scaleUp(final int fr, final int fc) {
            final int r1 = rows * fr;
            final int c1 = cols * fc;
            final Img x = new Img(r1, c1);
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] = a[i / fr][j / fc];
                }
            }
            return x;
        }

        public Img crop(final int r, final int c) {
            if (r == rows && c == cols) {
                return this;
            }
            final Img x = new Img(r, c);
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    x.a[i][j] = a[i][j];
                }
            }
            return x;
        }

        public Img rescale(final int fr, final int fc) {
            return scaleDown(fr, fc).scaleUp(fr, fc).crop(rows, cols);
        }

        public double quality(final Img x) {
            if (x.rows != rows || x.cols != cols) {
                throw new IllegalArgumentException();
            }
            double t = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    final int y = a[i][j] - x.a[i][j];
                    t += y * y;
                }
            }
            t /= 81 * rows * cols;
            t = 1 - Math.sqrt(t);
            return Math.pow(t, 8);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    sb.append(CHR[a[i][j]]);
                }
                sb.append('\n');
            }
            return sb.toString();
        }

        public Array toArray() {
            final Array x = new Array(rows * cols);
            int k = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[k++] = a[i][j];
                }
            }
            return x;
        }

        public String compress(final double quality) {
            int bi = 1;
            int bj = 1;
            int bs = rows * cols;
            Img bx = this;

            for (int i = 1; i < 3; ++i) {
                for (int j = 1; j < 3; ++j) {
                    Img x = rescale(i, j);
                    if (quality(x) >= quality) {
                        x = scaleDown(i, j);
                        if (x.rows * x.cols < bs) {
                            bi = i;
                            bj = j;
                            bs = x.rows * x.cols;
                            bx = x;
                        }
                    }
                }
            }

            Array a = bx.toArray();
            int bf = 0;
            for (int i = 1; i <= 20; ++i) {
                final int t = a.rle11(i).n;
                if (t < bs) {
                    bs = t;
                    bf = i;
                }
            }

            int b = 10;
            if (bf > 0) {
                b = 11;
                a = a.rle11(bf);
            }

            String s = null;
            for (int i = 92; i < 97; ++i) {
                for (char c = ' '; c < '$'; ++c) {
                    final String t = a.cjamBase(b, i, c);
                    boolean ok = true;
                    for (int j = 0; j < t.length(); ++j) {
                        if (t.charAt(j) > '~') {
                            ok = false;
                            break;
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    if (s == null || t.length() < s.length()) {
                        s = t;
                    }
                }
            }

            if (bf > 0) {
                s += "{(_A={;()";
                if (bf > 1) {
                    s += DIGITS[bf] + "*";
                }
                s += "\\(a@*}&\\}h]e_";
            }
            if (bi * bj == 1) {
                return s + '"' + CHARS + "\"f=" + cols + "/N*";
            }
            s += bx.cols + "/";
            if (bi > 1) {
                s += bi + "e*";
                if (rows % 2 == 1) {
                    s += "W<";
                }
            }
            if (bj > 1) {
                s += bj + "fe*";
                if (cols % 2 == 1) {
                    s += "Wf<";
                }
            }
            return s + '"' + CHARS + "\"ff=N*";
        }

        public void verify(final String s, final double quality) {
            final String t = CJam.run(s, "");
            final Img x = read(new StringReader(t));
            final double q = quality(x);
            if (q < quality) {
                throw new RuntimeException(q + " < " + quality);
            }
//          System.out.println(q + " >= " + quality);
        }
    }

    private static class Array {
        public final int[] a;
        public final int n;

        public Array(final int n) {
            this.n = n;
            a = new int[n];
        }

        public Array(final int[] a) {
            this.a = a;
            n = a.length;
        }

        public String join() {
            final StringBuilder sb = new StringBuilder();
            for (int x : a) {
                sb.append(x).append(' ');
            }
            sb.setLength(sb.length() - 1);
            return sb.toString();
        }

//      public String cjamStr() {
//          final StringBuilder sb = new StringBuilder("\"");
//          for (int x : a) {
//              sb.append(DIGITS[x]);
//          }
//          sb.append("\":~");
//          return sb.toString();
//      }

        public String cjamBase(final int m, final int b, final char c) {
            final boolean zero = a[0] == 0;
            String s = join();
            if (zero) {
                s = "1 " + s;
            }
            s = CJam.run("q~]" + m + "b" + b + "b'" + c + "f+`", s);
            s += "'" + c + "fm" + b + "b" + DIGITS[m] + "b";
            if (zero) {
                s += "1>";
            }
            return s;
        }

        public Array rle11(final int f) {
            final int[] b = new int[n];
            int m = 0;
            int x = -1;
            int k = 0;
            for (int i = 0; i <= n; ++i) {
                final int t = i == n ? -2 : a[i];
                if (t == x && m < 11 * f) {
                    m++;
                }
                else {
                    if (m >= f && m > 3) {
                        b[k++] = 10;
                        b[k++] = m / f - 1;
                        b[k++] = x;
                        for (int j = 0; j < m % f; ++j) {
                            b[k++] = x;
                        }
                    }
                    else {
                        for (int j = 0; j < m; ++j) {
                            b[k++] = x;
                        }
                    }
                    m = 1;
                    x = t;
                }
            }
            return new Array(Arrays.copyOf(b, k));
        }
    }

    private static void score() {
        double p = 1;
        for (int i = 1; i < 6; ++i) {
            final File f = new File("image" + i + ".txt");
            final Img img = Img.read(f);
            final int n = (int) f.length();
            for (int j = 5; j < 10; ++j) {
                final double q = j / 10.0;
                final String s = img.compress(q);
                System.out.println(f.getName() + ", " + q + ": " + n + " -> " + s.length());
                img.verify(s, q);
                p *= s.length();
            }
        }
        System.out.println(Math.pow(p, 1 / 25.0));
    }

    public static void main(final String... args) {
        if (args.length != 2) {
            score();
            return;
        }
        final String fname = args[0];
        final double quality = Double.parseDouble(args[1]);
        try {
            final Img img = Img.read(new File(fname));
            final String s = img.compress(quality);
            img.verify(s, quality);
            final FileWriter fw = new FileWriter(fname + ".cjam");
            fw.write(s);
            fw.close();
        }
        catch (IOException e) {
            throw new RuntimeException();
        }
    }
}
```

Requires the CJam jar in the classpath. If you give it 2 command line arguments (file name and quality), it appends ".cjam" to the file name and writes the compressed image there. Otherwise it calculates its score on the 5 test images, which are assumed to be in the current directory. The program also verifies every compressed image automatically. You may want to double-check the score calculation in case there's any discrepancy.

The techniques used (so far) are: scaling to half (horizontally, vertically or both) if it doesn't reduce the quality too much, a custom-coded RLE, and base conversion to pack more data into each character while remaining in the printable ASCII range.

Title: Lossy ASCII art compression

Body:
Java → CJam, score ≈4417.89

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.aditsu.cjam.CJam;

public class Compress {
    protected static final char[] DIGITS = "0123456789ABCDEFGHIJK".toCharArray();
    protected static final String CHARS = "@#+';:,.` ";
    protected static final char[] CHR = CHARS.toCharArray();

    private static class Img {
        public final int rows;
        public final int cols;
        public final int[][] a;

        public Img(final int rows, final int cols) {
            this.rows = rows;
            this.cols = cols;
            a = new int[rows][cols];
        }

        public Img(final List<String> l) {
            rows = l.size();
            cols = l.get(0).length();
            a = new int[rows][cols];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    a[i][j] = CHARS.indexOf(l.get(i).charAt(j));
                }
            }
        }

        public static Img read(final Reader r) {
            try {
                final BufferedReader br = new BufferedReader(r);
                final List<String> l = new ArrayList<>();
                while (true) {
                    final String s = br.readLine();
                    if (s == null || s.isEmpty()) {
                        break;
                    }
                    l.add(s);
                }
                br.close();
                return new Img(l);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public static Img read(final File f) {
            try {
                return read(new FileReader(f));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public Img scaleDown(final int fr, final int fc) {
            final int r1 = (rows + fr - 1) / fr;
            final int c1 = (cols + fc - 1) / fc;
            final Img x = new Img(r1, c1);
            final int[][] q = new int[r1][c1];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[i / fr][j / fc] += a[i][j];
                    q[i / fr][j / fc]++;
                }
            }
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] /= q[i][j];
                }
            }
            return x;
        }

        public Img scaleUp(final int fr, final int fc) {
            final int r1 = rows * fr;
            final int c1 = cols * fc;
            final Img x = new Img(r1, c1);
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] = a[i / fr][j / fc];
                }
            }
            return x;
        }

        public Img crop(final int r, final int c) {
            if (r == rows && c == cols) {
                return this;
            }
            final Img x = new Img(r, c);
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    x.a[i][j] = a[i][j];
                }
            }
            return x;
        }

        public Img rescale(final int fr, final int fc) {
            return scaleDown(fr, fc).scaleUp(fr, fc).crop(rows, cols);
        }

        public double quality(final Img x) {
            if (x.rows != rows || x.cols != cols) {
                throw new IllegalArgumentException();
            }
            double t = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    final int y = a[i][j] - x.a[i][j];
                    t += y * y;
                }
            }
            t /= 81 * rows * cols;
            t = 1 - Math.sqrt(t);
            return Math.pow(t, 8);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    sb.append(CHR[a[i][j]]);
                }
                sb.append('\n');
            }
            return sb.toString();
        }

        public Array toArray() {
            final Array x = new Array(rows * cols);
            int k = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[k++] = a[i][j];
                }
            }
            return x;
        }

        public String compress(final double quality) {
            int bi = 1;
            int bj = 1;
            int bs = rows * cols;
            Img bx = this;

            for (int i = 1; i < 3; ++i) {
                for (int j = 1; j < 3; ++j) {
                    Img x = rescale(i, j);
                    if (quality(x) >= quality) {
                        x = scaleDown(i, j);
                        if (x.rows * x.cols < bs) {
                            bi = i;
                            bj = j;
                            bs = x.rows * x.cols;
                            bx = x;
                        }
                    }
                }
            }

            Array a = bx.toArray();
            int bf = 0;
            for (int i = 1; i <= 20; ++i) {
                final int t = a.rle11(i).n;
                if (t < bs) {
                    bs = t;
                    bf = i;
                }
            }

            int b = 10;
            if (bf > 0) {
                b = 11;
                a = a.rle11(bf);
            }

            String s = null;
            for (int i = 92; i < 97; ++i) {
                for (char c = ' '; c < '$'; ++c) {
                    final String t = a.cjamBase(b, i, c);
                    boolean ok = true;
                    for (int j = 0; j < t.length(); ++j) {
                        if (t.charAt(j) > '~') {
                            ok = false;
                            break;
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    if (s == null || t.length() < s.length()) {
                        s = t;
                    }
                }
            }

            if (bf > 0) {
                s += "{(_A={;()";
                if (bf > 1) {
                    s += DIGITS[bf] + "*";
                }
                s += "\\(a@*}&\\}h]e_";
            }
            if (bi * bj == 1) {
                return s + '"' + CHARS + "\"f=" + cols + "/N*";
            }
            s += bx.cols + "/";
            if (bi > 1) {
                s += bi + "e*";
                if (rows % 2 == 1) {
                    s += "W<";
                }
            }
            if (bj > 1) {
                s += bj + "fe*";
                if (cols % 2 == 1) {
                    s += "Wf<";
                }
            }
            return s + '"' + CHARS + "\"ff=N*";
        }

        public void verify(final String s, final double quality) {
            final String t = CJam.run(s, "");
            final Img x = read(new StringReader(t));
            final double q = quality(x);
            if (q < quality) {
                throw new RuntimeException(q + " < " + quality);
            }
//          System.out.println(q + " >= " + quality);
        }
    }

    private static class Array {
        public final int[] a;
        public final int n;

        public Array(final int n) {
            this.n = n;
            a = new int[n];
        }

        public Array(final int[] a) {
            this.a = a;
            n = a.length;
        }

        public String join() {
            final StringBuilder sb = new StringBuilder();
            for (int x : a) {
                sb.append(x).append(' ');
            }
            sb.setLength(sb.length() - 1);
            return sb.toString();
        }

//      public String cjamStr() {
//          final StringBuilder sb = new StringBuilder("\"");
//          for (int x : a) {
//              sb.append(DIGITS[x]);
//          }
//          sb.append("\":~");
//          return sb.toString();
//      }

        public String cjamBase(final int m, final int b, final char c) {
            final boolean zero = a[0] == 0;
            String s = join();
            if (zero) {
                s = "1 " + s;
            }
            s = CJam.run("q~]" + m + "b" + b + "b'" + c + "f+`", s);
            s += "'" + c + "fm" + b + "b" + DIGITS[m] + "b";
            if (zero) {
                s += "1>";
            }
            return s;
        }

        public Array rle11(final int f) {
            final int[] b = new int[n];
            int m = 0;
            int x = -1;
            int k = 0;
            for (int i = 0; i <= n; ++i) {
                final int t = i == n ? -2 : a[i];
                if (t == x && m < 11 * f) {
                    m++;
                }
                else {
                    if (m >= f && m > 3) {
                        b[k++] = 10;
                        b[k++] = m / f - 1;
                        b[k++] = x;
                        for (int j = 0; j < m % f; ++j) {
                            b[k++] = x;
                        }
                    }
                    else {
                        for (int j = 0; j < m; ++j) {
                            b[k++] = x;
                        }
                    }
                    m = 1;
                    x = t;
                }
            }
            return new Array(Arrays.copyOf(b, k));
        }
    }

    private static void score() {
        double p = 1;
        for (int i = 1; i < 6; ++i) {
            final File f = new File("image" + i + ".txt");
            final Img img = Img.read(f);
            final int n = (int) f.length();
            for (int j = 5; j < 10; ++j) {
                final double q = j / 10.0;
                final String s = img.compress(q);
                System.out.println(f.getName() + ", " + q + ": " + n + " -> " + s.length());
                img.verify(s, q);
                p *= s.length();
            }
        }
        System.out.println(Math.pow(p, 1 / 25.0));
    }

    public static void main(final String... args) {
        if (args.length != 2) {
            score();
            return;
        }
        final String fname = args[0];
        final double quality = Double.parseDouble(args[1]);
        try {
            final Img img = Img.read(new File(fname));
            final String s = img.compress(quality);
            img.verify(s, quality);
            final FileWriter fw = new FileWriter(fname + ".cjam");
            fw.write(s);
            fw.close();
        }
        catch (IOException e) {
            throw new RuntimeException();
        }
    }
}

Requires the CJam jar in the classpath. If you give it 2 command line arguments (file name and quality), it appends ".cjam" to the file name and writes the compressed image there. Otherwise it calculates its score on the 5 test images, which are assumed to be in the current directory. The program also verifies every compressed image automatically. You may want to double-check the score calculation in case there's any discrepancy.

The techniques used (so far) are: scaling to half (horizontally, vertically or both) if it doesn't reduce the quality too much, a custom-coded RLE, and base conversion to pack more data into each character while remaining in the printable ASCII range.


答:
MATLAB / Octave, 42 bytes

```<code>@(x)upper(datestr(datenum(x,'yyyymm'),12))
</code>```

Creates an anonymous function named ans that is called with a string representing the date: ans('201604').

Online Demo

This solution uses datenum to convert the input date to a serial date number, and then datestr with the predefined output spec of mmmyy (12) to yield the string representation in the required format. Finally, we use upper to change it to MMMYY since the uppercase month is not an output option.

Title: Convert YYYYMM to MMMYY

Body:
Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.

Last two digits will be between 01 and 12.

Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

```<code>MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC
</code>```

Examples:

```<code>Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
</code>```

Body:
MATLAB / Octave, 42 bytes

@(x)upper(datestr(datenum(x,'yyyymm'),12))

Creates an anonymous function named ans that is called with a string representing the date: ans('201604').

Online Demo

This solution uses datenum to convert the input date to a serial date number, and then datestr with the predefined output spec of mmmyy (12) to yield the string representation in the required format. Finally, we use upper to change it to MMMYY since the uppercase month is not an output option.


答:
MATL, <s>18</s> <s>14</s> 13 bytes

```<code>4e!Z{Zc12XOXk
</code>```

Input is provided as a string (enclosed in single quotes).

This version only runs in MATL on MATLAB since MATLAB is able to automatically parse datestr('2016 04').

Explanation

```<code>        % Implicitly grab input as a string
4e!     % Reshape input to be 2 x 4 (puts the year in row 1 and month in row 2)
Z{      % Place each row in a separate cell
Zc      % Join them together using a space to create 'yyyy mm' format
12      % Number literal, pre-defined datestring of 'mmmyy'
XO      % Convert from serial date number to string using this format
Xk      % Convert to uppercase
        % Implicitly display

</code>```

Here is an 18 byte version which works on Octave (and therefore the online interpreter)

```<code>'yyyymm'2$YO12XOXk
</code>```

Try it Online

Modified version for all test cases

Explanation

```<code>            % Implicitly grab input as a string
'yyyymm'    % Push the format string as a string literal
2$YO        % Convert to a serial date number
12          % Number literal, pre-defined datestring of 'mmmyy'
XO          % Convert from serial date number to string using this format
Xk          % Convert to uppercase
            % Implicitly display
</code>```

Title: Convert YYYYMM to MMMYY

Body:
MATL, <s>18</s> <s>14</s> 13 bytes

4e!Z{Zc12XOXk

Input is provided as a string (enclosed in single quotes).

This version only runs in MATL on MATLAB since MATLAB is able to automatically parse datestr('2016 04').

Explanation

        % Implicitly grab input as a string
4e!     % Reshape input to be 2 x 4 (puts the year in row 1 and month in row 2)
Z{      % Place each row in a separate cell
Zc      % Join them together using a space to create 'yyyy mm' format
12      % Number literal, pre-defined datestring of 'mmmyy'
XO      % Convert from serial date number to string using this format
Xk      % Convert to uppercase
        % Implicitly display

Here is an 18 byte version which works on Octave (and therefore the online interpreter)

'yyyymm'2$YO12XOXk

Try it Online

Modified version for all test cases

Explanation

            % Implicitly grab input as a string
'yyyymm'    % Push the format string as a string literal
2$YO        % Convert to a serial date number
12          % Number literal, pre-defined datestring of 'mmmyy'
XO          % Convert from serial date number to string using this format
Xk          % Convert to uppercase
            % Implicitly display


答:
Japt, <s>35</s> 34 bytes

```<code>ÐUr$/..../$,"$&-")+P s4,7 u +Us2,4
</code>```

Link.

Uses the same technique as my JavaScript answer.

Title: Convert YYYYMM to MMMYY

Body:
Japt, <s>35</s> 34 bytes

ÐUr$/..../$,"$&-")+P s4,7 u +Us2,4

Link.

Uses the same technique as my JavaScript answer.


答:
Bash, <s>39</s> 28 bytes

```<code>date -d$101 +%b%y|tr a-z A-Z
</code>```

Thanks Digital Trauma!

Title: Convert YYYYMM to MMMYY

Body:
Bash, <s>39</s> 28 bytes

date -d$101 +%b%y|tr a-z A-Z

Thanks Digital Trauma!


问:
calculate days of a month
I would like to see the shortest expression to calculate the days (or the last day)  of a month in any language.

Considering y as the number of year and m as month.

Basic rules

without date / time functions.

considering leap years.

there is not other rule.

答:
VB.net (89 81c)

shame about the date function restriction as VB.net at only (21c)

```<code>Date.DaysInMonth(y,m)
</code>```

may have won one for a change. DAMN YOU!

So current best is 89c

    {0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 AndAlso (y Mod 4)=0 AndAlso (y Mod 400)>0,1,0)

```<code>{0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 And (y Mod 4)=0 And (y Mod 400)>0,1,0)
</code>```

Title: calculate days of a month

Body:
VB.net (89 81c)

shame about the date function restriction as VB.net at only (21c)

Date.DaysInMonth(y,m)

may have won one for a change. DAMN YOU!

So current best is 89c

    {0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 AndAlso (y Mod 4)=0 AndAlso (y Mod 400)>0,1,0)

{0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 And (y Mod 4)=0 And (y Mod 400)>0,1,0)


答:
Fith, 52 bytes

```<code>{ 1 + range dup sum 2 pow swap { 2 pow } map sum - }
</code>```

This is an anonymous function that takes the two numbers on the stack and leaves a single number.

Explanation:

```<code>{
    1 + range dup      2 ranges from a to b inclusive
    sum 2 pow          Sum one and square it
    swap               Bring a fresh range to the top
    { 2 pow } map sum  Square every element and sum the list
    -                  Subtract
}
</code>```

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:
Fith, 52 bytes

{ 1 + range dup sum 2 pow swap { 2 pow } map sum - }

This is an anonymous function that takes the two numbers on the stack and leaves a single number.

Explanation:

{
    1 + range dup      2 ranges from a to b inclusive
    sum 2 pow          Sum one and square it
    swap               Bring a fresh range to the top
    { 2 pow } map sum  Square every element and sum the list
    -                  Subtract
}


答:
Bash + coreutils, 18

Requires 64-bit version of date for the given testcases, which recognises dates earlier than 14th December 1901.

```<code>date -d$101 +%^b%y
</code>```

Title: Convert YYYYMM to MMMYY

Body:
Bash + coreutils, 18

Requires 64-bit version of date for the given testcases, which recognises dates earlier than 14th December 1901.

date -d$101 +%^b%y