title: Split me in half

text:
# Question
Title: Split me in half
You will be given a number `x`, where `0 <= x <= 2^32 - 1`.

You should output a list of numbers in decimal, after recursive splitting in binary format.

### Examples:

**Example 1:**

```
255 -> 255 15 15 3 3 3 3 1 1 1 1 1 1 1 1

```

The current list is just `255`.

The binary representation of `255` is `1111 1111`. Splitting it, we get `1111` and `1111`, which in decimal are `15` and `15`.

We add those to the list, so we will have `255 15 15`.

Now the numbers `15` and `15` will serve as inputs and these numbers are to be split.

Doing it again, we get (`3 3` from both `15`s): `255 15 15 3 3 3 3`.

Continuing the logic, final list will be `255 15 15 3 3 3 3 1 1 1 1 1 1 1 1` . And since `1` can no longer be split, the output stops.

**Example 2:**

```
225 -> 225 14 1 3 2 1 1 1 0

```

The starting list is `225`.

The binary representation of `225` is `1110 0001`. Splitting it, we get `1110` and `0001`, which in decimal are `14` and `1`.

Adding those to the list, we get `225 14 1`.

Now the numbers `14` and `1` will serve as inputs and these numbers are to be split.

Since `1` is no splittable, the output will be `225 14 1 3 2`.

**Example 3:**

```
32 -> 32 4 0 1 0

```

**Conditions**:

1. If the number of binary digits are odd, the first number will have one fewer binary digit than the next one. Example, `20 (10100)` will be split as `10` and `100`, with decimal output being `2` and `4`.
2. Standard loophole rules apply.
3. `0`s and `1`s do not propagate further.
4. Program crashing for trying to display too many numbers is a valid exit condition.

# Answer
> 14 votes
# Pyth, 18 bytes

```
u+QiR2smc2+0dt#.BM

```

Test suite

This code does something very tricky and clever with `u`, Pyth's fixed point operator.

The body of the function, which is everything other than the `u`, is fairly straightforward:

```
+QiR2smc2+0dt#.BM
+QiR2smc2+0dt#.BMG    Implicit variable
                      G will store the list of numbers from the previous iteration.
              .BMG    Map each number to its binary representation
            t#        Filter out the ones of length 1 (0 and 1)
      m               Map the remaining binary
         +0d          Prefix with a 0
       c2             Chop in half.
                      Since c puts the larger half first, prefixing with a 0
                      makes the chop work out right, and doesn't change the value.
     s                Concatenate
  iR2                 Map back to binary
+Q                    Add the input to the front of the list

```

This code removes 0s and 1s, splits every number, and adds the input in front.

`u` will run this function on the prior result of the function until the result stops changing.

What initial value does `u` use? That's the clever part: the code doesn't specify what value to use, so it defaults to the input. But the input isn't a list of numbers - it's a number. Pyth implicitly coerces the number on the fist time through the loop to the range of the number - `[0, 1, ..., Q-1]`. That doesn't look anything like the output we want to get. Fortunately, `u` will find the correct result regardless of what the initial input is - the desired output is the only fixed point of the function, and repeated application will always reach it.

Let's look at the intermediate values of the program with the input `7`. I've highlighted the prefix of the result which is guaranteed to be correct, regardless of initial input:

1. `7` (Implicitly `[0, 1, 2, 3, 4, 5, 6]`)
2. **`[7,`**`1, 0, 1, 1, 1, 0, 1, 1, 1, 2]`
3. **`[7, 1, 3,`**`1, 0]`
4. **`[7, 1, 3, 1, 1]`**

Which is the output.

---

# Packed Pyth, 16 bytes

Note that since Pyth uses only the 0-127 range of ASCII, it can be compressed by using a 7-bit encoding rather than an 8 bit encoding. Thus, the above program can be packed into 16 bytes. The resulting program is:

```
ꮎ�L����[
    ���4

```

hexdump:

```
0000000: eaae 8e9a 4cb9 edc6 c95b 0c9d 11ae 8534  ....L....[.....4

```

The interpreter is found here. Provide the input as a command line argument.

The code page of this language (Packed Pyth) is the 0-127 range of ASCII, and every character is represented with 7 bits, padded at the end. Thus, the above unreadable hexdump represents:

```
u+QiR2smc2+0dt#.BM

```

But in 16 bytes.

# Answer
> 6 votes
# 05AB1E, ~~21~~ ~~20~~ ~~18~~ 17 bytes

```
,¸[Žrbvy0ì2äCʒ=1›

```

Try it online!

## Explanation

```
,¸[Žrbvy0ì2äCʒ=1›   Argument n
,¸                  Print n and push n as array
  [Ž                Loop until stack is empty
    r               Reverse stack
     b              Convert elements in array to binary
      v             For each y in array
       y0ì2ä        Prepend '0' to y and split it into 2 elements
                    (the first element will take the additional character)
            C       Convert elements to decimal
             ʒ=1›   Keep only elements greater than 1, while printing each element

```

# Answer
> 5 votes
# Jelly, ~~21~~ 20 bytes

-1 byte by removing a monadic chain and then dealing with the consequence of an empty list being converted from binary yielding 0 later.

```
ỊÐḟBUœs€2UḄF
WÇÐĿṖUF

```

A monadic link taking a number and returning the list specified.

**Try it online!**

### How?

```
ỊÐḟBUœs€2UḄF - Link 1, perform an iteration: list of numbers
 Ðḟ          - filter out if:
Ị            -   insignificant (absolute value <= 1 - hence any 0s or 1s)
   B         - convert to a binary list (vectorises)
    U        - upend (reverse each)
     œs€2    - split €ach into 2 equal chunks (the first half is longer if odd ...hence
         U   - upend (reverse each)         ...this upend and the previous one)
          Ḅ  - convert from binary list to number (vectorises, although when the filter
             -                                     removes everything a zero is yielded)
           F - flatten the resulting list of lists to a single list

WÇÐĿṖUF - Main link: number
W       - wrap in a list
  ÐĿ    - loop and collect results until no change occurs:
 Ç      -   call last link (1) as a monad
    Ṗ   - pop (remove the last element - a list containing a single zero which results
        -     from the effect of Ḅ when link 1's input only contained ones and zeros)
     U  - upend (put the iterations into the required order)
      F - flatten to yield a single list

```

# Answer
> 4 votes
## JavaScript (ES6), 99 bytes

This looks a bit too long. There might be a better way to get the correct order.

```
f=(n,p=(a=[],1),i=33-Math.clz32(n)>>1)=>(a[p]=n)>1?f(n>>i,p*=2)&&f(n&(1<<i)-1,p+1):a.filter(n=>1/n)

```

### Demo

```
f=(n,p=(a=[],1),i=33-Math.clz32(n)>>1)=>(a[p]=n)>1?f(n>>i,p*=2)&&f(n&(1<<i)-1,p+1):a.filter(n=>1/n)

console.log(JSON.stringify(f(255)))
console.log(JSON.stringify(f(225)))
console.log(JSON.stringify(f(32)))
```

# Answer
> 2 votes
# Java 10, ~~541~~ ~~521~~ ~~245~~ 243 bytes

```
n->{var L=new java.util.Stack<Integer>();L.add(n);for(int i=9,o=0,t;o<i;)for(i=o;i<L.size();o++)if((t=L.get(i++))>1){var b=n.toString(t,2);L.add(n.parseInt(0+b.substring(0,t=b.length()/2),2));L.add(n.parseInt(b.substring(t),2));o++;}return L;}

```

Try it online.

-22 bytes thanks to *@ceilingcat*.

**Explanation:**

```
n->{                      // Method with Integer parameter & Integer-List return-type
  var L=new java.util.Stack<Integer>();
                          //  Create the result-List
  L.add(n);               //  Add the input-Integer to it
  for(int i=9,            //  Index integer `i`, set to a non-0 digit
      o=0,                //  Off-set integer `o`, starting at 0
      t;                  //  Temp integer `t`, uninitialized
      o<i;)               //  Loop as long as `o` isn't `i` yet:
    for(i=o;i<L.size()    //   Inner loop `i` in the range [`o`,list-size):
        ;o++)             //     After every iteration: Increase `o` by 1
      if((t=L.get(i++))   //    Set `t` to the `i`'th item
                          //    (and increase `i` by 1 afterwards with `i++`)
         >1){             //    If `t` is larger than 1 (thus can be further split):
        var b=n.toString(t,2);
                          //     Convert `t` to a binary-String
        L.add(            //     Add to the List:
          n.parseInt(     //      A String converted to Integer:
            0             //       A "0",
            +b.substring( //       Appended with a substring of `b`
               0,t=b.length()/2)
                          //       in the char-range [0,length/2)
          ,2));           //      Converted as a base-2 String to base-10 Integer
        L.add(            //     Also add to the List:
          n.parseInt(     //      A String converted to Integer:
            b.substring(  //       A substring of `b`
              t)          //       in the char-range [length/2,length)
          ,2));           //      Also converted from a base-2 String to base-10 Integer
        o++;}             //     And increase `o` by 1
  return L;}              //  Return the result-List

```

# Answer
> 2 votes
# Python 2, 110 bytes

```
l=[input()];i=1
while i:
 z=0
 for k in l[-i:]:
	if k>1:b=~-len(bin(k))/2;l+=[k>>b,k&2**b-1];z+=2
 i=z
print l

```

Try it online!

# Answer
> 2 votes
# Retina, 142 bytes

```
.+
$*
+`(1+)\1
${1}0
01
1
{`.+$
$&¶<$&>
+`;(\d*)>
>;<$1>
<.>

{`(\d)>
>$1
}`<(\d)
$1<
<>
;
\b0+\B

}`^;|;\B

¶
;
;;

1
01
+`10
011
0\B

1+
$.&

```

Try it online!

# Answer
> 2 votes
# PHP, 132 Bytes

```
for($r=[$argn];""<$n=$r[+$i++];)$n<2?:[$r[]=bindec(substr($d=decbin($n),0,$p=strlen($d)/2)),$r[]=bindec(substr($d,$p))];print_r($r);

```

Try it online!

# Answer
> 2 votes
# Ruby, 102 bytes

```
f=->*a{a==[]?[]:a+=f[*a.map{|i|s='%b'%i;i>1?[s[0...h=s.size/2].to_i(2),s[h..-1].to_i(2)]:[]}.flatten]}

```

Try it online!

# Answer
> 2 votes
# Ruby, 98 bytes

```
f=->*a{a==[]?a:a+=f[*a.flat_map{|i|s='%b'%i;i>1?[s[0...h=s.size/2].to_i(2),s[h..-1].to_i(2)]:[]}]}

```

Try it online!

Simply a basic optimization of Value Ink's answer : use flat\_map instead of map...flatten, and use

`a==[]?a` instead of `a==[]?[]`

# Answer
> 0 votes
# MathGolf, 18 bytes

```
{gÉo1>môàh½‼<≥å}∟;

```

Takes the input wrapped inside a list. If this is not allowed, a leading `a` can be added.
Print each of the resulting items on a separated line to STDOUT.

Try it online.

**Explanation:**

```
{              }∟  # Do-while true without popping:
 g                 #  Filter the current list of integers by
                   #  (or the implicit input-list in the first iteration),
  É                #  using the following 3 characters as inner code-block:
   o               #   Print the integer with trailing newline (without popping)
    1>             #   Check that it's larger than 1 (thus can be further split)
      m            #  Map over the remaining integers,
       ô           #  using the following 6 characters as inner code-block:
        à          #   Convert the integer to a binary-string
                   #   Split it into the correct halves by:
         h         #    Pushing its length (without popping)
          ½        #    Integer-dividing this length by 2
           ‼       #    And apply the following commands separated on the stack:
            <      #     Slice to get the first length//2 bits
             ≥     #     Slice to get the remaining bits
              å    #  After the map: convert all binary-parts back to integers
                 ; # After the do-while: remove the empty list from the stack
                   # (the empty stack is then output implicitly with newline)

```

---
Tags: code-golf, number, base-conversion, binary
---


# Question
Title: Encode a program with the fewest distinct characters possible
The goal is to write a program that encodes an other program (input) with the fewest character possible.

### Scoring

* The score is equal to the different number of characters needed for the output.
* Lower score is better.

### Rules

* No target languages with a limited set of commands. (No Brainf\**k, Whitespace etc)
**Edit**: I mean at least 26 significant characters, `A` doesn't change the way a brainf\**k program operates, so you can't count this character. Same applies to whitespace.
* The target language must exist at the time where this question is written.
* You have to include a small explanation how you achieve your score.
* The input program is valid.
* The encoded program must be a valid program in the same language as the input.
* The encoded program must do the same job as the original program.
* Your encoder must work for every valid program in that language.
* Include some sample input and output.

### Notes

* The encoder might be written in any language, not only in the language it targets.
* This is not , readable programs are encouraged.
* The great goal is to see how many different characters are needed to write anything in that language. I disallowed BF etc because there would be no challenge.
* This was inspired by Print a string in as few distinct characters as possible, you could take it as for that question.

### Example

In Java, you can use `\uXXXX` instead other characters. A valid entry encodes every character from the input this way. This would have a score of 18. (`\ 0-9a-f`)

Code in Tcl, encodes a Java program:

```
set res {}
foreach char [split [read stdin] {}] {
    append res [format \\u%04x [scan $char %c]]
}
puts $res

```

# Answer
### GolfScript / GolfScript, score 4

```
"'',,"\{"'"\","*"',+"}%"''+~"

```

The encoder itself is a GolfScript program which takes the original code on STDIN and transforms it into a sequence of characters `',+~`. This output itself is valid GolfScript code which performs the same operations as the original version.

The basic method consists of an encoding of the code as a string (using chars `',+`, see below) and then evaluate this string using the eval command `~`.

If one concatenates any string together with an array of numbers in GolfScript the numbers are converted to code points and the result is a string itself. Thus the string encoding simply builds a list of numbers (from the code points of the input code) and then concatenates all those with an empty string.

*Example:*

The input code

```
"hi"
p

```

is translated into (note: line breaks and comments added for readability)

```
# initialize an empty array []
'',,

# append number 34 (length of string ',,, ... ,,,')
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+

# ... other numbers
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+
',,,,,,,,,,',+
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,',+

# result is array [34 104 105 34 10 112]

# append empt string, i.e. convert array to string (results in "\"hi\"\np")
''+

# evaluate
~

```
> 10 votes

# Answer
# Python -\> Python, 8 distinct characters

```
def minimal_python(input_code):
    """Convert Python code to minimal Python code."""

    # Create a list of the ordinal numbers of <input_code>'s characters.
    # '%' signs have to be treated specially and are represented with -1.
    ords = []
    num_escaped_chars = 0
    for char in input_code:
        if char == '%':
            ords.append(-1)
        else:
            ords.append(ord(char))
            num_escaped_chars += 1

    modulo_sign_escape = '%' * 2**num_escaped_chars
    def formatters():
        num_escaped_chars_so_far = 0
        for o in ords:
            if o == -1:
                yield modulo_sign_escape
            else:
                yield '%' * 2**num_escaped_chars_so_far + 'c'
                num_escaped_chars_so_far += 1
    format_str = "'" + ''.join(formatters()) + "'"

    values_str = ''.join('%' + '-~'*o + '0' for o in ords if o != -1)

    return 'exec' + format_str + values_str

```

This uses modulo formatting to rebuild the input string. For example, `print 1` results in this program:

```
exec'%c%%c%%%%c%%%%%%%%c%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c'%-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0

```

In theory you can encode any program like this, but the resulting program will always have more than 2n characters, where n is the number of characters in the input, not including `%` symbols.
> 11 votes

# Answer
# CJam -\> CJam, score: 3

CJam is newer than the question so it's not eligible to win.

```
q{[{_'(>{'(-')*''\+}{is'c+T}?}%{"+"T}*'~]}:T~

```

It uses `')~`. `')` is the character `)`, and each extra `)` increments it by one. `~` can evaluate a character or a string. The complete program is evaluated after concatenating all the characters by evaluating `+`. And an integer of the character value and a number-to-character operation is evaluated for each character less than `)`.

### Examples

```
XX{_2$+}I*]N*

```

is translated into:

```
'))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))')))~')))))))))))'))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))')))~'))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))')))~'))')))~~

```

and

```
q{[{_'(>{'(-')*''\+}{is'c+T}?}%{"+"T}*'~]}:T~

```

is translated into:

```
')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))'))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))'))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')')))~'))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))')))~'))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))')))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))'))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~')))')))~')))))))))))'))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))')))~')))))))))))')))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))')))~')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))))))))')))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))~~

```
> 8 votes

# Answer
## APL (score: 10)

```
'⍎⎕AV[',(⊃,/{'(⍴',(⍵/'⍬'),')'}¨⎕AV⍳⍞),']'

```

Characters used in encoding: `⍎⎕AV[(⍴⍬)]`

The APL program to encode must restrict itself to the APL charset and not use any extra Unicode.

Encoding for the program `42` (which outputs the answer to Life, the Universe, and Everything):

```
⍎⎕AV[(⍴⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬)(⍴⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬⍬)]

```

How it works:  is the empty list, `⍬⍬⍬⍬` is therefore a list of four empty lists, `⍴⍬⍬⍬⍬` is the length of the list of four empty lists, which is four. Dyadic  is reshape, so the length-of-list-of-lists instructions must be wrapped in parenthesis, giving the final encoding of character number four as `(⍴⍬⍬⍬⍬)`.

These numbers are then looked up in `⎕AV` which is the character set, and  executes the resulting string.

(At first sight it looks like the score could be brought to 9 by using `⎕UCS` instead of `⎕AV` and saving `[]`, but that doesn't work, because `(⍴⍬)(⍴⍬)` is a list of lists of scalars, i.e `[[1], [1]]` instead of the `[1, 1]` that would be required, and working around that would require interspersing the encoded values with commas, bringing the score back up to 10.)
> 4 votes

# Answer
# Lenguage, score 1

The program consists of \\$1{,}517{,}807\\$ of any characters. These can be any characters you want, as Lenguage only depends on the length of a program. This does not break rule 1 as all characters are significant in Lenguage because of this fact.

This is one of the extremely few useful Lenguage programs that fits into the observable universe. Here is one of the \\$1{,}114{,}112^{1{,}517{,}807}\\$ possible Lenguage self-encoders.

# Explanation

Lenguage starts by calculating the program's length and converting it to binary. `1517807` in binary is `101110010100011101111`. Next, it left-pads that number with zeros until the length of that number is a multiple of three. The length of `101110010100011101111` is 21, which is already a multiple of three, so we don't need to worry about this. After that, it splits it into chunks of three. This becomes `101 110 010 100 011 101 111`. Finally, it is translated to BF using this simple table:

| BF | Translated Lenguage |
| --- | --- |
| `+` | `000` |
| `-` | `001` |
| `>` | `010` |
| `<` | `011` |
| `.` | `100` |
| `,` | `101` |
| `[` | `110` |
| `]` | `111` |

And then evaluated as BF code. Here, `101 110 010 100 011 101 111` becomes `,[>.<,]`. Here's what it does:

```
,[>.<,]  # full program
,        # input* to current cell
 [    ]  # while current cell is nonzero...
  >      # move pointer right
   .     # output current cell as a char
    <    # move pointer left
     ,   # input to current cell

```

This outputs a null byte for every character inputted. This doesn't change the execution of the inputted program since, as I said, the program is only dependant on the length of the program. Why a null byte, you ask? Because the tape initially starts out filled with zeros, and it's easier to just output the null byte that can already be output from the second cell than to set the second cell to some other value and output that every time. If you don't understand, here's an example:

Say the input is \\$23{,}855\\$ `$`s. This is one of the many variations of a cat program in Lenguage. It decodes to `,[.,]`, which is the standard BF cat. Here's the tape through each command:

| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `^` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| `,` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |

| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|  | `^` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| `[>` | `.` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |

| `36` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` | `0` |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `^` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| `<,]` |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |

etc.

As you can see, each `.` command ends up on a `0`, outputting a null byte for each character inputted.

\*This program assumes that EOF is a null byte.
> 3 votes

# Answer
# RProgN, 7 Distinct Characters, Noncompeting

RProgN is newer than this question.

`' do.Lc`

Convert the program to `'oooo...' L c 'ooooo...' L c 'oo...' L c . . . do`, where each 'oo...' represents the character code in o's, surrounded by apostrifies to make a string out of them. L c then turns them into a number constant. After all the strings are placed on the stack, a chain of .'s equal to the amount of characters in the encoded string minus one rebuild the encoded string, and do executes it.

## Encoder, also written in RProgN.

```
'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' L c 'ooooooooooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooo' L c 'oooooooooooooooooooooooooooooooooooooooooooooo' L c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . do

```

Try it online!
> 2 votes

# Answer
# Ruby -\> Ruby, 8

```
#Convert a number from 0 to 255 to the form "111+11+11+1+1+1"
def byte_to_ones(byte)
  output = []
  ones = [111,11,1]
  ones.each do |one|
    while byte>=one
      byte-=one
      output<<one
    end
  end
  output.join('+')
end

bytes = $<.each_byte.map { |byte| byte_to_ones(byte) }

puts "eval''<<#{bytes.join('<<')}"

```

Sample:

```
puts "Hello, world!" => eval''<<111+1<<111+1+1+1+1+1+1<<111+1+1+1+1+1<<111+1+1+1+1<<11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+1<<11+11+11+11+11+11+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<111<<11+11+11+11<<11+11+1+1+1+1+1+1+1+1+1+1<<111+1+1+1+1+1+1+1+1<<111<<111+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1<<11+11+11<<11+11+11+1<<1+1+1+1+1+1+1+1+1+1

```

Implements the Ruby solution given in the linked problem and replaces I/O with eval.
> 1 votes

# Answer
# 05AB1E, ~~8~~ 4 distinct bytes

```
[„)\ìNú₅ö©g₅Qi®ƒ„.g}¤…B.VJ?q

```

No TIO of the actual program, since the output would be way too big. It basically encodes the input-program into a program using the approach I've also used in the *Fewest (distinct) characters for Turing Completeness* challenge.

Try it online (with `ƒ„.g}¤…B.V` replaced with `"D>gB.V"` so we push the number instead of that many `.g` or try it online (with `®` replaced with `9` as an example).

**Explanation:**

```
[                            # Start an infinite loop:
 „)\ì                        #  Prepend ")\" in front of the (implicit) input
     Nú                      #  Pad it with the loop-index amount of leading spaces
       ₅ö                    #  Convert it from a base-255 string to a number
         ©                   #  Store this number in variable `®` (without popping)
          g₅Qi               #  If the length of this number is 255:
              ®ƒ„.g}         #   Push `®` + 1 amount of ".g" to the stack
                    ¤        #   Tail (without popping): pushes "g"
                     …B.V    #   Push "B.V"
                         J   #   Join the stack together
                          ?  #   Output it without trailing newline
                           q #   And stop the program

```

This will produce a program with the 4 distinct bytes `.gBV` in the following format:

Loads and loads of `.g` to push a huge number. Then one additional `.g`+`g` to push 255, followed by `B.V`.

* Loads of `.g`: Push the amount of items on the stack, which will become one larger every time, where only the last two are relevant
* `g`: Pop the top number, and push its length (which will always be 255)
* `B`: Convert the large number to base-255, resulting in the original input-program with prepended `)\`, to clean the stack from all the numbers we've pushed with `.g` (`)` wraps the entire stack into a list and `\` discards it)
* `.V`: Execute it as 05AB1E code

Try such a program for (with the many `.g` replaced with a huge number plus additional `D>`).  will push the lowercase alphabet & palindromizes it.
> 1 votes

# Answer
# Knight, score ~~5~~ 4

```
AE+1
```

Using the `ASCII` function, we can assemble arbitrary strings using `+A(whitespace)1`. However, since we know that all Knight programs will always be printable ASCII, tab, CR, or LF, we can always assume codepoints will be \>= 9.

Therefore, to avoid whitespace, we can use EVAL.

`+` can be used to both concatenate strings and do addition, `A` converts an integer to a string with its ASCII value, and `1` is used to add a bunch of 1's together to get any non-zero integer (strings with null bytes are illegal in Knight).

For example, if we wanted a string with a tab (ASCII 9) followed by a newline (ASCII 10) we would do this:

```
+A++++++++E1E1E1E1E1E1E1E1E1A+++++++++E1E1E1E1E1E1E1E1E1E1

```

Now, we can simply encode a Knight program using this method and evaluate it with `E`.

Here is the conversion program in Knight. It adds a leading newline and leaves out the trailing newline, but otherwise encodes a functionally equivalent program.

This could be further optimized if we used `111` and `11`, but this isn't despite the question being tagged it...

```
# start with empty string
; = acc ""
# slurp the entirety of stdin and concatenate with newlines
; WHILE(= tmp PROMPT)
    : = acc + + acc ASCII(10) tmp
# First output the E to evaluate the next expression
# note: #"# is just to fix syntax highlighting
; OUTPUT("E\") #"#
# Now output length - 1 `+`'s to build the string one ASCII at a time
; OUTPUT(+ * "+" (- LENGTH(acc) 1) "\") #"#
# Now loop through the string
: WHILE(acc)
    # Grab the ASCII value of the first character in acc
    ; = char ASCII(acc)
    # snip off the first character of acc
    ; = acc SUBSTITUTE(acc 0 1 "")
    # output the ASCII keyword
    ; OUTPUT("A\") #"#
    # output n - 1 pluses
    ; OUTPUT(+* "+" (- char 1) "\") #"#
    # output n ones
    : OUTPUT(+*"E1" char "\") #"#

```
> 1 votes

# Answer
# Julia 0.7, score 12

```
function f(a)
    u = unique("eval(parse(-*))")
    d = Dict{Union{Char,Int},String}(u .=> repr.(u))

    while a ⊈ keys(d)
        d2 = empty(d)
        for (k1,v1) in d
            for (k2,v2) in d
                try
                    d2[k1-k2] = "($v1-$v2)"
                catch
                end
            end
        end
        merge!((x,y)->x,d,d2)
    end

    if length(a) == 1
        return "eval(parse(*($(d[a[1]]))))"
    elseif length(a) > 1
        return "eval(parse(" * join(getindex.([d],[a...]),'*') * "))"
    else
        return ""
    end
end

print(f(read(stdin,String)))

```

Try it online!

* the 12 used characters are `eval(prs-*')`
* `parse("string")` parses a string into an expression (AST)
* `eval` evaluates an expression
* we use character arithmetic to compute any character (`'b'-'a'==1`, `'b'-1=='a'`)
* characters are combined into a string with multiplication (`'a'*'b'=="ab"`)
* `d` stores every character and number for which we have found a representation with the allowed characters
* every combination of `d[k1]-d[k2]` is computed and added to `d` until all the characters of the input are found
* in Julia 1.x, `parse` is replaced with `Meta.parse`, which would add 3 to the score
* there is a warning in stderr due to the usage of `parse` instead of `Meta.parse`, which can be disabled with `--depwarn=no` if it is a problem for this challenge
> 1 votes

---
Tags: code-golf, code-generation, metagolf
---


title: Cartesian literal notation

text:
# Question
Title: Cartesian literal notation
## Introduction

> In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values, some also have notations for elements of enumerated types and compound values. Wikipedia

For example `1` usually represent an integer value, `"Hello"` a string, `[9,5,11]` an array and `1..9` a range.

The range notation is special because we have just two values in the literal but the actual value includes all elements in between.
We can say that a range expands to an array or a list of values. So the expansion of the range `1..9` is `[1,2,3,4,5,6,7,8,9]`.

In this challenge you are given a **Cartesian literal** as input and you have to output its expansion.

## Notation format rules

* consider only non negative integers values.
* this notation could work for products of any degree but in this challenge you have to handle only products of two sets, so we get a list of pairs.
* we can have one or more groups of products. Every group is terminated by the `/` symbol and generates its own list which is then concatenated to the others groups.
* each group has 2 sets: A and B and they are separated by the `:` symbol.
* each set is composed of ranges and/or atomic values separated by `,`.
Ranges are in the form `start-end` for example `0-10`.

Values must be sorted without overlaps, for example `1-5,5,4` can not appear.
* every group contains non empty sets.

## Example

The literal `1-2,5:10-12/0:1-3/` is composed of two groups.

The first group (`1-2,5:10-12`) has the sets:

```
A=[1,2,5]
B=[10,11,12]

```

and generates the product

```
[1,10],[1,11],[1,12],[2,10],[2,11],[2,12],[5,10],[5,11],[5,12]

```

the second group generates `[0,1],[0,2],[0,3]` which is appended to the first so the output is:

```
[[1,10],[1,11],[1,12],[2,10],[2,11],[2,12],[5,10],[5,11],[5,12],[0,1],[0,2],[0,3]]

```

## Test cases

```
"0:0/" -> [[0,0]]
"1-3:2/" -> [[1,2],[2,2],[3,2]]
"4:5-6/" -> [[4,5],[4,6]]
"9,10,11:9-11/" -> [[9,9],[9,10],[9,11],[10,9],[10,10],[10,11],[11,9],[11,10],[11,11]]
"100:0-1,2,3-4/1:2/" -> [[100,0],[100,1],[100,2],[100,3],[100,4],[1,2]]
"1:2/3:4/5:6/7:8/9:10/" -> [[1,2],[3,4],[5,6],[7,8],[9,10]]
"11-13:2/" -> [[11,2],[12,2],[13,2]]

```

## Rules

* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.
* You can assume the input will always be a valid literal, you don't have to handle invalid literals.

# Answer
> 4 votes
# Jelly, ~~25~~ 23 bytes

```
ṣṪṣ”:ṣ”,⁾-ry$€VFƲ€ŒpƊ€Ẏ

```

Try it online!

-2 bytes from reading Kevin Cruijssen's answer.

```
ṣṪṣ”:ṣ”,⁾-ry$€VFƲ€ŒpƊ€Ẏ
ṣ                       Split on
 Ṫ                        last character, removing it from the string
                    Ɗ€  For each:
  ṣ”:                     Split on ":"
                Ʋ€        For each:
     ṣ”,                    Split on ","
            $€              For each:
           y                  Replace
        ⁾-r                     "-" with "r"
              V             Evaluate as Jelly programs (r = range)
               F            Flatten
                  Œp      Cartesian product
                      Ẏ Tighten (shallow flatten)

```

# Answer
> 4 votes
# 05AB1E, 25 bytes

```
¯I¤¡¨vy':¡ε',¡ε'-¡Ÿ}˜}`â«

```

Pretty straight-forward approach.

Try it online or verify all test cases.

**Explanation:**

```
¯                    # Start with an empty list []
 I                   # Push the input-string
  ¤                  # Push its last character (without popping): "/"
   ¡                 # Split it on "/"
    ¨                # Remove the trailing empty string
     vy              # Foreach over the parts:
       ':¡          '#  Split the part on ":"
          ε          #  Map over each smaller part:
           ',¡      '#   Split it on ","
              ε      #   Inner map yet again:
               '-¡  '#    Split on "-"
                  Ÿ  #    Convert this pair (or single integer) to a ranged list
              }˜     #   After the inner-most map: flatten
          }`         #  After the outer map: pop and push the lists separated to
                     #  the stack
            â        #  Create pairs of the two lists with the cartesian product
             «       #  Merge this list of pairs to the result-list
                     # (after the loop, the result is output implicitly)

```

# Answer
> 4 votes
# Ruby, ~~98~~ 87 bytes

```
p`dd`.gsub(/\d+-/,'*\00..').split(?/).flat_map{|x|eval"[%s].product([%s])"%x.split(?:)}

```

Try it online!

#### Explanation

```
 `dd`.gsub(/\d+-/,'*\00..')               # input and replace "number-" with "*number-0..", ruby syntax for ranges
.split(?/).flat_map                       # split on "/" and map block, then concat
{|x|eval"[%s].product([%s])"%x.split(?:)} # string interpolate and eval
p                                         # print

```

# Answer
> 3 votes
# Vyxal, ~~36~~ 27 bytes

```
ṫ/ƛ\:/ƛ⌐ƛ\-/k≈•⌊÷ṡ;f;÷Ẋ;f2ẇ

```

Try it Online!

*-9 thanks to Kevin*

With colour:

## Explained

```
ṫ/ƛ\:/ƛ⌐ƛ\-/k≈•⌊÷ṡ;f;÷Ẋ;f2ẇ
ṫ/                           # Split the input string on its last character ("/") - returns groups
  ƛ                          # To each group G:
   \:/                       #   Split G on ":" - returns sets
      ƛ                      #   To each set S:
       ⌐                     #     Split S on commas - returns values
        ƛ                    #     To each value V:
         \-/                 #       Split V on "-" - returns items in range
            k≈•              #       Mold that to the shape of [0, 1] - honestly idk what this does, but it works and it's genius. (it seems to make it so that each list is of length 2, even if it's a single item list)
              ⌊÷ṡ            #       Generate an inclusive range between the two numbers
                 ;           #     End map over each V
                  f          #     and flatten that - returns a flat list of all numbers to cartesian product
                   ;         #   End map over each S
                    ÷Ẋ       #   Cartesian product of the sets
                      ;      # End map over each G
                       f2ẇ   # flatten and place back into pairs

```

# Answer
> 3 votes
# Ruby, ~~131 118~~ 110 bytes

```
->s{eval"[#{s.gsub(/(\d+)-/,'*\1..').gsub(/([^\/:]+)/,'[\1]').gsub(/:([^\/:]+)/,'.product(\1)').tr ?/,?+}[]]"}

```

Try it online!

I tried to parse the expression and apply the single operations, but the shortest solution is to just convert the string into a Ruby expression, and evaluate it.

# Answer
> 3 votes
# Python 3, 188 bytes

```
from itertools import*
f=lambda s:[q for x in s.split("/")[:-1]for q in product(*([w for z in y.split(",")for w in range(*map(eval,(z+"-"+z+"+1").split("-")[-2:]))]for y in x.split(":")))]

```

Try it online!

Uses a lot of nested list comprehensions. The hardest parts are the ranges. `(z+"-"+z+"+1").split("-")[-2:]` converts a range of form `"a-b"` to `["a","b+1"]` and a single integer `"a"` to `["a","a+1"]`. These are then evaluated and fed directly to `range`.

# Answer
> 2 votes
# Zsh, 96 bytes

```
for x (${(s:/:)${1//(#m)<->-<->/\{${MATCH/-/..}\}}})eval print -l \{${x/:/,z\},\{z,}\}|grep -v z
```

Attempt This Online!

Zsh seems like it was *made* for this challenge!

*not*.

---

Explanation:

* `${1//(#m)<->-<->/\{${MATCH/-/..}\}}`: replace all instances of `A-B`, where `A` and `B` are numbers, with `{A..B}`
* `for x (${(s:/:)})`: split that on `/` and loop:
    + `${x/:/,z\},\{z,}` replace `:` with `,z},{z,`
    + This constructs strings that follow Zsh's pattern of brace expansion, which is the easiest way to do a Cartesian product
    + By `eval`ing them, they are expanded properly, and `print -l` prints them newline-separated.
    + The `,z`s are to work around the fact that things of the form `{0}` are treated as literal strings, and don't just expand to a 1-element list. They are removed again by the `|grep -v z`

# Answer
> 2 votes
# Ruby, ~~79~~77 bytes

```
->s{eval"[#{s.gsub(?:,'].product([').gsub(/\d+-/,'*\00..').gsub ?/,'])+['}]"}

```

Try it online!

* Saved 2 thanks to @G B

The literal already has a structure we can use, we just have to substitute a few symbols and then we evaluate it

```
[      prepend a [
#{s.gsub(..).gsub(...    transform input by replacing:
  `:`       => '].product(['
  `/(\d+)-/` => '*\1..'  here \1 is the captured number
  `/`       => '])+[' we add next square
] which we close empty if there's no group available.

```

Here is an example with **adds** and `substitutions` :
100 `:` `0-` 1 , 2 , `3-` 4 `/` 1 `:` 2 `/`
**\[** 100 `].product([` `*0..` 1,2, `*3..` 4 `])+[` 1 `].product([` 2 `])+[` **\]**

# Answer
> 1 votes
# Retina, 79 bytes

```
!_S`/
%(+`\b(\d+)-(\1\b|())
$1$#3*$(,$.(*__)-
Lw$`\b(\d+)\b.*:.*\b(\d+)\b
$1,$2

```

Try it online! Outputs each pair on its own line but link includes test suite that joins the lines back together for convenience. Explanation:

```
!_S`/

```

Split on `/`s, but drop empty entries.

```
%(`

```

Separately for each split:

```
\b(\d+)-(\1\b|())
$1$#3*$(,$.(*__)-

```

Expand a range: if it has already expanded to the form `n-n` then simply delete the `-n` otherwise replace it with `n,n+1-m`.

```
+`

```

Repeat until all ranges have been completely expanded.

```
Lw$`\b(\d+)\b.*:.*\b(\d+)\b
$1,$2

```

Take the Cartesian product of both sets by considering overlapped matches of one number from each of the sets.

# Answer
> 1 votes
# Charcoal, 49 bytes

```
Ｆ⪪Ｓ/¿ι«≔⟦⟧θＦ²ＦＥ⪪§⪪ι:¬κ,Ｉ⪪λ-Ｆ…·§λ⁰⊟λ¿¬κ⊞θμＦθ⟦⁺⁺μ,ν

```

Try it online! Link is to verbose version of code. Would be 1 byte shorter if the product could be output in a different order. Explantion:

```
Ｆ⪪Ｓ/¿ι«

```

Split the input on `/`s and loop over non-empty groups.

```
≔⟦⟧θ

```

Prepare to collect the second set.

```
Ｆ²

```

Loop over each set.

```
ＦＥ⪪§⪪ι:¬κ,Ｉ⪪λ-

```

Split the group on `:`, extract the desired set, then split that on `,`, then split that on `-`, then cast to integer.

```
Ｆ…·§λ⁰⊟λ

```

Loop over each of the resulting ranges. (Where there was no `-` in that range, the same integer will be used as the start and end of the range, resulting in a range of that integer.)

```
¿¬κ

```

If this is the second set (which is being processed first), then...

```
⊞θμ

```

... save this integer for later, otherwise...

```
Ｆθ⟦⁺⁺μ,ν

```

... for all integers from the second set, pair the current integer from the first set with it.

# Answer
> 1 votes
# Bash \+ GNU coreutils, 126 bytes

```
tr :/ \\n|sed -Ee 's/([0-9]+)-([0-9]+)/{\1..\2}/g' -e 's/.+,.+/{\0}/'|while read s&&read t;do eval printf %s\\\\n $s\\ $t;done

```

Try it online! Takes input on STDIN without a trailing newline. Explanation:

```
tr :/ \\n|

```

Split the input on both colons and slashes. This results in a trailing newline but `read` eats that anyway.

```
sed -Ee 's/([0-9]+)-([0-9]+)/{\1..\2}/g' -e 's/.+,.+/{\0}/'|

```

Expand numeric ranges and wrap lists in braces.

```
while read s&&read t;do eval printf %s\\\\n $s\\ $t;done

```

Read two sets at a time and generate their Cartesian product.

# Answer
> 1 votes
# Pure Bash, ~~223~~ ~~213~~ 205 bytes

```
IFS=/
for i in $1
do
l=
IFS=:
for j in $i
do
while [[ $j =~ ([0-9]*)-([0-9]*) ]]
do
set -- ${BASH_REMATCH[@]}
j=${j/$1/"{$2..$3}"}
done
k=${j##*,*}
l=$l\\\ ${k:-"{$j}"}
done
eval printf %s\\\\n ${l:2}
done

```

Try it online! Takes input as a command-line parameter. Edit: Saved 10 bytes thanks to @pxeger. Explanation:

```
IFS=/
for i in $1
do
...
done

```

Split the input on `/`s. (The last empty string gets ignored.)

```
l=

```

Start building up the sets.

```
IFS=:
for j in $i
do
...
done

```

Split the group on `:`s.

```
while [[ $j =~ ([0-9]*)-([0-9]*) ]]
do
set -- ${BASH_REMATCH[@]}
j=${j/$1/"{$2..$3}"}
done

```

Expand numeric ranges.

```
k=${j##*,*}
l=$l\\\ ${k:-"{$j}"}

```

Wrap lists in braces and concatenate the sets.

```
eval printf %s\\\\n ${l:2}

```

Generate the Cartesian product of the sets.

# Answer
> 1 votes
# Python 3, 187 bytes

```
import itertools as t
[k for b in s.split('/')[:-1] for k in t.product(*[[j for x in m.split(',') for j in range(*[int(x.split('-')[0]),int(x.split('-')[-1])+1])] for m in b.split(':')])]

```

# Answer
> 1 votes
# Burlesque, 54 bytes

```
~]'/;;{':;;{',;;{J'-~[{'-;;)ti^pr@}qtiIE}\m}MPcp}\m}MP

```

Try it online!

```
~]           # Drop final /
'/;;         # Split on /
{
  ':;;       # Split on :
  {
   ',;;      # Split on ,
   {
    J'-~[    # Contains -
    {
     '-;;    # Split on -
     {ti}MP  # Map to int and force onto stack
     r@      # Range from low to high
    }
    {ti}     # To int
    IE       # If else
   }\m       # Map and concatenate
  }MP        # Map and push
  cp         # Cartesian product
 }\m         # Map and concatenate
}MP          # Map and push

```

# Answer
> 1 votes
# , 196 bytes

```
function(x,`[`=sapply,t=strsplit,d=do.call)apply(matrix(t(x,'/')[t,":"][t,","][t,"-"][lapply,function(j)as.list(scan(t=j)+!3:4)][function(i)unlist(i[d,w=`:`])],2),2,function(l)d(outer,c(l,paste)))

```

Try it online!

Outputs a list of each 'group of products' (separated by `/` in the input), containing space-separated pairs of elements.
+8 bytes to output as a flat vector.

**Ungolfed:**

```
a=
 sapply( ... strsplit(x,'/'),   # split input on '/
  sapply( ... strsplit(x,':'),  # split that on ':'
   sapply( ... strsplit(x,','), # split that on ','
    sapply(strsplit(x,'-'))     # and finally split that on '-'
b=lapply(a,function(j)as.list(rep(j,2)[1:2]))
                                # double any lists of one item
c=sapply(b,function(i)unlist(s(i,do.call,what=`:`)))
                                # and apply ':' (range) using
                                # 2-element lists as arguments,
                                # concatenating (unlist) the results
m=matrix(c,2)                   # put the output into 2-row matrices
apply(m,2,function(l)do.call(outer,c(l,paste)))
                                # and, for each column, paste togethe
                                # the elements of each of the two rows

```

# Answer
> 1 votes
# JavaScript (ES10), 150 bytes

This seems quite long...

```
s=>s.replace(/(\d+)-(\d+)/g,g=(_,a,b)=>a-b?a+[,g(_,-~a,b)]:a)[S='split']`/`.map(s=>s?(g=k=>s[S]`:`[k][S]`,`)(0).map(a=>g(1).map(b=>[a,b])):[]).flat(2)

```

Try it online!

---
Tags: code-golf, parsing
---


title: Create and write to a file

text:
# Question
Title: Create and write to a file
## Challenge

Create a new file and write the string `Hello World` to it.

## Restrictions

* Your challenge must write to a file on disk, in the file system.
* The file may not be a log file generated during normal operation of the interpreter.
* The file must contain **only** the string `Hello World`. It is allowed to contain a trailing newline or minimal whitespace. No other content.
* No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. `perl -p`)

## Notes

* This is , so shortest program in bytes wins.
* Follow the spirit, not the letter, of the rules.

# Answer
> 2 votes
## Pyth, 14 bytes

```
.w"Hello World

```

Outputs to a file called `o.txt`.

# Answer
> 25 votes
# Python 2, 32 bytes

```
print>>open(*"ww"),"Hello World"

```

Yes, this is valid python.

# Answer
> 8 votes
# Haskell, 25 bytes

```
writeFile"o""Hello World"

```

# Answer
> 6 votes
## zsh, 17 bytes

```
<<<Hello\ World>x

```

Outputs to a file called `x`.

# Answer
> 6 votes
# Vyxal 2.5.3, 32 bytes

```
kh→@|;@+open(*"ww").write(VAR_)#

```

Vyxal can't really do anything with external files, which would normally render this challenge impossible. However, in Vyxal 2.5.3 and prior, there was an ACE exploit allowing for arbitrary Python execution. Yep, I found another one.

---

#### The ACE:

Vyxal is a transpiled language, so every Vyxal command is translated to some Python code, and then all of the translated commands are executed. Previously, I found that you could escape a string to insert any Python commands you wanted into the transpiled code. It turns out that you can do something similar with function names.

When defining a function in Vyxal, the resulting python looks something like this:

```
def FN_func(parameter_stack, arity=None):
    ...setup stuff...
    ...commands...
    ...finishing stuff...
    return stack

```

When calling a function in Vyxal, the resulting Python code looks something like this:

```
stack += FN_func(stack)

```

The thing is, when parsing the name of a function, the strategy was to just read characters until reaching a `:`, `|`, or `;`, which are the delimiters of different parts of the function declaration/call. This meant that you could put any characters you wanted into the name, and it would attempt to transpile it the same way.

In this case, I used a `+` in the function name when I called it. That results in this transpiled code:

```
stack += FN_+open(*"ww").write(VAR_)#(stack)

```

This code will error when ran, because it tries to add together a function and the None that is returned from the `open` command. However, even though it errors, the `open` command still runs, meaning that we have executed arbitrary Python. If you wanted to write longer sections of Python code, you could replace the `+` with `([])` and add a newline after it.

---

#### The program:

In this program, the payload (the arbitrary Python code) is the following:

```
open(*"ww").write(VAR_)

```

The basis of this code is the `open().write()` command, which creates a file named `w` if it doesn't exist, then writes the contents of `VAR_` to it.

The `VAR_` variable is set at the beginning of the Vyxal program with `kh→`. This pushes the builtin `Hello World` and saves it to the nameless variable. All variable names are prepended with `VAR_` internally, so the variable `VAR_` is created and contains `Hello World`, which is written to the newly created file. Even though this has the overhead of the ACE setup, it ends up being shorter than the Python solutions due to the builtin.

This ACE has not been fixed in the repo, but it had a patch applied server-side for the online interpreter. It was also fixed in the rewrite and subsequent 2.6 release. If you want to try out this program for yourself, you can download the 2.5.3 version here.

# Answer
> 5 votes
# Vim, 15 + 2 == 17 bytes

```
iHello World<esc>ZZ

```

+2 bytes for launching this with `vim f` instead of `vim`. Additionally, this version works to:

```
iHello World<C-o>ZZ

```

If launching vim like this is not allowed, there is also:

### Vim, 18 bytes

```
iHello World<esc>:w f<cr>

```

Side note: this is a polyglot. The same thing works in V, except that it is one byte shorter (since the `<cr>` at the end is implicit.)

# Answer
> 5 votes
# Ruby, 26 bytes

Writes to file `f`.

```
open(?f,?w)<<"Hello World"

```

# Answer
> 5 votes
## Batch, 19 bytes

```
@echo Hello World>o

```

# Answer
> 5 votes
# **Batch, 18 bytes**

```
echo Hello World>f

```

# Answer
> 3 votes
# C, 44 bytes

```
main(){fputs("Hello World",fopen("o","w"));}

```

# Answer
> 3 votes
# Dyalog APL, 19 bytes

```
⎕NPUT⍨'Hello World'

```

Creates a file with the name and contents "Hello World".

# Answer
> 3 votes
# PowerShell, 15 bytes

```
"Hello World">o

```

`>` redirects the string to a file called `o` in the current directory.

# Answer
> 3 votes
# Node.js, 42 bytes

```
require("fs").writeFile('o','Hello World')

```

i don't think this needs explanation

# Node.js REPL, 31 bytes

```
fs.writeFile('o','Hello World')

```

for some reason in repl you dont need to include `fs`

# Answer
> 3 votes
## Bash, 18 bytes

```
echo Hello World>a

```

# Answer
> 2 votes
# ed, 19 characters

```
i
Hello World
.
w o

```

Sample run:

```
bash-4.3$ ed <<< $'i\nHello World\n.\nw o'
12

bash-4.3$ cat o
Hello World

```

# Answer
> 2 votes
# MATL, 15 bytes

```
'Hello World'Z#

```

This creates a file called `inout` and writes the string to it.

# Answer
> 2 votes
## K, 20 Bytes

```
    `:f 0:,"Hello World"
    `:f

```

Confirmation;

```
    mmm@chromozorz:~/q$ cat f.txt
    Hello World

```

# Answer
> 2 votes
# R, ~~38~~ ~~36~~ 35 bytes

```
sink(" ");cat("Hello World");sink()

```

I like how the created file has no name ! It's just ~~`.txt`~~ anything, in fact !

**-2** bytes thanks to @PEAR remark !
**-1** bytes thanks to @BartvanNierop !

This code will produce a file with no name.

# Answer
> 2 votes
# C#, ~~93~~ ~~77~~ 76 bytes

~~`using System.IO;namespace N{class C{static void M(){File.WriteAllText("f", "Hello World");}}}`~~

~~`class C{static void Main(){System.IO.File.WriteAllText("f", "Hello World");}}`~~

```
class C{static void Main(){System.IO.File.WriteAllText("f","Hello World");}}

```

See it work, with an exception for unauthorized file access.

## Changelog

### Rev2

* Removed unnecessary namespace
* Changed function name to Main (because otherwise it won't be detected as main function)
* Removed `using` directive (thanks Jean Lourenço)

### Rev3

* Removed space that sneaked in.

# C# (without boilerplate), 47 bytes

```
void M(){File.WriteAllText("f","Hello World");}

```

# Answer
> 2 votes
# Clojure, 23 bytes

```
#(spit"x""Hello World")

```

Anonymous function which creates file called `x` and writes `Hello World` there.

# Answer
> 1 votes
# Python, 34 bytes

```
open("h","w").write("Hello World")

```

Outputs to a file called `h`.

# Answer
> 1 votes
# APLX, 15 bytes

```
'Hello World'⍈1

```

Creates an APL component file containing just one component; the desired string. It can be read back with:

```
      'Hello World'⍇1
Hello World

```

# Answer
> 1 votes
# Gema, 28 characters

```
\A=@write{o;Hello World}@end

```

Sample run:

```
bash-4.3$ gema '\A=@write{o;Hello World}@end'

bash-4.3$ cat o
Hello World

```

# Answer
> 1 votes
# Java 7, ~~100~~ 95 bytes

```
void f()throws Exception{java.io.Writer p=new java.io.PrintWriter("x");p.print("Hello World");}

```

Or if you want to close the writer after using it (**101 bytes**):

```
void f()throws Exception{try(java.io.Writer p=new java.io.PrintWriter("x")){p.print("Hello World");}}

```

**Ungolfed:**

```
class Main{
  static void f() throws Exception{
    try(java.io.Writer p = new java.io.PrintWriter("x")){
      p.print("Hello World");
    }
  }

  public static void main(String[] a){
    try{
      f();
    } catch(Exception ex){
    }
  }
}

```

**Usage:**

```
java -jar Main.jar

```

# Answer
> 1 votes
# Racket, 43 bytes

```
(display"Hello World"(open-output-file"f"))

```

# Answer
> 1 votes
## C#, ~~118~~ ~~112~~ 98 bytes

---

**Golfed**

```
void M(){var f=new FileInfo("_");var s=f.CreateText();s.Write("Hello World");s.Flush();s.Close();}

```

---

**Ungolfed**

```
public void M() {
    var f = new FileInfo( "_" );
    var s = f.CreateText();

    s.Write( "Hello World" );
    s.Flush();
    s.Close();
}

```

---

**Full explicit code**

```
using System.IO;

namespace N {
    class C {
        public void M() {
            // A file name is required
            FileInfo f = new FileInfo( "_" );

            // Obtain the Stream to later write on it
            StreamWriter s = f.CreateText();

            // Write 'Hello World' to the Stream
            s.Write( "Hello World" );

            // Flush it to the file
            s.Flush();

            // Close the Stream, for security and integrity reasons.
            s.Close();
        }
    }
}

```

---

**Releases**

* **v1.2** \- `-14 bytes` \- Changed to `var`s. Shoutout to Jean Lourenço.
* **v1.1** \- `-6 bytes` \- Simplified names.
* **v1.0** \- `118 bytes` \- Initial solution.

---

---

---

I'll leave a version down below that only uses the Console to write on th file. Just because I can.

---

## C# Console Version, 39 bytes

---

**Golfed**

```
void M(){Console.Write("Hello World");}

```

---

**Ungolfed**

```
public void M() {
    Console.Write("Hello World");
}

```

---

**Full code**

```
using System;

namespace N {
    class C {
        public void M() {
            // Write 'Hello World' to the output handler
            Console.Write("Hello World");
        }
    }
}

```

---

**Usage**

```
<Exe. file name>.exe > FileToOutput.txt

```

---

**Releases**

* **v1.0** \- `39 bytes` \- Initial solution.

# Answer
> 1 votes
# Nim, ~~28~~ 26 bytes

```
"o".writeFile"Hello World"

```

Yes, Nim has a function in the `system` module for opening a file, writing a string to it, then closing it again.

# Answer
> 1 votes
# Julia, 47 bytes

```
f=open("o","w");write(f,"Hello World");close(f)

```

I tried using `writedlm`, but it didn't work out.

# Answer
> 1 votes
# C, 37 bytes

```
main(){system("echo Hello World>o");}

```

# Answer
> 1 votes
# Perl 6,  ~~27~~  23 bytes

```
~~'o'.IO.spurt: 'Hello World'~~
spurt 'o','Hello World'
```

# Answer
> 1 votes
# eacal, 26 bytes

```
write a string Hello World

```

This `write`s a `string` `Hello World` to file `a`, creating it if not present. Basically:

```
write <fileName> <exec>

```

and

```
string <params to convert to string>

```

Run the program as:

```
λ node eacal.js writeFile

```

# Answer
> 1 votes
# J, 21 bytes

```
'Hello World'1!:3<'o'

```

This writes to a file `o` in the current directory, or, if not called from a file, in your `j64-804` file. `1!:3` is the write foreign, and `<'o'` is the boxed filename (filenames need to be boxed). The LHS is the string to write.

# Answer
> 1 votes
**Java**

```
public class H
{
    public static void main(String[] a)
        throws IOException
    {
        FileWriter o = new FileWriter("x");
        o.write("Hello World");
        o.close();
    }
}

```

Simple I/O with no exception handling.

**Corrected**

Corrected the original code to write the correct string (`Hello World`).

# Answer
> 1 votes
# JavaScript, 89 bytes

This code was tested in Chrome. In other browsers, the element must be in the document for the click method to work.

```
a=document.createElement("a");a.href="data:text/plain,Hello World";a.download=1;a.click()

```

# Answer
> 1 votes
# HTML, 83 bytes

This code was tested in Chrome. It relies on the image failing to load, then it clicks itself, triggering the anchor tag which is a download link.

```
<a href="data:text/plain,Hello World" download><img src onerror="this.click()"></a>

```

# Answer
> 1 votes
# Awk, ~~29~~ 27 characters

```
BEGIN{print"Hello World">1}

```

(No, not another output redirection. Just Awk's syntax is similar.)

Thanks to:

* Pedro Maimere for suggesting to use integer for file name (-2 characters)

Sample run:

```
bash-4.3$ awk 'BEGIN{print"Hello World">1}'

bash-4.3$ cat 1
Hello World

```

# Answer
> 1 votes
# Tcl, 28 bytes

```
puts [open T w] Hello\ World

```

# Answer
> 1 votes
# JavaScript (SpiderMonkey), <sup>~~48 37 30~~</sup> 29 bytes

```
open`data:text/t,Hello World`

```

Try it online!

# Answer
> 1 votes
# R, 20 bytes

```
write("Hello World")

```

This creates a file named "data" in the current directory and write "Hello World" in it.

# Answer
> 0 votes
## Bash script, ~~20~~ 18 bytes

```
echo Hello World>o

```

Save this as a file `write.sh` and run it: \`bash o.sh

# Answer
> 0 votes
# AutoIT, ~~43~~ 40 bytes

```
FileWrite(FileOpen("a",1),"Hello World")

```

**Explanation**

FileOpen takes two parameters and returns the handle of the file. Mode must be 1 for writing (appending) text.

> FileOpen ( "filename" \[, mode = 0\] )

FileWrite takes two parameters, a handle and the text to write

> FileWrite ( "filehandle/filename", "text/data" )

If a file does not exist, AutoIT will create it. Note that in my example it will not have any file extension associated (filename: a), but can still be opened with any text editor.

AutoIT is a Windows only scripting language.

Script-Example.com has an online AutoIT compiler that can verify the solution.

# Answer
> 0 votes
# Php, 38 bytes

`file_put_contents('a', 'Hello World');`

# Answer
> 0 votes
# PHP, 34 bytes

```
fputs(fopen(7,'c'),'Hello World');

```

# Answer
> 0 votes
# Mathematica, 27 bytes

```
".txt"~Export~"Hello World"

```

# Answer
> 0 votes
# Perl, 20 bytes

```
`echo Hello World>o`

```

Perl will execute anything in backticks (\`) as a system command.

# Answer
> 0 votes
## ListSharp, 37 bytes

```
OUTP="Hello World" HERE[<here>+"\\a"]

```

simply writes Hello World to a file called "a"(not even a text file) in the script execution environment,

# Answer
> 0 votes
# PHP, 27 bytes

```
exec('echo Hello World>o');

```

# PHP, 20 bytes

```
`echo Hello World>o`

```

# Answer
> 0 votes
## C#, 50 bytes

```
s=>System.IO.File.WriteAllText("f","Hello World");

```

An anonymous function that takes in an unused argument and outputs the file.

Alternatively and cheating slightly this one:

```
s=>System.IO.File.WriteAllText("f",s);

```

That takes in a string and works assuming the string contains the text: `Hello World`, for 38 bytes.

# Answer
> 0 votes
# Common Lisp, 69 bytes

Lauded for being incredibly expressive, it's not the best golfing language...

```
(with-open-file (f "f" :direction :output) (format f "Hello, world"))

```

See it work, with permission denied.

# Answer
> 0 votes
# Groovy, 28 characters

```
new File("o")<<"Hello World"

```

Sample run:

```
bash-4.3$ groovy -e 'new File("o")<<"Hello World"'

bash-4.3$ cat o
Hello World

```

# Answer
> 0 votes
# Sed, 20 characters

(19 characters code + 1 character dummy input.)

```
s/^/Hello World/
wo

```

Seems the side effect of also displaying the string to STDOUT after the file was created is not prohibited.

Requires dummy input to work as per Are languages like sed exempt from “no input” rules?

Sample run:

```
bash-4.3$ sed $'s/^/Hello World/;wo' <<< ''
Hello World

bash-4.3$ cat o
Hello World

```

# Answer
> 0 votes
# QBasic, 39 bytes

```
OPEN"f"FOR OUTPUT AS#1
?#1,"Hello World

```

Opens a file named `f` (creating it if it doesn't exist, wiping it if it does) and gives it the file handle `#1`. Then prints (`?`) to file `#1` the string `Hello World` (with a trailing newline).

# Answer
> 0 votes
# Jelly, 25 bytes

```
“ṠȷŀƤoĊịSAĊhJİⱮa¤XPṢḞɦ»ŒV

```

Try it online!

Executes the Python code `open(*'aw').write('Hello World')`.

---
Tags: code-golf, kolmogorov-complexity, hello-world, file-system
---


title: Constructing Solar Panels from Squares

text:
# Question
Title: Constructing Solar Panels from Squares
I'm designing a new space station for generic super-villain purposes (something something megalaser), but I'm having trouble designing the solar panels.

My genius team of scientists can calculate exactly how many square meters of paneling we need to power the station, but the problem is our solar panels only come in squares!

Thankfully due to a generous supply of duct tape, my minions can stitch together the right squares to make up the surface area needed, but my scientists have gone on strike (something about cyanide not being an ethical coffee sweetener) and my minions are too stupid to figure out what squares they need to connect.

That's where you come in ~~minion~~ loyal golfer. I need some code that will take the target surface area and tell me what size solar panels my minions need to tape together to reach it.

The minions have a tiny budget, so they still have to program their computer by punchcard. Time spent programming is time not spent taping, so make sure your code is as small as possible!

## The Challenge

Given a positive integer `n`, output the smallest list of square numbers that sums to `n`.

A square number is any integer that is the result of multiplying an integer by itself. For example `16` is a square number because `4 x 4 = 16`
This is A000290

For example:
For `n = 12`, you could achieve the desired size with 4 panels of sizes `[9, 1, 1, 1]` (note that this is the correct answer for the Google FooBar variant of this challenge), however this is not the smallest possible list, because you can also achieve the desired size with 3 panels of sizes `[4, 4, 4]`
For `n = 13`, you can achieve the desired size with only 2 panels: `[9, 4]`

If `n` is a square number, the output should be `[n]`.

### Input

A positive integer `n` representing the total desired surface area of the solar panels.
Note that `0` is not positive

### Output

The smallest possible list of square numbers that sums to `n`, sorted in descending order.
If there are multiple smallest possible lists, you may output whichever list is most convenient.

### Testcases

```
1 -> [1]
2 -> [1,1]
3 -> [1,1,1]
4 -> [4]
7 -> [4,1,1,1]
8 -> [4,4]
9 -> [9]
12 -> [4,4,4]
13 -> [9,4]
18 -> [9,9]
30 -> [25,4,1]
50 -> [49,1] OR [25,25]
60 -> [49,9,1,1] OR [36,16,4,4] OR [25,25,9,1]
70 -> [36,25,9]
95 -> [81,9,4,1] OR [49,36,9,1] OR [36,25,25,9]
300 -> [196,100,4] OR [100,100,100]
1246 -> [841,324,81] OR one of 4 other possible 3-length solutions
12460 -> [12100,324,36] OR one of 6 other possible 3-length solutions
172593 -> [90601,70756,11236] OR one of 18 other possible 3-length solutions

```

# Answer
> 8 votes
# Python 3.8 with Numpy using Lagrange's four-square theorem, 92 bytes

A Numpy version with Lagrange's four-square theorem as exploited by others.

3 bytes shaved thanks to @ovs using the `r_` trick, literally called `index_tricks` in Numpy.

i.e. the Lagrange's four-square theorem together with Numpy save you 44 byte comparing to pure Python.

```
from numpy import*
lambda n:[r[r!=0][::-1]**2for i in ndindex(*[n+1]*4)if(r:=r_[i])@r==n][0]

```

Faster but use 1 more byte:

```
from numpy import*
f=lambda n:next(r[r!=0][::-1]**2for i in ndindex(*[n+1]*4)if(r:=r_[i])@r==n)

```

Fully written out:

```
from numpy import ndindex, square, sum
def f(n):
    for i in ndindex(m := n + 1, m, m, m):
        if sum(s := square(i)) == n:
            return s[s!=0][::-1]

```

The version with `r_` is equivalent (but not identical) to

```
from numpy import ndindex, square, array
def f(n):
    for i in ndindex(m := n + 1, m, m, m):
        if (a := array(i)) @ a == n:
            return a[a!=0][::-1]**2

```

# Python 3.8 using Lagrange's four-square theorem, 135 bytes

A pure Python version with Lagrange's four-square theorem as exploited by others.

i.e. the Lagrange's four-square theorem only save you one byte with pure Python.

```
from itertools import *
lambda n:[[a for a in s[::-1]if a!=0]for i,j,k,l in product(*[range(n+1)]*4)if sum(s:=(i*i,j*j,k*k,l*l))==n][0]

```

Try it online!

Faster but use 1 more byte:

```
from itertools import *
lambda n:next([a for a in s[::-1]if a!=0]for i,j,k,l in product(*[range(n+1)]*4)if sum(s:=(i*i,j*j,k*k,l*l))==n)

```

Try it online!

Fully written out:

```
from itertools import product
def f(n):
    for i, j, k, l in product(*[range(n + 1)] * 4):
        if sum(s := (i * i, j * j, k * k, l * l)) == n:
            return [a for a in s[::-1] if a != 0]

```

# Python 3.8, 136 bytes

A brute force version with no import.

```
g=lambda n:[[]]if n==0else sum(([l+[i*i]for l in g(r)]for i in range(1,n+1)if(r:=n-i*i)>=0),[])
lambda n:sorted(min(g(n),key=len))[::-1]

```

Try it online!

Fully written out:

```
def g(n: int) -> list[list[int]]:
    """Calculate all combinations of set of square numbers that sum to n.

    :param int n: >= 1
    """
    if n == 0:
        return [[]]
    res = []
    for i in range(1, n + 1):
        r = n - i * i
        if r >= 0:
            res += [l + [i * i] for l in g(r)]
    return res

def f(n):
    """Calculate the smallest set of square numbers that sum to n.

    In decending orders.
    """
    return sorted(min(g(n), key=len))[::-1]

```

# Test

```
for i in [
    1,
    2,
    3,
    4,
    7,
    8,
    9,
    12,
    13,
    18,
    30,
    50,
    60,
    70,
    95,
    300,
    1246,
    12460,
    172593,
]:
    print(f"{i}\t{f(i)}")

```

# Answer
> 7 votes
# , ~~81~~ 79 bytes

-2 bytes thanks to pajonk

```
function(n,`!`=function(x)outer(x,x,`+`),x=which(n==!!(0:n)^2,T)[1,]-1)x[x>0]^2

```

Try it online! (For large inputs, TIO will run into time-out/out-of-memory problems.)

By Lagrange's four-square theorem, the output is always of length at most 4. This constructs all the sums of 4 squares from \\$0^2\\$ to \\$n^2\\$ in a 4-dimensional arrays, and keeps the first value which is equal to \\$n\\$. Because of how `which` works, it will first find sums which include some 0s if there are any, guaranteeing that we find solutions with 1/2/3 squares if there are any. We then filter out the 0s with `x[x>0]^2`.

In more recent version of R (unavailable on TIO for now), this can be shortened to:

---

# \>= 4.1.0, 65 bytes

```
\(n,`!`=\(x)outer(x,x,`+`),x=which(n==!!(0:n)^2,T)[1,]-1)x[x>0]^2

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 46 bytes

```
# #&@@PowersRepresentations[#,4,2]/. 0->Set@$&

```

Try it online!

Relies on the four-square theorem, then removes zeroes. Built-in does most of the work.

# Answer
> 3 votes
# 05AB1E, 10 bytes

```
ÅœéʒÅ²P}нR

```

Try it online!

will be ridiculously slow for larger inputs

```
integer partitions
sort by length
filter
  square? (implicit map)
  product
  (implicit truthy)
end filter
head
reverse

```

# Answer
> 3 votes
# JavaScript (ES6), ~~110~~ ~~81~~ 71 bytes

*-7 thanks to Mayube, -6 thanks to emanresu A, and -2 thanks to Arnauld*

```
f=(x,i=x**.5|0,r=i?[i*i,...f(x-i*i)]:[])=>s=i>1&&r[f(x,i-1).length]?s:r

```

Recursive solution. Lots of golfs along the way :p

Try it online!

# Answer
> 3 votes
# , 36 bytes

```
((i.~+/&>){])[:*:&.>@,4{\@$[:<1+i.@-

```

Try it online!

Brute force. Relies on 4-square theorem, which I learned about from Robin Ryder's answer.

# Answer
> 3 votes
# Python 2, ~~77~~ 76 bytes

```
f=lambda n,i=1:min(`f`*(~i*~i>n)or f(n,i+1),n and[i*i]+f(n-i*i)or[],key=len)

```

Try it online!

```
f=lambda n,i=1         # recursive function with input n and initial side length 1
   n and ... or []     # If n is 0, return the empty list.
   min(..., key=len)   # Otherwise return the shortest of
     `f`*(~i*~i>n)     #  - '<function <lambda> at ...>' if (i+1)**2 is larger than n
      or f(n,i+1)      #    or the result of the recursive call f(n, i+1)
     [i*i]+f(n-i*i)    #  - the shortest solar panel configuration starting with a length-i panel
                       # In case both have the same length, the first will be selected.
                       # This results in larger panels appearing first.

```

# Answer
> 3 votes
# , 67 bytes

```
function(n,b=n+1){while(sum(T)-n)T=((F=F+1)%/%b^(0:3)%%b)^2;T[T>0]}

```

Try it online!

Counts up from 1, converting each number to base-`n` digits, least-significant first, and returning the first set for which the sum of squares of the digits equals `n`.

---

*(previous version, with 4 bytes saved thanks to Robin Ryder)*:
**\# , ~~75~~ 71 bytes**

```
function(n,x=expand.grid(a<-0:n,a,a,a)^2,y=x[rowSums(x)==n,][1,])y[y>0]

```

Try it online!

Uses a variation of Robin Ryder's approach, here constructing all combinations of four squares in one step using the built-in  function `expand.grid`.

# Answer
> 2 votes
# Jelly, 9 bytes

```
ŒṗÆ²Ạ$ƇṪU

```

Try it online!

```
ŒṗfƑƇ²€ṪU

```

Try it online!

Times out for test cases larger than 50.

## How they work

```
ŒṗÆ²Ạ$ƇṪU - Main link. Takes n on the left
Œṗ        - Integer partitions of n; Ways to sum positive integers to n
     $Ƈ   - Keep those partitions P for which the following is true:
    Ạ     -   All elements are:
  Æ²      -   Square numbers
       ṪU - Take the last (the shortest) and reverse it

ŒṗfƑƇ²€ṪU - Main link. Takes n on the left
Œṗ        - Integer partitions of n; Ways to sum positive integers to n
      €   - For each integer to n:
     ²    -   Yield its square
   ƑƇ     - Keep partitions that are unchanged after:
  f  ²€   -   Removing all non-squares
       ṪU - Take the last (the shortest) and reverse it

```

# Answer
> 2 votes
# Retina 0.8.2, ~~201~~ ~~92~~ 91 bytes

```
.+
$*
^((^1|11\2)*?)((1(?(4)1\4))*?)((1(?(6)1\6))*?)((1(?(8)1\8))+)$
$.7 $.5 $.3 $.1
+` 0$

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
^((^1|11\2)*?)((1(?(4)1\4))*?)((1(?(6)1\6))*?)((1(?(8)1\8))+)$

```

Try to match 3 squares lazily, plus a 4th square (greedily, since that's golfier). This is based on my answer to Three triangular numbers but adjusted to match squares instead. (I'm not sure where the original square matching pattern was devised but Retina's entry in the Showcase of Languages has it.) The lazy matching of the first three squares generates the squares in ascending order, with the first squares as low as possible (preferably zero).

```
$.7 $.5 $.3 $.1

```

List the matched squares in descending order.

```
+` 0$

```

Delete any trailing zeros.

# Answer
> 2 votes
# Charcoal, 37 bytes

```
ＮθＦ⊕θＦ⊕ιＦ⊕κＦＥ⊕λＸ⟦μλκι⟧²Ｆ⁼θΣμ⊞υμＩ⮌Φ⌊υι

```

Try it online! Link is to verbose version of code. Very slow. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆ⊕θＦ⊕ιＦ⊕κＦＥ⊕λＸ⟦μλκι⟧²

```

Generate all sets of four squares in ascending order with the largest square not exceeding .

```
Ｆ⁼θΣμ⊞υμ

```

If the squares sum to `n` then save the set.

```
Ｉ⮌Φ⌊υι

```

Print the set with the most zeros, but without the zeros and in reverse order so that the largest element is printed first.

# Answer
> 2 votes
# JavaScript (ES6), 79 bytes

```
f=(n,i=o=1,l=[])=>(n?i>n||f(n-i*i,i,[i*i,...l])|f(n,i+1,l):l[o.length]?o:o=l,o)

```

Try it online!

# Answer
> 2 votes
# Pari/GP, 54 bytes

```
n->forpart(p=n,prod(i=1,#p,issquare(p[i]))&&return(p))

```

Try it online!

Port of wasif's 05AB1E answer. PARI/GP has a built-in to iterate over integer partitions, sorted by length.

# Answer
> 2 votes
# Core Maude, 245 bytes

```
mod S is pr LIST{Nat}. ops([_])([_})({_]): Nat ~> Nat . var A B : Nat . eq[A]=[A
0]. ceq[A B]=[A B}if A ={[A B}]. eq[A B]=[A s B][owise]. eq[A s B}=((s B rem
s A)^ 2)[A(s B quo s A)}. eq[A 0}= nil . eq{A X:[Nat]]= A +{X:[Nat]]. eq{nil]=
0 . endm

```

The result is obtained by reducing the `[_]` operator with the input value, e.g., `[300]`.

### Example Session

```
Maude> red [1] .  --- Expected: [1]
result NzNat: 1
Maude> red [2] .  --- Expected: [1,1]
result NeList{Nat}: 1 1
Maude> red [3] .  --- Expected: [1,1,1]
result NeList{Nat}: 1 1 1
Maude> red [4] .  --- Expected: [4]
result NzNat: 4
Maude> red [7] .  --- Expected: [4,1,1,1]
result NeList{Nat}: 4 1 1 1
Maude> red [8] .  --- Expected: [4,4]
result NeList{Nat}: 4 4
Maude> red [9] .  --- Expected: [9]
result NzNat: 9
Maude> red [12] .  --- Expected: [4,4,4]
result NeList{Nat}: 4 4 4
Maude> red [13] .  --- Expected: [9,4]
result NeList{Nat}: 9 4
Maude> red [18] .  --- Expected: [9,9]
result NeList{Nat}: 9 9
Maude> red [30] .  --- Expected: [25,4,1]
result NeList{Nat}: 25 4 1
Maude> red [50] .  --- Expected: [49,1] OR [25,25]
result NeList{Nat}: 49 1
Maude> red [60] .  --- Expected: [49,9,1,1] OR [36,16,4,4] OR [25,25,9,1]
result NeList{Nat}: 49 9 1 1
Maude> red [70] .  --- Expected: [36,25,9]
result NeList{Nat}: 36 25 9
Maude> red [95] .  --- Expected: [81,9,4,1] OR [49,36,9,1] OR [36,25,25,9]
result NeList{Nat}: 81 9 4 1
Maude> red [300] .  --- Expected: [196,100,4] OR [100,100,100]
result NeList{Nat}: 196 100 4
Maude> red [1246] .  --- Expected: [841,324,81] OR one of 4 other possible 3-length solutions
result NeList{Nat}: 1156 81 9
Maude> red [12460] .  --- Expected: [12100,324,36] OR one of 6 other possible 3-length solutions
...

```

Maude didn't find a solution for \\$n = 12460\\$ before I got bored and killed the interpreter. But Maude has unbounded integers, so it would have found it eventually (see below).

### Ungolfed

```
mod S is
    pr LIST{Nat} .

    ops ([_]) ([_}) ({_]) : Nat ~> Nat .

    var A B : Nat .

    eq [A] = [A 0] .
    ceq [A B] = [A B} if A = {[A B}] .
    eq [A B] = [A s B] [owise] .

    eq [A s B} = ((s B rem s A) ^ 2) [A (s B quo s A)} .
    eq [A 0} = nil .

    eq {A X:[Nat]] = A + {X:[Nat]] .
    eq {nil] = 0 .
endm

```

The program is pure brute force. We keep a counter and interpret it as a base \\$n + 1\\$ number. So, e.g., for \\$n = 30\\$ we would interpret a counter value of \\$1026 = 1 \times 31^2 + 2 \times 31 + 3\\$ as the list \\$\[1, 2, 3\]\\$ and check if \\$1^2 + 2^2 + 3^3 = 30\\$. (It doesn't.) This checks *a lot* of impossible candidates (something like \\$(n - \sqrt{n})^4\\$ more than necessary), but Maude doesn't have an integer square root function to limit the search. (And that would cost bytes anyway.)

# Answer
> 2 votes
# Ruby, 78 bytes

```
f=->n,r=[[]]{r.find{|q|q.sum==n}||f[n,r.product([*-n..-1]).map{|x,y|x+[y*y]}]}

```

Try it online!

## Old version, with squares in ascending order (wrong)

# Ruby, 76 bytes

```
f=->n,r=[[]]{r.find{|q|q.sum==n}||f[n,r.product([*1..n]).map{|x,y|x+[y*y]}]}

```

Try it online!

# Answer
> 2 votes
# Brachylog, 9 bytes

```
~+.~^₂ᵐ≜∧

```

Try it online!

```
~+.~^₂ᵐ≜∧ the input
~+        is the sum of
  .       the output
   ~^₂ᵐ   whose elements are squares
          (√ doesn't work as it support floats)
       ≜  get a solution (that luckily is in the right order)
        ∧ return the output

```

# Answer
> 2 votes
# Vyxal, 11 bytes

```
ṄµL;'∆²A;Rh

```

Try it Online!

```
Ṅ           # Integer partitions
 µL;        # Sorted by length
    '   ;   # Filtered by...
       A    # All...
     ∆²     # Are square
          h # Get first (And therefore shortest)
         R  # Reversed

```

# Answer
> 1 votes
# Vyxal, 11 bytes

```
ɾ²Þ×'∑?=;tṘ

```

Try it Online!

# Answer
> 1 votes
# TI-Basic, ~~80~~ 83 bytes

```
Input N
For(I,0,N
For(J,0,N
For(K,0,N
For(L,1,N
If I²+J²+K²+L²=N and not(Ans(1
{L,K,J,I}²→S
End
End
End
End
sum(not(not(Ans→dim(ʟS
ʟS

```

Output is stored in `Ans` and displayed.

---

Faster but longer solution:

### ~~100~~ 103 bytes

```
Input N
√(N
For(I,0,Ans
For(J,0,Ans
For(K,0,Ans
For(L,1,Ans
If I²+J²+K²+L²=N:Then
{L,K,J,I}²→S
√(N→I
Ans→J
Ans→K
Ans→L
End
End
End
End
End
sum(not(not(ʟS→dim(ʟS
ʟS

```

# Answer
> 1 votes
# TI-Basic, 88 bytes

```
Input N
{1→A
While N≠sum(ʟA²
1+ʟA(1→ʟA(1
For(I,1,dim(ʟA
If N≤ʟA(I
Then
1→ʟA(I
If I<dim(ʟA
1+ʟA(I+1
Ans→ʟA(I+1
End
End
End
ʟA²

```

works with any number of panels (more than 4 if it was possible). It's basically an addition with a carry (up to N and starting at 1) because recursion is ~~impossible~~ a real pain in TI-Basic (all variables are global)

It is quite slow, it could be optimized for speed by setting the limit to `√N` instead of `N` and a condition such as `ʟA(I+1)≤ʟA(I)`

# Answer
> 0 votes
# Python 3, 104 bytes:

Pure Python, no imports, brute force:

```
def f(n,c):yield from([x for k in range(1,n+1)for x in f(n-k*k,c+[k*k])],[c])[n==0]
min(f(13,[]),key=len)

```

---
Tags: code-golf, number, optimization
---