# Question
Title: Build the widest unsupported bridge with nothing but frictionless blocks
In this challenge you must write a computer program that creates a stack of a thousand identical \\$1 \times 1\\$ frictionless homogeneous blocks such that each block is supported and the stack is stable under gravity when placed on the edge of a table which spans from \\$x = -\infty\\$ to \\$0\\$ horizontally, with the surface at \\$y = 0\\$. The winning criterion is the amount of *overhang* you manage to create, that is, the \\$x\\$ coordinate of the rightmost edge of the stack. Highest overhang wins.

This problem is analyzed in *Overhang* by Mike Paterson and Uri Zwick. Using their algorithm I wrote a judging program in Python that given a list of \\$(x, y)\\$ coordinates of the bottom left corners of the blocks returns whether the solution is valid and how much overhang it achieves. You will need Python 3 and the `pulp` library to run this program. You can get the latter using `python3 -m pip install --user pulp`. The program expects one pair of coordinates per line, separated by whitespace, on stdin.

To prevent rounding issues the judging program rounds the \\$x\\$ coordinates to six decimal places (and the \\$y\\$ coordinates are expected to be non-negative integers). Your answer must include (a link to) a list of coordinates that passes the judging program, and contain the score it reports. Yes, this does mean you need to be able to run your program to completion to get your output—you can't get away with "end of the universe" brute force.

As an example, the optimal stack with thirty blocks (2.70909 units of overhang):

Note that since the blocks are homogeneous and frictionless all forces are strictly vertical (in a balanced stack) and the actual width : height ratio of the blocks does not matter, so for clarity the blocks are shown elongated.

# Answer
> 8 votes
# Python 3, 3.742717 units

I figured just to get something out there I'd implement the harmonic stack, it's a pretty bad algorithm but being the first submitter that makes me the current winner ;)

# stack.py

```
# Number of blocks
N = 1000

# Evaluate 0.5*H(n)
def harmonic():
    h = 0
    i = 0
    yield 0 # Avoid divide by zero errors by defining H(0) to be 0
    while True:
        i += 1
        # Stupid rounding error means we need to divide by *sliightly* more than 2
        h += 1/(2.00000202478*i)
        yield h # Generators are sexy

# Get the harmonic number up to N
def nth_harmonic(n):
    return next(x for i,x in enumerate(harmonic()) if i==n)

def main():
    # Calculate the block offset
    offset = nth_harmonic(N) - 1

    for i, x in enumerate(harmonic()):
        # Spit the 6 decimal place formatted value to stdout along with the height
        print(format(offset - x, '.6f'), N - 1 - i)
        if i == N - 1: # We gotta stop at some point
            break

if __name__ == "__main__":
    main()

```

---
Tags: code-challenge, geometry
---


title: Non-sums of distinct positive powers

text:
# Question
Title: Non-sums of distinct positive powers
There are 31 positive integers that cannot be expressed as the sum of 1 or more distinct positive squares:

```
2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 22, 23, 24, 27, 28, 31, 32, 33, 43, 44, 47, 48, 60, 67, 72, 76, 92, 96, 108, 112, 128

```

There are 2788 positive integers that cannot be expressed as the sum of 1 or more distinct positive cubes:

```
2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67, 68, 69, 70, 71, 74, 75, 76, ...

```

It has been proven that this sequence is finite for all powers, and the largest term in each sequence is part of the Anti-Waring numbers, specifically \\$N(k,1)-1\\$, for a power \\$k\\$.

You are to take a positive integer \\$n \> 1\\$ as input, and output *all* positive integers that **cannot** be expressed as the sum of 1 or more distinct positive integers to the power of \\$n\\$. You may output the integers in any clear and consistent format (as digits, unary, Church numerals etc.) and you may use any clear and consistent separator between the numbers (newlines, spaces, as a list, etc.).

Your program *must* terminate, through error or natural termination, in finite time; iterating over all integers and outputting those that cannot be expressed in such a form is not an acceptable method.

This is , so the shortest code in bytes wins.

## Test cases

```
2 -> 2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 22, 23, 24, 27, 28, 31, 32, 33, 43, 44, 47, 48, 60, 67, 72, 76, 92, 96, 108, 112, 128
3 -> 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, ...
4 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, ...
5 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, ...
6 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67, 68, 69, 70, 71, 72, 73, ...
7 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, ...

```

# Answer
> 13 votes
# APL(Dyalog Unicode), 26 bytes SBCS

```
⊢{z~∊(⊢,+)\⍺*⍨z←⍳!⍵}!×2*×⍨

```

Try it on APLgolf!

This only works theoretically in multiple ways. The upper bound used (factorial of `c = n! * 2^(n^2)`is way too high to be accurately computed in floats, it would take forever to accurately compute it as a bigint, and it would quickly go out of memory trying to compute its range and all subset sums of *that*. As a minimal evidence of correctness, the function `g` in the link instead takes an explicit `limit` on its right and `n` on its left, and computes all numbers up to `limit` that are non-sums of distinct n-th powers.

### Deriving a correct and simple upper bound

A001661 contains a formula for the upper bound of the last term for each n. I was able to simplify it in many steps (and greatly overshoot the bound in the process) to just 7 bytes of APL:

```
d*2^(n-1)*(c*2^n + (2/3)*d*(4^n - 1) + 2*d - 2)^n + c*d
where c = n!*2^(n^2) and d = 2^(n^2 + 2*n)*c^(n-1) - 1

= d*(c + 2^(n-1)*(c*2^n + (2/3)*d*(4^n + 2) - 2)^n)

= d*(2*c + (2*c*2^n + (4/3)*d*(4^n + 2) - 4)^n)/2

by 2c<n^n*(2^n)^n = (n*2^n)^n
and a^n+b^n<(a+b)^n
= d*(n*2^n + 2*c*2^n + (4/3)*d*(4^n+2)-4)^n/2

by n*2^n + 2*c*2^n < c*(2^(n+1)+1) < 2^(n^2+2*n)*c <= d + 1
<= d*(d + 1 + (4/3)*d*(4^n+2)-4)^n/2

= d*(d*(4^(n+1)/3+11/3)-3)^n/2

by 4^(n+1)/3+11/3 < c
and 2^(n^2 + 2*n) = 2^(n^2)*4^n <= 2^(n^2)*n!*64/6
which gives d < c^n*64/6
< c^n*64/6 * (c^n*64/6 * c)^n/2
= c^(n^2+2n) * (32/3)^(n+1)/2

by (32/3)^(n+1)/2 < c^2
(for n=2 = 16384/27 < 607)
(for n=3 < 6475)
< c^(n^2+2n+2)
< c!

The APL formula for `c!`: !!×2*×⍨

```

### The code

```
⊢{z~∊(⊢,+)\⍺*⍨z←⍳!⍵}!×2*×⍨    Monadic train. ⍵←n
                    !×2*×⍨    c = n!*2^(n^2)
⊢{                 }          Pass to a dyadic dfn, ⍺←n, ⍵←above
              z←⍳!⍵   z ← 1..c!
           ⍺*⍨        Raise each to the power of n
    ∊(⊢,+)\           Compute all sums of distinct powers
  z~                  Remove them from z

```

# Answer
> 5 votes
# Ruby, ~~80 ... 72~~ 71 bytes

```
->n,*w{*r=0;a=1;1while w!=w|=[*(z=a**n)..(a+=1)**n]-r|=r.map{|y|y+z};w}

```

Try it online!

### Explanation:

The algorithm stops when no new numbers are found between `(x-1)^n` and `x^n`. When that range is covered, then by just adding `x^n` we can cover the range up to `2*x^n`. I assume that's enough to reach `(x+1)^n` (but alas, I can't prove it, sorry)

# Answer
> 4 votes
# Python 2, 97 bytes

```
n=input()
q=x=1
w=0
a=n**n<<n*n
while q<a**a:
 if w**n<q:w+=1;x|=x<<w**n
 if~x>>q&1:print q
 q+=1

```

Try it online!

Uses \\$\left(n^n2^{n^2}\right)^{n^n2^{n^2}}\\$ as an upper bound (Derived from Bubbler's upper bound with \\$n^n\ge n!\\$). Calculating this takes so much time that there won't be any output for \\$n\>4\\$ on TIO.

---

Here is an alternative approach that doesn't rely on an upper bound but rather terminates when no new number was found in \\$\left(w^n, (w+1)^n\right\]\\$ for some integer \\$w\\$. I'm not sure if this is valid, but the highest numbers from \\$n=2\\$ to \\$n=6\\$ (see below) match up with the paper linked in the challenge, and I think the Ruby answer works in a similar way.

```
def f(n):
 w=f=q=1;x=3
 while f:
  w+=1;x|=x<<w**n;f=0
  while w**n^q:f|=x>>q&1<1!=print(q);q+=1

```

Try it online!

Here is a more optimized version of the same algorithm that only prints the last integer: Try it online!

# Answer
> 2 votes
# Jelly, 19 bytes

```
²2*×!!ŒṗQƑƇfƑƇɗÐḟ²€

```

Try it online!

A monadic link taking an integer `n` as its argument and returning a list of integers. Implements @Bubbler’s method for determining the upper bound, so be sure to upvote that one too! While this answer would end in a finite time, it would be a very very long time even for n=2, and requires a huge amount of RAM (enough to generate integer partitions of \\$3072!\\$). I’ve therefore included a footer on TIO which demonstrates that the rest of the code works for integers up to 50.

# Answer
> 1 votes
# Python 3.8 (pre-release), 202 bytes, (Compact™)

```
g=lambda x:x<2or x*g(~-x);from itertools import*
def f(n,q=2):
 while q<g(g(n)*2**n**n):k=[x**n for x in range(1,q)];q not in[sum(h)for l in range(1,-~len(k))for h in combinations(k,l)]and print(q);q+=1

```

Try it online!

Hmph, the damn upper limit is too big. Won't work for \\$n\>2\\$ because of the big factorial calculation

-1 thanks to @cairdcoinheringaahing

# Python 3 (PyPy), 283 bytes, (Performance™)

```
g=lambda x:x<2or x*g(~-x);from itertools import*
def f(n,q=2):
 c=g(n)*2**n**2;d=2**(n*n+2*n)*c**~-n-1
 while q<d*2**~-n*(c*2**n+.6*d*~-4**n+2*d-2)**n+c*d:k=[x**n for x in range(1,-~int(q**(1/n)))];q not in[sum(h)for l in range(1,-~len(k))for h in combinations(k,l)]and print(q);q+=1

```

Try it online!

Probably terminates more than billion times faster compared to the above version.

Optimizations:

* Uses the full formula to calculate the upper bound from A001661, the generated upperbound is still big, but not as big as one by the Compact version
* To check if number can be represented in nth powers of 1 or more integers, previous version checks in the range of 1 to the number, but this checks until the nth root of the number, which speeds up the check dramatically.

It works for \\$n\>2\\$ too!

---
Tags: code-golf, sequence, integer-partitions
---


title: Custom Rows of Smileys Triangle

text:
# Question
Title: Custom Rows of Smileys Triangle
This problem is inspired from shinh's problem.

Given an input of positive integer \\$n\\$, output a smiley triangle (see below) with \\$n\\$ rows.

## Detailed rules

* Can be either a function or a full program.
* Standard I/O rules applied.
    + **RULE CLARIFICATION: Output as exactly a string, rather than an array of strings whose item represent a line.**
* Standard loopholes are forbitten.
* This is code-golf. Shortest code wins.

# Valid output syntax

Assuming ASCII encoding. A smiley triangle with \\$n\\$ rows `triangle(n)`, where n\>=1, should be output. `<0xXX>` is a character with such codepoint, in hexadecimal.

```
triangle(n) = triangle(n) <0x0a> | triangle_(n)
triangle_(1) = <0x3a> spaces
triangle_(n) = triangle_(n-1) <0x0a> row(n) spaces
row(2) = <0x3a> <0x2d>
row(n) = row(n-1) <0x29>
spaces = <0x09> spaces | <0x20> spaces | *empty*

```

## Example outputs

If n is 1, then

```
:

```

If n is 2, then

```
:
:-

```

If n=5, then

```
:
:-
:-)
:-))
:-)))

```

# Answer
# Husk, ~~11~~ ~~10~~ ~~9~~ 8 bytes

*Edit: -1 byte simultaneously spotted by Razetime*

```
↑ḣ¡→":-)

```

Try it online!

```
    ":-)    # the string ":-)"
  ¡         # construct infinite list by repeatedly appending
   →        # last element of list so far;
 ḣ          # now make list of all prefixes,
↑           # and take number of elements equal to input

```
> 2 votes

# Answer
# Python 2, 41 bytes

```
s=':-'
exec"print s[:-1];s+=')';"*input()

```

Try it online!

**42 bytes**

```
s,c=':-'
exec"print s;s+=c;c=')';"*input()

```

Try it online!

**43 bytes**

```
s=':'
exec"print s;s+='-)'[s>':'];"*input()

```

Try it online!
> 10 votes

# Answer
# Jelly, 10 bytes

```
“:-)”ṁ«\)Y

```

Try it online!

```
        )     Map over (the range from 1 to) the input:
“:-)”ṁ        Mold ":-)" to the shape of the argument, cycling its contents.
      «\      Scan by minimum: replace anything to the right of ) with ).
         Y    Join on newlines.

```

Thanks to Jonathan Allan for salvaging my first attempt, `”)xⱮa⁾:-Y`, for another 10-byter:

# Jelly, 10 bytes

```
”)xa⁾:-ṁ)Y

```

Try it online!

```
        )     Map over (the range from 1 to) the input:
”)x           Repeat ")" by the argument.
   a⁾:-       Zipwith-vectorize logical AND with ":-":
              overwrite the first two characters with ":-".
       ṁ      Mold to the shape of the argument, trimming the extra "-" for 1.
         Y    Join on newlines.

```
> 9 votes

# Answer
# Excel, ~~37~~ 49 bytes

*+12 bytes to accommodate clarification that the output should be one string*

```
=CONCAT(LEFT(":-"&REPT(")",A1),SEQUENCE(A1))&"
")

```

This returns one string as opposed to the earlier version which returned multiple cells each containing a string. Due to the Excel string limit, this only works for n \<= 254.

Link to Spreadsheet

```
=LEFT(":-"&REPT(")",A1),SEQUENCE(A1))

```

Previous version that works for n \<= 32767.
> 7 votes

# Answer
# 05AB1E, 11 bytes

```
…:-).ÞI£Jη»

```

Try it online!

Or, for the same length:

```
')×„:-ì¨¨η»

```

Try it online!

```
…:-)         # string literal ":-)"
    .Þ       # cycle last character to create infinite list
      I£     # take the first input characters
        J    # join into a string
         η   # take all prefixes
          »  # join by newlines

')×          # repeat ")" input times
   „:-ì      # prepend ":-"
       ¨¨    # remove the last two characters
         η»  # join the prefixes by newlines

```
> 5 votes

# Answer
# Stax, 8 bytes

```
╞■¼╤╝<Ñ┬

```

Run and debug it

outputs with newlines.
> 5 votes

# Answer
# Haskell, 32 bytes

```
(`take`(":":iterate(++")")":-"))

```

Try it online!
> 4 votes

# Answer
# Japt, ~~11~~ 10 bytes

Outputs an array of lines.

```
õî":-"ú')U

```

Try it

```
õî":-"ú')U     :Implicit input of integer U
õ              :Range [1,U]
 î             :For each slice the following to that length
  ":-"         :  Literal string
      ú')U     :  Right padded with ")" to length U

```
> 3 votes

# Answer
# , 17 15 bytes

*-1 thanks to Jonah!*

```
[:]\$!.'('&':-'

```

Try it online!

Reshape `:-` with fill `(` to length `n`. `[:[\` return each prefix.
> 3 votes

# Answer
# K (oK), 37 bytes

```
{({(":-",(x-2)#")")[!x]}'!x+1)[1+!x]}

```

Try it online!

My first non trivial K answer, a lot of room for inprovement.
> 3 votes

# Answer
# Vyxal `j`, 9 bytes

```
⇩\)*‛:-p¦

```

Try it Online!

Wasif said I should post my 9-byter as my own answer, but I thought it was too similar to his, so I got rid of the map lambda and the slice, just because why not. :P

Explanation:

```
⇩          # x = input - 2
 \)*       # Push a 'x' long string of ')'
    ‛:-p   # Prepend the string ':-'
        ¦  # Prefixes
           # 'j' flag - Join top of stack on newlines and print

```
> 3 votes

# Answer
# Python 3, 52 bytes

```
lambda n:[print((':-'+')'*i)[:-1])for i in range(n)]

```

Try it online!

-1 byte thanks to Mohammad
> 2 votes

# Answer
# JavaScript, 37 bytes

```
f=n=>--n?f(n)+(s=n>1?s+')':`
:-`):':'

```

Try it online!
> 2 votes

# Answer
# Vyxal `jr`, 10 bytes

```
ƛ?\)*‛:-+Ẏ

```

Try it Online!

Thanks to @emanresuA for -2 bytes

# Vyxal `j`, 12 bytes

```
‛:-?⇩\)*+¦?Ẏ

```

Try it Online!
> 2 votes

# Answer
# APL(Dyalog Unicode), 20 bytes SBCS

```
{,\⍵⍴':-',')'⍴⍨|⍵-2}

```

Try it on APLgolf!

Monadic function

`{`...`}` monadic function, takes n on right

`⍵-2` n minus 2

`|` abs (No. of braces, call it x)

swap x with

`')'` brace for

dyadic reshape to get x braces

`,` concat with

`':-'` smiley head

`⍵⍴` take first n (monadic reshape)

`,\` prefixes (ravel scan)
> 2 votes

# Answer
# TI-Basic, ~~40~~ ~~35~~ 27 bytes

```
Input N
Disp ":
":-
For(I,2,N
Disp Ans
Ans+")
End

```

-5 bytes thanks to MarcMush

-8 bytes thanks to MarcMush
> 2 votes

# Answer
# PHP -F, 59 bytes

```
for(;$i<$argn;)echo$i++?":-".str_repeat(")",$i-2)."
":":
";

```

Try it online!

Straightforward stuff.. Probably golfable a bit more, I'll try other things later
> 1 votes

# Answer
# M4, 88 bytes

Just a port of the syntax in OP.

```
define(g,`ifelse($1,2,,`)g(decr($1))')')define(f,`ifelse($1,1,:,`f(decr($1))
:-g($1)')')

```

Try it online!

## Usage

`f(number here)`
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ＮθＧ↓→θ⁺:-×)θ

```

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

```
Ｎθ

```

Input `n`.

```
Ｇ↓→θ

```

Draw a triangle of size `n`.

```
⁺:-×)θ

```

Paint the triangle using a smiley with `n` chins.
> 1 votes

# Answer
# Python 2, 56 bytes

```
i=input()
o=':-'+')'*i
for x in range(1,i+1):print o[:x]

```

Try it online!

Without the leading newline

# Python 2, 54 bytes

```
i=input()
o=':-'+')'*i
for x in range(i+1):print o[:x]

```

Try it online!

Never going to be a winner. Just an alternative approach.

**55 bytes**

```
lambda x:'\n'.join((':-'+')'*x)[:x]for x in range(x+1))

```

Try it online!

Another alternative using a lambda, surprisingly longer than using `input()`. It's that `join()` that's expensive.
> 1 votes

# Answer
# Retina 0.8.2, 25 bytes

```
.+
$*)
^.
:
:.
:-
.
$`$&¶

```

Try it online! Explanation:

```
.+
$*)

```

Start with `n` chins.

```
^.
:

```

Change the first chin into eyes.

```
:.
:-

```

Change the second chin, if any, into a nose.

```
.
$`$&¶

```

Output all of the nontrivial prefixes.
> 1 votes

# Answer
# Ruby, ~~40~~ 38 bytes

```
->n{n.times{|i|puts":-#{?)*n}"[0..i]}}

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~37~~ 35 bytes

```
f x=($":-"++cycle")").take<$>[1..x]

```

Try it online!

* Thanks to @Unrelated String for saving 2!
> 1 votes

# Answer
# C (gcc), 63 bytes

```
f(x){x&&f(x-1)+g(x);}g(x){x&&g(x-1);putchar("\n:-)"[x<3?x:3]);}

```

Try it online!

* double recursion
> 1 votes

# Answer
# PowerShell Core, ~~43~~ ~~33~~ 28 bytes

```
':-'+')'*"$args"|% *ve @args

```

Try it online!

Saved 10 bytes thanks to mazzy!
Saved 5 bytes by:

* removing gratuitous parenthesis
* using `Remove` instead of `Substring`
* using splatting
> 1 votes

# Answer
# brainfuck, 57 bytes

This assumes the initial memory location contains *n* in binary (0x05 == 5). The TIO link allows a single ASCII character as input and converts it to binary.

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

```

Try it online!
> 1 votes

# Answer
# Java (JDK), 82 80 bytes

```
String a(int n){return(n>1?a(n-1):"")+(":-"+")".repeat(n)).substring(0,n)+"\n";}

```

Try it online!

Recursively append longer smileys. A different approach might be shorter...

-2 thanks to ceilingcat!
> 1 votes

# Answer
# Zsh, ~~53~~ ~~39~~ 37 bytes

```
a=:-;for n ({1..$1})a+=\)&&<<<$a[1,n]

```

Try it online! ~~39 bytes~~ ~~53 bytes~~

Realised I was wasting bytes by doing 2 loops when one would suffice.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~109~~ 95 bytes

```
 n =input
b s =gt(n,1) char(10) ':-' dupl(')',n - 2) s :f(c)
 n =n - 1 :(b)
c output =':' s
end

```

Try it online!
> 1 votes

# Answer
# C (gcc), 68 bytes

```
i;f(n){char*s=calloc(n,4);for(s[i=0]=58;n--;s[i]=i++?41:45)puts(s);}

```

Try it online!
> 0 votes

# Answer
# Wolfram Mathematica, 67 bytes

```
Column@With[{n=#},":-"<>")"~StringRepeat~n~StringTake~#&/@Range@n]&

```

Try it online!

For some reasons unbeknownst to me, TIO doesn't display the list in column form. But if you run it in Mathematica, it will generate the desired result.

Explanation:

```
s=":-"<>StringRepeat[")",n]   (* generates the main string *)
StringTake[s,#]& /@ Range[n]  (* a list of substrings up to length n *)

```
> 0 votes

# Answer
# PHP `-F`, 86 bytes

Without any predefined funcation!

```
for($n=0;$n<$argn;$n++){echo':';for($i=1;$i<=$n;$i++){echo$i>1?')':'-';}echo PHP_EOL;}

```

Try it online!

Thanks.
> 0 votes

# Answer
# Perl 5, 40 bytes

```
sub f{map{substr':-'.')'x99,0,$_}1..pop}

```

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Simplify a square root

text:
# Question
Title: Simplify a square root
Given a positive integer `n`, simplify the square root `√n` into the form `a√b` by extracting all square factors. The outputted `a,b` should be positive integers with `n = a^2 * b` with `b` as small as possible.

You may output `a` and `b` in either order in any reasonable format. You may not omit outputs of `1` as implicit.

The outputs for `n=1..36` as `(a,b)`:

```
1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)

```

These are OEIS A000188 and A007913.

Related: A more complex version.

```
var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Jelly, 9 bytes

```
ÆE;0d2ZÆẸ

```

Try it online! or verify all test cases.

### How it works

```
ÆE;0d2ZÆẸ  Main link. Argument: n

ÆE         Exponents; generate the exponents of n's prime factorization.
  ;0       Append 0 since 1ÆE returns [].
    d2     Divmod by 2.
      Z    Zip/transpose to group quotients and remainders.
       ÆẸ  Unexponent; turn the exponents of prime factorizations into integers.

```
> 13 votes

# Answer
# Jelly, 6 bytes

```
²×¥þœi

```

Try It Online!

TFW you outgolf Dennis by 33% :P

Outputs `[b, a]`.

This does not use any prime factorization built-ins. Instead, it uses an array-oriented built-in `œi` (multi-dimensional index of), which is interestingly not found in any of APL/J/K/BQN.

### How it works

```
²×¥þœi    Monadic link. Input: the positive integer n.
²×¥þ      Compute the table of (x^2 * y) for both x and y in 1..n
          For n = 3, this returns:
          × | 1  4  9
          --+--------
          1 | 1  4  9
          2 | 2  8 18
          3 | 3 12 27
    œi    Find the multi-dimensional index of n in the matrix above
          [3, 1]

```

Since it finds the first occurrence in the matrix, `b` (first index) is guaranteed to be minimized, and `n` always appears at least once in the matrix at the coordinates `[n, 1]`.
> 13 votes

# Answer
# Python 2, 43 bytes

```
k=n=input()
while n%k**2:k-=1
print k,n/k/k

```

Test it on Ideone.
> 12 votes

# Answer
## PARI/GP, 12 bytes

```
n->core(n,1)

```

`core` returns the squarefree part of `n` by default, but setting the second argument flag to 1 makes it return both parts. Output order is `(b, a)`, e.g. `(n->core(n,1))(12) -> [3, 2]`.
> 12 votes

# Answer
# MATL, 12 bytes

```
t:U\~f0)GyU/

```

**Try it online!**

### Explanation

```
t     % Take input n implicitly. Duplicate
:U    % Push [1 4 9 ... n^2]
\~    % True for entries that divide the input
f0)   % Get (1-based) index of the last (i.e. largest) dividing number
G     % Push input again
y     % Duplicate index of largest dividing number
U     % Square to recover largest dividing number
/     % Divide input by that. Implicitly display stack

```
> 6 votes

# Answer
# Julia, 32 bytes

```
\(n,k=n)=n%k^2>0?n\~-k:[k,n/k^2]

```

Try it online!
> 4 votes

# Answer
# Mathematica 34 bytes

```
#/.{a_ b_^_:>{a, b},_[b_,_]:>{1,b}}&

```

This says to replace all the input (`#`) according to the following rules: (1) a number, **a**, times the square root of **b** should be replaced by `{a, b}` and a function b to the power of whatever should be replaced by {1,b} . Note that the function assumes that the input will be of the form, `Sqrt[n]`. It will not work with other sorts of input.

This unnamed function is unusually cryptic for Mathematica. It can be clarified somewhat by showing its full form, followed by replacements of the original shorter forms.

```
Function[
   ReplaceAll[
      Slot[1],
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]]

```

which is the same as

```
   ReplaceAll[
      #,
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]&

```

and

```
ReplaceAll[#,
  List[RuleDelayed[
    Times[Pattern[a, Blank[]],
     Power[Pattern[b, Blank[]], Blank[]]], {a, b}],
   RuleDelayed[Blank[][Pattern[b, Blank[]], Blank[]], {1, b}]]] &

```

and

```
ReplaceAll[#,
  List[RuleDelayed[Times[a_, Power[b_, _]], {a, b}],
   RuleDelayed[Blank[][b_, _], {1, b}]]] &

```

and

```
ReplaceAll[#, {RuleDelayed[a_*b^_, {a, b}], RuleDelayed[_[b_, _], {1, b}]}]&

```

and

```
ReplaceAll[#, {a_*b^_ :> {a, b}, _[b_, _] :> {1, b}}] &

```
> 2 votes

# Answer
## 05AB1E, 14 bytes

```
Lv¹ynÖi¹yn/y‚ï

```

**Explained**

```
Lv              # for each x in range(1,N) inclusive
  ¹ynÖi         # if N % x^2 == 0
       ¹yn/y‚ï  # create [N/x^2,x] pairs, N=12 -> [12,1] [3,2]
                # implicitly output last found pair

```

Try it online
> 2 votes

# Answer
# Python, 74 Bytes

```
def e(k):a=filter(lambda x:k/x**2*x*x==k,range(k,0,-1))[0];return a,k/a**2

```

Straightforward enough.
> 2 votes

# Answer
# Pyth, 15 bytes

```
/Q^
ef!%Q^T2SQ2

```

Test suite.
> 1 votes

# Answer
## Matlab, 51 bytes

```
x=input('');y=1:x;z=y(~rem(x,y.^2));a=z(end)
x/a^2

```

**Explanation**

```
x=input('')       -- takes input
y=1:x             -- numbers from 1 to x
z=y(~rem(x,y.^2)) -- numbers such that their squares divide x
a=z(end)          -- biggest such number (first part of output)
x/a^2             -- remaining part

```
> 1 votes

# Answer
# JavaScript (ECMAScript 2016), 40 bytes

```
n=>{for(k=n;n%k**2;k--);return[k,n/k/k]}

```

Basically a JavaScript port of Dennis's Python 2 answer.

Try it on JSBin.

Note: it doesn't work in strict mode, because `k` is not initialized anywhere. To make it work in strict mode, `k=n` in the loop should be changed to `let k=n`.
> 1 votes

# Answer
# Haskell, ~~43\>~~ 42 bytes

Brute force solution.

Saved 1 byte thanks to Xnor

```
f n=[(x,y)|y<-[1..],x<-[1..n],x*x*y==n]!!0

```
> 1 votes

# Answer
## APL, 25 chars

```
 {(⊢,⍵÷×⍨)1+⍵-0⍳⍨⌽⍵|⍨×⍨⍳⍵}

```

In English:

* `0⍳⍨⌽⍵|⍨×⍨⍳⍵`: index of the largest of the squares up to n that divides completely n;
* `1+⍵-`: the index is in the reversed array, so adjust the index
* `(⊢,⍵÷×⍨)`: produce the result: the index itself (a) and the quotient b (that is, n÷a\*a)

Test:

```
     ↑{(⊢,⍵÷×⍨)⊃z/⍨0=⍵|⍨×⍨z←⌽⍳⍵}¨⍳36
1  1
1  2
1  3
2  1
1  5
1  6
1  7
2  2
3  1
1 10
1 11
2  3
1 13
1 14
1 15
4  1
1 17
3  2
1 19
2  5
1 21
1 22
1 23
2  6
5  1
1 26
3  3
2  7
1 29
1 30
1 31
4  2
1 33
1 34
1 35
6  1

```
> 1 votes

# Answer
# JavaScript (ECMAScript 6), 35 bytes

```
f=(n,k=n)=>n/k%k?f(n,--k):[k,n/k/k]

```

# JavaScript 1+, 37 B

```
for(k=n=prompt();n/k%k;--k);[k,n/k/k]

```
> 1 votes

# Answer
# , 19 bytes

```
(0|:0 2#:])&.(_&q:)

```

Try it online!

Same as the Jelly solution.
> 1 votes

# Answer
# Vyxal, 9 bytes

```
K'∆²;t₍/√

```

Try it Online!

Very cool and good. Outputs as `[constant, surd]`

## Explained

```
K'∆²;t₍√/
K        # from the factors of the input,
 '∆²;    # keep only square numbers
     t   # and keep the last.
      ₍√/ # Push [sqrt(^), input / ^]

```
> 1 votes

# Answer
**Python 2.7 (ungolfed) - 181 Bytes**

```
def e(n):
 for x in range(1,n+1):
  r=(1,x)
  for i in range(1,x+1):
   l=i**.5
   for j in range(1,x+1):
    if i*j==x and l%1==0 and j<r[1]:r=(int(l),j)
  print x,r

```

Run as: e(number) eg. e(24)

Sample output:

```
>> e(24)
1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)

```
> 0 votes

---
Tags: code-golf, math, arithmetic
---


title: Snap (card game)

text:
# Question
Title: Snap (card game)
When I was a child I used to play a variation of Snap to stake soccer trading cards.
"Game" is an overstatement because the only role of the players is to secretly prepare their starting piles. As the game starts there are no choices other than just perform the game algorithm.

## Rules

There is no maximum number of players and they all start with a fixed number of cards.
Players in turn play the top card of their piles on a common pile (initially empty).

***If the current player has no cards***, the common pile bottom card will be played.

***When a player happens to play an equal card to that on top of the common pile***:

* This player will take the common pile and append it face-down to his own pile. (Players' piles are face-down but the common pile is face-up, so the pair of equal cards should end up at the bottom)
* Anyone with no cards is out of the game.
* This player has to resume the game replenish the common pile with their top card as usual.

***The game ends*** in one of three scenarios:

* one player has all the cards (they win)
* all the cards are in the common pile, the next player rotates it but doesn't form a pair (the common pile can't be taken)
* one previous state of the game reoccurs (the game gets stuck in a loop)

## Step by step game examples

```
1) Initial configuration: "abba abca"

     p1      p2      common pile

 1   abba    abca
 2   bba     abca    a
 3   bba     bca     aa
 4           TAKES
 5   bba     bcaaa
 6   bba     caaa    b
 7   ba      caaa    bb
 8   TAKES
 9   babb    caaa
10   abb     caaa    b
11   abb     aaa     bc
12   bb      aaa     bca
13   bb      aa      bcaa
14           TAKES
15   bb      aabcaa
16   bb      abcaa   a
17   b       abcaa   ab
18   b       bcaa    aba
19           bcaa    abab
20           caa     ababb
21   OUT     TAKES
22           caaababb

============ p2 wins ============

2) Initial configuration: "abba acab"

      p1      p2      common pile

  1   abba    acab
  2   bba     acab    a
  3   bba     cab     aa
  4           TAKES
  5   bba     cabaa
  6   bba     abaa    c
  7   ba      abaa    cb
  8   ba      baa     cba
  9   a       baa     cbab
 10   a       aa      cbabb
 11           TAKES
 12   a       aacbabb
 13   a       acbabb  a
 14           acbabb  aa
 15   TAKES
 16   aa      acbabb
 17   a       acbabb  a
 18   a       cbabb   aa
 19           TAKES
 20   a       cbabbaa
 21   a       babbaa  c
 22           babbaa  ca
 23           abbaa   cab
 24           abbaa   abc
 25           bbaa    abca
 26           bbaa    bcaa
 27   TAKES
 28   bcaa    bbaa
 29   caa     bbaa    b
 30   caa     baa     bb
 31           TAKES
 32   caa     baabb
 33   caa     aabb    b
 34   aa      aabb    bc
 35   aa      abb     bca
 36   a       abb     bcaa
 37   TAKES
 38   abcaa   abb
 39   bcaa    abb     a
 40   bcaa    bb      aa
 41           TAKES
 42   bcaa    bbaa
 43   bcaa    baa     b
 44   caa     baa     bb
 45   TAKES
 46   caabb   baa
 47   aabb    baa     c
 48   aabb    aa      cb
 49   abb     aa      cba
 50   abb     a       cbaa
 51           TAKES
 52   abb     acbaa
 53   abb     cbaa    a
 54   bb      cbaa    aa
 55   TAKES
 56   bbaa    cbaa
 57   baa     cbaa    b
 58   baa     baa     bc
 59   aa      baa     bcb
 60   aa      aa      bcbb
 61           TAKES
 62   aa      aabcbb
 63   aa      abcbb   a
 64   a       abcbb   aa
 65   TAKES
 66   aaa     abcbb
 67   aa      abcbb   a
 68   aa      bcbb    aa
 69           TAKES
 70   aa      bcbbaa
 71   aa      cbbaa   b
 72   a       cbbaa   ba
 73   a       bbaa    bac
 74           bbaa    baca
 75           baa     bacab
 76           baa     acabb
 77   TAKES
 78   acabb   baa
 79   cabb    baa     a
 80   cabb    aa      ab
 81   abb     aa      abc
 82   abb     a       abca
 83   bb      a       abcaa
 84   TAKES
 85   bbabcaa a
 86   babcaa  a       b
 87   babcaa          ba
 88   abcaa           bab
 89   abcaa           abb
 90           TAKES
 91   abcaa   abb
 92   abcaa   bb      a
 93   bcaa    bb      aa
 94   TAKES
 95   bcaaaa  bb
 96   caaaa   bb      b
 97   caaaa   b       bb
 98           TAKES
 99   caaaa   bbb
100   caaaa   bb      b
101   aaaa    bb      bc
102   aaaa    b       bcb
103   aaa     b       bcba
104   aaa             bcbab
105   aa              bcbaba
106   aa              cbabab
107   a               cbababa
108   a               bababac
109                   bababaca
110                   ababacab // common pile can't be taken

============ p1, p2 in game ============

3) Initial configuration: "bdad acbc abba"

     p1          p2          p3          common pile

 1   bdad        acbc        abba
 2   dad         acbc        abba        b
 3   dad         cbc         abba        ba
 4   dad         cbc         bba         baa
 5                           TAKES
 6   dad         cbc         bbabaa
 7   dad         cbc         babaa       b
 8   ad          cbc         babaa       bd
 9   ad          bc          babaa       bdc
10   ad          bc          abaa        bdcb
11   d           bc          abaa        bdcba
12   d           c           abaa        bdcbab
13   d           c           baa         bdcbaba
14               c           baa         bdcbabad
15                           baa         bdcbabadc
16                           aa          bdcbabadcb
17                           aa          dcbabadcbb
18   TAKES       OUT
19   dcbabadcbb              aa
20   cbabadcbb               aa          d
21   cbabadcbb               a           da
22   babadcbb                a           dac
23   babadcbb                            daca
24   abadcbb                             dacab
25   abadcbb                             acabd
26   badcbb                              acabda
27   badcbb                              cabdaa
28                           TAKES
29   badcbb                  cabdaa
30   badcbb                  abdaa       c
31   adcbb                   abdaa       cb
32   adcbb                   bdaa        cba
33   dcbb                    bdaa        cbaa
34   TAKES
35   dcbbcbaa                bdaa
36   cbbcbaa                 bdaa        d
37   cbbcbaa                 daa         db
38   bbcbaa                  daa         dbc
39   bbcbaa                  aa          dbcd
40   bcbaa                   aa          dbcdb
41   bcbaa                   a           dbcdba
42   cbaa                    a           dbcdbab
43   cbaa                                dbcdbaba
44   baa                                 dbcdbabac
45   baa                                 bcdbabacd
46   aa                                  bcdbabacdb
47   aa                                  cdbabacdbb
48                           TAKES
49   aa                      cdbabacdbb
50   aa                      dbabacdbb   c
51   a                       dbabacdbb   ca
52   a                       babacdbb    cad
53                           babacdbb    cada
54                           abacdbb     cadab
55                           abacdbb     adabc
56                           bacdbb      adabca
57                           bacdbb      dabcaa
58   TAKES
59   dabcaa                  bacdbb
60   abcaa                   bacdbb      d
61   abcaa                   acdbb       db
62   bcaa                    acdbb       dba
63   bcaa                    cdbb        dbaa
64                           TAKES
65   bcaa                    cdbbdbaa
66   bcaa                    dbbdbaa     c
67   caa                     dbbdbaa     cb
68   caa                     bbdbaa      cbd
69   aa                      bbdbaa      cbdc
70   aa                      bdbaa       cbdcb
71   a                       bdbaa       cbdcba
72   a                       dbaa        cbdcbab
73                           dbaa        cbdcbaba
74                           baa         cbdcbabad
75                           baa         bdcbabadc
76                           aa          bdcbabadcb
77                           aa          dcbabadcbb
78   TAKES
79   dcbabadcbb              aa                       // loop (line 19)

============ p1, p3 in game ============

```

**N.B.** game states are inviduated by piles configuration and current player. As you can see in example `2)` lines 28, 42 are not the same game state.

## Input

A list of players' piles (top to bottom) as:

* an array of strings `["code", "golf", "fold"]`, or
* a matrix of positive integers `[[1,2,3,4],[5,2,6,7],[7,2,6,3]]`

Players order is implied by piles order.

## Output

A number indicating the player who wins or a list of numbers for the players who reach the end of the game.
You decide whether players are 0 or 1 indexed.

## I/O Examples (1-indexed players):

```
"abca abba"      -> 1
"abba abca"      -> 2
"abba acab"      -> 1 2
"bdad acbc abba" -> 1 3
"fizz buzz"      -> 2
"robinhooda ndlittlejo hnwalkingt hroughthef orestlaugh ingbackand forthatwha ttheothero nehastosay" -> 9

```

# Answer
> 6 votes
# JavaScript (Node.js), ~~483~~ 426 bytes

*-57 bytes thanks to @emanresu A*

Takes a list of strings as input and indexes from 0.

Try it online!

```
a=>{a=a.map(p=>[...p]);e=[];t=[];o=[];i=0;g=a.length;m=n=>(n%g+g)%g;r=_=>[...a.keys()].filter(x=>!d(x));d=x=>o.includes(x);q=_=>JSON.stringify([o,i,a,e]);for(;;){if(!d(i)&&(l=e.length==e.unshift(a[i].shift(t.push(q()))||e.pop())&&!a.filter(p=>p[0])[0],(e[0]==e[1]&&e[1]&&(i=m(i-1,a[i].push(...e.reverse())),e=[],o.push(...a.flatMap((p,j)=>p[0]||d(j)?e:j))+1==g)||l)))return l?r():r()[0];if(t.includes(q(i=m(i+1))))return r()}}

```

**Unminified**

```
(a) => {
    a = a.map((p) => [...p]);
    e = [];
    t = [];
    o = [];
    i = 0;
    g = a.length;
    m = (n) => ((n % g) + g) % g;
    r = (_) => [...a.keys()].filter((x) => !d(x));
    d = (x) => o.includes(x);
    q = (_) => JSON.stringify([o, i, a, e]);
    for (;;) {
        if (
            !d(i) &&
            ((l = e.length == e.unshift(a[i].shift(t.push(q())) || e.pop()) && !a.filter((p) => p[0])[0]),
            (e[0] == e[1] && e[1] && ((i = m(i - 1, a[i].push(...e.reverse()))), (e = []), o.push(...a.flatMap((p, j) => (p[0] || d(j) ? e : j))) + 1 == g)) || l)
        )
            return l ? r() : r()[0];
        if (t.includes(q((i = m(i + 1))))) return r();
    }
};

```

# Answer
> 4 votes
# Python 3.8 (pre-release), 378 bytes

```
def f(s,p='',G=[],V=sorted,E=enumerate):
 O=V(p.join(s))
 while 1:
  for i,S in E(s):
   if S:p+=S[0];s[i]=S[1:]
   elif""==S:p=p[1:]+p[0]
   if s[i]!=0<1<len(p)!=p[-2]==p[-1]:s[i]+=p;s=[P or 0for P in s];p=s[i][0];s[i]=s[i][1:]
   C=s+[p,i]
   if any(a and O==V(a)for a in s)or(O==V(p)*all(a!=b for a,b in zip(p,p[1:]+p[0])))or C in G:return[i for i,S in E(s)if S!=0]
   G+=[C]

```

Try it online!

Wow, was this a pain to write.

Takes in a list of strings, outputs a list of 0-indexed numbers. My code can be slightly changed to output a single value if a single player wins, but I see no rule preventing me from outputting as my code does.

## Explanation

Stores game states in `G`. A *state* here is the list of strings followed by the pile and the number indicating whose turn it is (evidently, whose turn it is does make a difference). If the current state has been seen before, we break by setting T to 1. (breaks from the inner loop then from the outer loop)

For each iteration, if S is truthy (current string) we append its first letter to the pile and remove it from `s[i]`. If `S` is empty string, we rotate the pile.

A zero indicates that the player is out; we ignore such cases. If the last two characters of `p` are the same, we append the entire pile to the end of `s[i]` and reset it, before resuming the game in the same iteration.

The two other checks for the endgame are:

* if any of the sorted strings in `s` match the sorted `O`, or
* if the sorted pile equals sorted `O` and there are no neighboring pairs in the pile (end and beginning count as a pair).

To get the list of "in" players, we simply output all indices corresponding to a nonzero entry in `s`.

Any tips for shortening the code will be greatly appreciated. Thanks to @ovs for ~~-28~~ -35 bytes!

# Answer
> 3 votes
# Perl 5, 209 bytes

```
sub{(@p,$i,$_,%s,@o)=pop=~/\w+/g;while((@w=grep$p[$_-1],1..@p)>1||y///c and!$s{$i,@p,@o}++){if(!$o[$i]&&($p[$i]=~s,.,,||s,.,,)&&($_.=$&)=~s/.*(.)\1$//){$p[$i].=$&;$p[$_]or$o[$_]=1for 0..$#p;next}$i=++$i%@p}@w}

```

Try it online!

---
Tags: code-golf, string, card-games
---


# Question
Title: 2016 Time Capsule String: How Versatile Is Your Language?
About a year ago on Dec 31, 2015, I had the idea that:

> We should make a time capsule string. Everybody gets to add one character and next new years we'll see who can make the best program out of all the characters with the esolangs that exist then.

Doorknob graciously collected characters from the PPCG community and kept them safe for a year.

A whopping *74 people* participated so we have a spiffing *74* printable-ASCII characters to play with!

Here are the 74 characters of the 2016 time capsule string in the order they were submitted:

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

Here are the 74 characters of the 2016 time capsule string in ASCII order (note leading space):

 !!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~
</code></pre>

It's not a whole lot to work with, but round here we like a challenge.

# The Challenge

To determine what language is "best" with the time capsule string we'll have 6 (for 201**6**) challenges that increase in difficulty where in each you must use a subset of the 74 time capsule characters.

Having 6 distinct challenges helps ensure more languages can compete, but only the best languages will be able to answer all of them and score high.

**Scoring:**

* Each challenge will be scored from 0 to 74 depending on how many characters are used.
* Higher scores are better.
* If your language cannot complete a challenge, your score for that challenge is 0.
* Any nonempty subset of the challenges may be completed.
* Your final score is the sum of scores from all 6 challenges.
* **The best final score possible is 6×74 or 444**.

# The Challenges

## 1. Run

If a language's code can't run in the first place it won't be able to do anything at all.

Write the longest full program possible (using only the 74 time capsule characters, remember) that runs/executes without compile-time or runtime errors.

It doesn't matter what the program does, it doesn't matter if it has input/output or enters an infinite loop, it only matters that it runs without errors. (Warnings are ok, as are errors caused by bad user input.)

Comments are allowed, so this could be as simple as

```
#H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

in Python for a score of 74.

(Don't be afraid to answer if this is the only challenge your language can complete, but don't expect lots of votes either.)

**Score = program length** (longer program is better)

## 2. I/O

A language that has no form of input or output is almost as useless as one that can't run.

Given a printable ASCII character from `!` (0x33) to `}` (0x7D) inclusive, output the printable ASCII character before and after it.

The output can be a length two string or list, or the characters separated by a space or newline.

For example if the input is `}` the output might be `|~` or `["|", "~"]` or `| ~` or `|\n~`.

Likewise,  `"` is the output for `!` and `AC` is the output for `B`.

**Score = 74 - program length** (shorter program is better)

## 3. Branchability

Conditionals are often a requirement for Turing completeness, which is often a requirement for a language being useful.

Given a positive integer, if it ends in the decimal digits `16` then change the `6` to a `7` and output the result; otherwise, output the input unchanged. You may use strings for input/output if preferred.

Examples:

```
2016 -> 2017
16 -> 17
116 -> 117
1616 -> 1617
6 -> 6
15 -> 15
17 -> 17
106 -> 106
2106 -> 2106

```

**Score = 74 - program length** (shorter program is better)

## 4. Loopability

A language that can't do loops will spawn repetitive code so tedious you'll need to take a programming break for a while.

Given a positive integer, output an ASCII-art square of that side length filled with a pattern of concentric smaller squares that alternates between any two distinct printable ASCII characters. They don't have to be the same two characters for different inputs.

For example:

```
1    <- input
X    <- output

2
XX
XX

3
XXX
X-X
XXX

4
XXXX
X--X
X--X
XXXX

5
YYYYY
Y...Y
Y.Y.Y
Y...Y
YYYYY

6
XXXXXX
X----X
X-XX-X
X-XX-X
X----X
XXXXXX

7
ZZZZZZZ
Z-----Z
Z-ZZZ-Z
Z-Z-Z-Z
Z-ZZZ-Z
Z-----Z
ZZZZZZZ

```

**Score = 74 - program length** (shorter program is better)

## 5. Math

A language that's not good with numbers and math may as well be for humanities majors.

Take no input but output the 72 integer divisors of 2016, positive and negative, in any order. The output can be formatted as a string or list in a reasonable way.

Example:

```
-1, -2, -3, -4, -6, -7, -8, -9, -12, -14, -16, -18, -21, -24, -28, -32, -36, -42, -48, -56, -63, -72, -84, -96, -112, -126, -144, -168, -224, -252, -288, -336, -504, -672, -1008, -2016, 1, 2, 3, 4, 6, 7, 8, 9, 12, 14, 16, 18, 21, 24, 28, 32, 36, 42, 48, 56, 63, 72, 84, 96, 112, 126, 144, 168, 224, 252, 288, 336, 504, 672, 1008, 2016

```

**Score = 74 - program length** (shorter program is better)

## 6. Esotericism

(No, not that.) We at PPCG like our esoteric stuff, and quines are a good example of that.

Write the longest quine you can, according to usual quine rules. A quine is a program that takes no input and outputs itself.

**Score = program length** (longer program is better)

# Specific Rules

* In each of the 6 challenges ***your program must be a subset of the 74 time capsule characters*** rearranged any way you like. It may be an empty subset or an improper subset, so each of your programs could have as few as 0 and as many as 74 characters.
* A single trailing newline at the end of input/output/code is alright anywhere since some languages require this or it cannot be easily avoided.
* Unless otherwise specified, each challenge may be completed as a function or full program according to our defaults.
* All challenges must be completed in the same language.
* You must use a language (or version of a language) made before it was 2017 anywhere on Earth.
* Anyone is welcome to answer, whether you added a character to the time capsule or not.

<sub>Feel free to use the 2016 time capsule characters in your own challenges.</sub>

# Answer
> 38 votes
## Glypho, 74 + (74 - 36) = 112

### 1. Run (74 bytes)

<pre><code>!!#%QTQT@=A@$!!$)()*!&))+...1449:@HILOQZ\\^`````````eefmpx|||{~~~~~~y~|~ ~

### 2. IO (36 bytes)

```
!!!#!$!$4419TAHT\ee\OQQQ))*+)..)|~~~

```

### Explanation

Glypho seemed like a fairly good choice for this challenge, because it doesn't care about the actual characters being used. Instead, it looks at groups of four characters and chooses the command based on the pattern of repetition in those four characters. Since there are a lot of duplicates among the time capsule string, we're fairly flexible in the programs we can write, except that we're limited to programs of 18 commands (which isn't a whole lot in Glypho). While this allowed me to solve the first two problems quite easily, I doubt that Glypho can run the others with so few characters.

I've tested these using the Java interpreter retrieved from 2006-06-23 on the wayback machine, which uses a slightly different mapping of the commands:

```
0000 n
0001 i
0010 >
0011 \
0012 1
0100 <
0101 d
0102 [
0110 +
0111 o
0112 *
0120 -
0121 ]
0122 !
0123 e

```

The **Run** program translates to:

```
1d-+[...]

```

Where `...` is some junk that I didn't bother translating.

```
1      Push 1.
d      Duplicate.
-      Turn into -1.
+      Add. Gives 0.
[...]  Skip the rest because the top of the stack is zero.

```

The **IO** program translates to:

```
id1-+o1+o

```

Here is what this does:

```
i   Read a character.
d   Duplicate.
1   Push 1.
-   Turn into -1.
+   Add to character, i.e. decrement it.
o   Output it.
1   Push another 1.
+   Add to character, i.e. increment it.
o   Output it.

```

# Answer
> 24 votes
# CJam, 74 + (74 − 14) + (74 − 26) = 182 score

## 1. Run (74 bytes)

e# !!!!!$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````efmpxy{||||~~~~~~~~~
</code></pre>

Moving `e#` to the front comments out the entire line.

## 2. I/O (14 bytes)

```
9`)ZH*+~):Q(Q)

```

Dennis saved 8 bytes.

Explanation:

```
9`                   Push "9".
  )                  Extract character '9'.
   ZH*               Push 3 * 17 = 51.
      +              Add to get character 'l'.
       ~             Eval as CJam code. Command l reads a line.
        )            Extract the only character from the input line
         :Q(         Assign to Q and decrement
            Q)       Push Q and increment

```

## 3. Branchability (26 bytes)

```
4`)4Z|`I!`|~^~~T$AT$*%H(=+

```

Explanation:

```
4`)                            Push character '4'
   4Z|`                        Push 4 | 3 = 7, stringify
       I!`                     Push !18 = 0, stringify
          |~                   Setwise or and eval to get 70
            ^                  XOR to get 'r'
             ~                 Eval to read input
              ~                Eval the input as CJam code to turn
                               it into an integer
               T$              Duplicate it
                 A             Push 10
                  T$*          Duplicate that and multiply → 100
                     %         Mod the copy by 100
                      H(=      Compare to 17 - 1 = 16
                         +     Add the result (1 or 0) to the original

```

I’ll look at the others later. (**EDIT**: I doubt they’re possible, without block or string literals… maybe the math one?)

# Answer
> 11 votes
# J, score 71 + (74 - 19) = 126

## Task 1, length 71

```
AHILO=:( |T`T`Z`e`e`f`m`p`x`y|.~~%~@{|~^|Q@Q@Q+.*.449!~!~!~!!#$$&1\\~~)

```

This defines a verb `AHILO` to be the inside. Unused:

```
)))

```

I don't think there's any way to get longer than this.

## Task 3, length 19

```
+($#~$~4)=1e4|&%:*~

```

The way to do this task with no restrictions is `+16=100|]`, which reads as follows:

```
        ]  Input
    100|   mod 100
 16=       equals 16? (Evaluates to 1 or 0)
+          Add to input.

```

We have `+`, `=` and several copies or `|` in our disposal, and it's easy to get around `]`, but the numbers are more problematic. Here's the first part that computes input modulo 100:

```
1e4|&%:*~
       *~  Input squared (multiplied with itself).
1e4        The number 10000.
   |       Perform modulo
    &      on
     %:    their square roots.

```

After we're done with that, let's produce the number 16. The easy way is with `*~4` (4 multiplied with itself), but we already used `*` so that's forbidden. Instead, we'll do some array manipulation.

```
($#~$~4)
    $~4   Reshape 4 to shape 4, resulting in the array 4 4 4 4.
  #~      Replicate wrt itself: replace each 4 by four 4s.
 $        Take length.

```

## Work

### 2

This is most definitely impossible. The only ways to manipulate character values are `a.` and `u:`, and we have access to neither.

Now, if we could use `a` instead of, say, `A`, then this would be a solution:

```
Q{~(*^.4%9 1)+I.~&Q=:a.

```

The hardest part to getting this to work was producing the number -1.

```
Q{~(*^.4%9 1)+I.~&Q=:a.
                     a.  The array of all bytes.
                  Q=:    Bind it to Q
              I.~&       and find the input's index in it.
   (        )+           Add the following array:
    *                    Signum of
     ^.                  logarithm of
       4%                4 divided by
         9 1             the array 9 1.
                         This evaluates to -1 1.
Q{~                      Index back into Q.

```

### 4

```
(*.1:"|~@+.)

```

This generates the shape of the husk, but I can't seem to find a way to generate characters. Alas.

### 5

Admittedly, this seems like the easiest of the tasks to do in J. However, without `i.`, this will be quite hard.

### 6

This is likely impossible without a fake-out quine like `449` or something like that, because the capsule string doesn't contain quotes or any other way of producing J strings.

# Answer
> 8 votes
# PowerShell \- Total Score: 74

## 1. Run - Score: 74

```
#~= `TeQ.)`~H|$QL4yA)\*`!^O$1)!Z`!`~|\`&T@!x+e(f|Q`.|!4%.{~`:~~)m@~`@p~I9~

```

---

Since this is extremely difficult in PowerShell (every possible method of obtaining input is impossible with the characters given, as far as I can tell), I've at least decided to randomize the first challenge so we're not all copying the example directly from the post.

So here's a random challenge 1 answer generator (for languages where `#` is a comment):

<pre><code>'#'+$(-join([char[]]' !!!!!$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~'|Get-Random -Count 73))

# Try it online!

# Answer
> 8 votes
# Brainfuck, 74 bytes

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

I just had to.

# Explanation:

Any character that is not a valid Brainfuck character is treated as a comment. The only code that actually gets run is this:

```
.+..

```

This produces no printable output, since neither 0 nor 1 are printable characters in ASCII. However, it does not cause an error, so we successfully complete the first challenge.

# Answer
> 8 votes
## memes, score of (~~62~~ 65 + 70) 135

**1: Run**

I removed all backticks (```) and mathematical operators. They conflicted because there weren't enough numbers to satisfy every unary and binary operator. *I left some in, resulting in +3 bytes*. Resulting program:

```
 !!!!!#$$%&())))...+1^4*49:=@@@AHILOQQQTTZ\\eefmpxy{||||~~~~~~~~~

```

I have no idea why and how this worked. Atleast it doesn't throw any C# runtime exception, and doesn't therefore crash.

**6: Quine**

~~You know, if there would've been an `-` or lowercase `q` somewhere in those 74 characters, this would be way too easy. I'm glad for the `I` operator, atleast.<br>```
1/4I

```
This code isn't exactly obvious. Here's an explanation:<br>```
1    Set object to 1 (1)
/4   Divide by 4     (0.25)
I    Set object to a fraction string. (1/4)

```~~

~~Fraction strings (e.g. `1/4`) are displayed with an I at the end, to indicate exactly that. The `I` operator is usually useless, I added it for other means, but hey, it works like this!~~

Above code is invalid. Stupid me didn't see that the 74 characters don't contain a single division operator, forwardslash (`/`). I came up with something else though:

```
True

```

Explanation:

```
T    Set object to "true" (bool value)
rue  None of these are valid tokens, so they don't get interpreted.

```

Outputs `True` (because of how the way C# handles `Boolean.ToString()` uppercase and not lowercase). Not sure if this is a proper quine, meanwhile I'm still cracking my head for a valid, really proper, and intuitive one.

Could maybe also solve I/O and Math challenge, but I'm missing specific tokens (characters) which aren't included in the 74 characters.

# Answer
> 7 votes
# Mathematica, score of 62

I'd be surprised if anyone can make challenges 2-6 work in Mathematica. Here's the best I did with challenge 1:

```
A:=1.`!#&@(4`+4.`*9.`^$$H~I~L~O~Q~Q~Q~T~T||Z||e@@efmpxy%)!!!!

```

Defines a pretty stupid function `A` with a constant value. The 12 unused characters are:

<pre><code>)))\\`````{~

# Answer
> 6 votes
# Octave, score 74

### 1. Run

x =@(AHILOQQQTTZeefmpy)+.1||!!!!!~~~~~~~~~4.^.4||9%#$$)))*@@\`````````{\&:
</code></pre>

50 of these characters are part of the function, while the remaining 24 are not.

**What it does:**

`x =@(AHILOQQQTTZeefmpy)` creates a function `x` that can take a variable `AHILOQQQTTZeefmpy` as input.

**To understand the rest:**

`a||b` calls the function `all()` on both `a` and `b`. If one or both of those return true, the `||` operator will return true.

`!a` and `~a` means the same thing here, they are both `not(a)`.

`a.^b` is an element-wise power `(a(1)^b(1), a(2)^b(2) ...)`

**Continued explanation**

I'll shorten each of the steps as I go along:

```
4.^.4||9  % This is 4 raised to the power of .4||9
          % .4||9 is true, since both .4 and 9 are true
          % true is evaluated to 1 when used in an expression
...       % 4 raised to the power of 1 is simply 4.
4         % The above expression simplified

```

And:

```
!!!!!~~~~~~~~~4  % ! and ~ are the not() operator, so this is equivalent to:
not(not(not(not(not(not(not(not(not(not(not(not(not(not(4))))))))))))))

```

There is an even number of `not`, so this is equivalent to `not(not(4))` which is `true` or `1`.

```
+.1||1      % This is equivalent to all(+.1) | all(1), which returns true

```

The rest is commented out.

# Answer
> 6 votes
# \*\>\<\>, total score = 74

## 1. Run, score 74

```
f:4%*e+e14=p!Q H@~^)$.`~A|Q)~`\ZI~O.~@``#|9@)T\T`(!``|`~!y!`)Q~$x.|m~~&!L{

```

Try it here!

This was extremely hard to do without the `;` character. I actually thought it was going to be impossible for a couple moments, until I saw the `%`, I had basically given up.

This is also a valid \>\<\> program.

### Explained (irrelevant parts omitted)

```
f:4%*e+e14=p!Q

f:               copy 15
  4%             pop 15, push 15%4 (3)
    *            pop 15 and 3, push 15*3 (45)
     e+          pop 45, push 45+14 (59, ascii ";")
       e         push 14
        14=      push 0
           p     replace coord (14, 0) with ";"
            !Q   skip Q (this is just filler)
              ;  end execution

```

## Challenges faced

I might try the other challenges ... they'd be extremely hard and may involve bending the rules in weird ways but liberal use of the `|` mirrors and the `!` trampolines should make at least one more challenge possible.

These challenges are particularly hard because we're not allowed any outputs with \*\>\<\> (`o` and `n`), or even function calls (`C`), function returns (`R`), or program terminators (`;`). Even though we're also missing `i` for input, we can still have input placed on the stack which is a plus. Another plus is that we get a single `p` instruction, which allows us to replace an instruction in the codebox. This might be able to be used multiple times (haven't figured out a practical way yet), which would start to make the other programs seem more possible (as we'd be able to generate two or more instructions).

# Answer
> 5 votes
# Haskell, score 63

### 1. Run:

```
(!!!!!#$$%&*+...:@@@\\^||||~~~~~~~~~)fmpxyAHILOQQQTTZ e=14`e`49

```

Not used are `)))```````{`. Comments in Haskell are `--` or `{- ... -}`, so there is no easy all-comment version.

This code defines an infix operator `!!!!!#$$%&*+...:@@@\^||||~~~~~~~~~` which takes two arguments:

1. `fmpxyAHILOQQQTTZ` which is ignored and can therefore be of an arbitrary type
2. `e`, which must be a function taking two numbers

In the function body `e` is then applied to 14 and 49, using the ```-infix notation.

*Usage example:*

```
Prelude> () !!!!!#$$%&*+...:@@@\\^||||~~~~~~~~~ (*)
686

```

The operator is applied to `()`, the empty tuple, and `(*)`, the multiplication operator, so `14*49 = 686` is computed.

Try it online!

### Other challenges

I doubt that any of the other challenges are possible, most notably because of the lack of possible variable names that can appear twice, which is only `e` (or something like `eQT`), because variable names can't start with an uppercase letter. Of course, having only one `=` doesn't help either.

# Answer
> 5 votes
# Pyth, 131 for now (2 challenges complete)

## 1. Run, 74

# `````````!!!)!)!)*$AOeIefLmpxQ|Q|y|Q|~~~~~~~~~()${+%&\=@@@^\:.1.4.49TTZH
</code></pre>

This program takes no input and creates no output.

This program uses `$$`, which allows arbitrary code execution, and so is banned online, so this program online runs offline. Here's its compilation output, so you can see what actually gets run:

```
while True:
 try:
  (repr(repr(repr(repr(repr(repr(repr(repr(repr(Pnot(Pnot(Pnot()))))))))))))
  imp_print(Pnot())
  imp_print(Pnot())
  imp_print(times(AOeIefLmpxQ|Q|y|Q|~~~~~~~~~(),uniquify(plus(mod(("=" and lookup(lookup(lookup(Ppow(":",.1),.4),.49),T)),T),Z))))
  imp_print(H)
 except Exception:
  break

```

It's fairly tricky to write a program with arbitrary characters that doesn't error in Pyth. I set myself the additional challenge of requiring that the program run without requiring user input, as well.

The first step is to use `#` to eat all of the errors. Next, we need to avoid errors caused by `~`, `I` and `L`, which each have their own details. This is achieved by putting them inside the `$$`, which embeds them inside the output compilation, and thus subjects them to Python's compilation rules, not Pyth's. Finally, to avoid taking user input, the various arity 0 tokens (Variables and similar) are placed at the end, and the `Q`s are moved inside the `$$` block.

# 2. IO

This will be incredibly difficult, if it's even possible. None of the Pyth functions that create arbitrary strings or characters are present except `.f`, and that does a really poor job of creating arbitrary characters.

# 3. Branchability: 74 - 17 = 57

```
|&x%Q*TTye|LZ9Q+1

```

Try it online

An equivalent Pyth program would be:

```
?n%Q100 16Q+1

```

This code takes the input mod 100, compares it to 16, and then uses a ternary to choose between the input and the input plus one. Due to character restrictions, I made some substitutions:

* Instead of `?`, the ternary, I used `|&`, `or` then `and`, which has the same functionality, except that it breaks if the input is zero, but since we're guaranteed positive integer input, it's fine. (This could have been fixed for no additional characters, but it's simpler this way.)
* Instead of directly comparing the two numbers, I take their XOR with `x`, which is zero if and only if they're equal, as desired.
* Instead of writing `100` directly, I generate it with `*TT`, since `T` is initialized to `10`.
* Instead of writing `16` directly, I generate it with `ye|LZ9`. `|LZ` essentially functions as the range function, so `|LZ9` gives `[0, 1, 2, 3, 4, 5, 6, 7, 8]`. `e` takes the final element of a list, giving `8`. `y` doubles it, giving `16` as desired. With an extra `+` or an extra `*` I could save a character, but they're both more useful elsewhere.

More to come!

# Answer
> 3 votes
## Ruby - Score: 74

### 1. Run

```
#H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

Grabbed from the challenge.

# Answer
> 3 votes
## JavaScript (ES6), score = 74

### 1. Run, 74 bytes

```
Z=` !!!!!#$$%())))...1449:@@@\AHILOQQQTT^\`eefmpxy{||||~~~~~~~~~`*``+``&``

```

### 6. Esotericism (invalid)

For the record, my suggested quine was:

```
1.4e+49

```

which turned out to be invalid, as discussed in the comments below.

# Answer
> 3 votes
# Retina, score 74

### 1. Run, score 74

<pre><code>)))` !!!!!#$$%&()*.+..1449:=@@@AHILOQQQTTZ\\^````````eefmpxy{||||~~~~~~~~~
</code></pre>

I moved the extra parens to the config in order for them to balance in the regex. I also moved the ``` right after those, and changed `+.` to `.+`.

Try it online

The others are likely impossible, since there are no newlines. There's also no `-` for Transliteration or `d` for a digits character class.

# Answer
> 3 votes
# Pip, score 74 + (74 - 19) = 129

So many backticks with nary a quote to be seen, single or double!

### Task 1, score 74

```
`` `\``!!!!!`#$$%&())))*+...1449:=@@@ILOQQQTTZ\^efmpx{|||~~~~~~~~~`|`yeAH`

```

Basically just a series of pattern (regex) literals in backticks, the last of which is printed. Since there are an odd number of backticks, we have to backslash-escape one of them (``\```). Try it online, with the `-w` flag added to prove that no warnings are generated.

### Task 3, score 55 (length 19)

```
e+!!e%(1.#x.!9)=4*4

```

Using a rather odd input method--the fifth command-line argument--this is possible. Try it online!

```
                     e is 5th cmdline arg; x is empty string
       1.#x.!9       Concatenate 1, 0 (length of x), and 0 (not 9)
    e%(       )      e mod 100...
               =4*4  ... equals 16?
  !!                 Logically negate twice
e+                   Add to e (+1 if number mod 100 is 16, +0 otherwise)
                     Expression is autoprinted

```

### Other tasks

It's possible to get input for **task 2**, by the same method as task 3 above. The trouble is converting to ASCII code and back to a character. The former can be done with `A`, but the latter requires `C`, or possibly indexing into the `PA` variable. Constructing and evaluating code can't be done without `V`. I don't think the task is possible.

**Task 4** is challenging even without a restricted character set. At a guess, it would require lists (without using the `[]` delimiters or `RL` (repeat list) and only having one chance to use `AL` (append list)--not likely) or possibly something with `CG` (coordinate grid) or `MC` (map coords), both disallowed.

**Task 5** is on the edge of possibility. Loops would be difficult, since `F`or and `M`ap aren't possible, and ranges can't be constructed with `,`. There might be something to be done with `T`ill. Increment could be of the `x:x+1` variety (obviously with a variable other than `x`, though). Divisibility checks can use `%`. Still, I don't think there are enough characters--especially repeated letters--to do everything that needs to happen.

**Task 6** looks completely impossible. All known Pip quines have `"` in them. They also use `R` (replace), `RP` (repr), or `V` (eval), none of which are available.

# Answer
> 2 votes
# Actually, score (74 + *0* \+ *0* \+ *0* \+ *0* \+ *0*) = 74

Yes, the capsule string will work with Actually as it is for Run, as Actually dismisses any errors and every error becomes a NOP.

`H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@`#|9@)Tf\eT`=(!`|`~!y!`) Q~$x.4|m4~~&!L{%` (Try it online!)

It will output a mess of things, though (but also its source once :3).

I'll be working on other challenges, however.

# Answer
> 2 votes
# 05AB1E \- Total score: 74

### 1. Run, 74 bytes

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

Everything that causes an error is skipped by 05AB1E. This whole line of code is a NOP.

Try it online!

# Answer
> 2 votes
# Mathematica, score 68

```
`A:= .1%*.44y#+.9^`H@`$I@`L@(`$O~`Q~`Q~`Q~`T~T~Z~e~e|f|m|p|x)!!!!!&\

```

Notice the trailing newline. I do not believe that any of the other challenges can be achieved with Mathematica.

# Answer
> 2 votes
# (abused) PHP, 74 + 74 = 148

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

The PHP interpreter simply dumps the source code until it finds a `<?` since we lack `<` every permutation of those chars is a running quine. I guess this is not that worse than using a builtin quine command :P

# Answer
> 2 votes
# Labyrinth, score 74

<pre><code>AH)
IL)
OQ:
`=!)~`{+4.@ !!!$$%&(*..149@@TTZ\\^```eefmpxy||||~~~~~~~~
`Q#
`Q)
``!

I'm pretty sure any assortment of these characters produces a valid Labyrinth program, but to make it at least slightly more interesting, this prints out `2016` digit by digit. (In summary: push 2 `2`'s on the stack, pop/print one, move the other to the aux stack, print 0, push 2 `1`'s on the stack, pop/print 1, increment, bitwise not, negate (that last `1` is a `3` at this point), sum with the `2` from the aux stack, 5\*10+4 = 54, print as ascii value, terminate)

Most of the long line is simply ignored, as the `@` terminates the program.

Challenges 2, 3, and 4 are impossible since neither of Labyrinth's input commands are available (`,` or `?`), and I didn't come up with anything for 5 or 6.

# Answer
> 2 votes
# SmileBASIC, 48 points

### challenge 1:

```
@LOQQQTTZ A$=H$+@efmy+@9414*!exp(!!.||!!.#||I%):

```

explanation:

```
@LOQQTTZ 'label
A$= 'set value of A$ (string)
H$ 'string
+@efmy 'adds label, interpreted as string literal
+@9414 'adds label, interpreted as string literal
*!exp( 'multiplies by logical not e^x (= 0)
!!. 'not not 0.0 (= 0)
||!!.# 'or not not 0.0 converted to a float (= 0)
||I% 'or I% (integer variable)
: 'equivalent to a line break, does nothing here

```

### others:

No input/output commands are avaliable, so the rest are not possible.

Still, not bad for a real language without using comments.

# Answer
> 1 votes
# MATL, total score 74

## 1. Run, score 74

`4.e4 1.$!!!!!T+Zyf9.)AH^ILx@Q@Q@Qm||||~~~~~~~~~:=Tp*O%#$&()))\\````````e{

Everything up to `%` is actual code. `%` is a comment symbol, so the characters to its right are ignored.

The program outputs `1` without errors.

Try it online!

# Answer
> 1 votes
# bash, score 74

1: Run. We can run all 74

```
#H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

6: Esotericism:

The empty program is a quine in bash.

Without any whitespace characters, nothing else on the list can be accomplished. Ergo, I have the winning bash entry.

# Answer
> 1 votes
# Perl 6, total score 74

## 1. Run, score 74

my @TOTAL=$!||(e*4...9^e)Z+1~4||!!Q`{fp)))\#\&`~Q!```HI````!~Q:x~~~$~@~@~%

No comments.
(Just putting the `#` at the front to make everything a comment also works, but this is more fun.)

## Work

This is the subset of the Perl 6 language that only uses the allowed characters:

```
Constants:   e

Type names:  IO

Functions:   exp

Methods:
    on type IO:   .e  .f  .x
    (...probably more.)

Operators:     |  infix:               |  prefix:
    -----------+-----------------------+---------
    numeric:   |  +  *  +^  +|  +&  %  |  +  +^
    string:    |  ~  x  ~^  ~|  ~&     |  ~
    boolean:   |  ||  ~~               |  !
    junctions: |  |  &  ^              |
    misc:      |  =  :=  Z  ..  ...    |

syntax:
    number literals:  1  4  9
    string literals:  Q` `  Q! !   etc.
    shell commands:   Q:x` `  Q:x! !   etc.
    Whatever star:    *
    variables:        my  \  $  @  &
    grouping:         (  )
    comments:         #  #`( )
    unspace:          \

```

The immediate hurdle preventing the challenges 2-6, is that there doesn't seem to be a way to do I/O:

* If we assume there's a file called `f`, we could use `Q`f`.IO.e` to check if it exists or `Q`f`.IO.x` to check if it is executable. But we can't read it or write from it.
* We could use `Q:x` `` to run a shell command (assuming we find the characters for one). But we can't interpolate anything into, so it would only be good for reading, not writing.
* Since there is no closing brace, we can't make a block lambda (e.g. `{1 + $_}`) that automatically returns the value of its last statement.
* We *could* use the asterisk to make an expression lambda (e.g. `1+*`), but then we can only take one argument, refer to this argument only once, and are even more limited in the syntax/operators we can use.

# Answer
> 1 votes
# Vyxal, score 74

## Run, 74 bytes

```
#H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

Try it Online!

## The rest aren't easily possible.

# Answer
> 1 votes
# abcn, score 65

The Challenges :

# RUN : (73 bytes)

```
H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{%

```

## How it works :

Every thing other than `@` (which is for input) is not present in current version of abcn. Note : abcn treats everything save its commands as simple comments so all of it is one big comment the three `@` since we give no output are automatically set to `0`.

I can obviously increase the length infinitely by doing nothing but bull but wont do it. (Alternate program down below) (scrapped it since I was 130 bytes in and not even 1/4th of the way done)

# I/O : (8 bytes)

```
@agxbbgx

```

## How it works :

```
@                                 --> asks for input
a                                 --> adds one
g                                 --> converts to ASCII
x                                 --> prints
bb                                --> b takes back to input second takes back by 1 more so we at input - 1
gx                                --> converts to ASCII and prints

```

Don't think can do remaining now.

Total score : 73 - 8 =\> 65

# Answer
> 0 votes
# Lua, score 31

## 1. Run (31 of 74 points)

```
AHILOQQQTTZeefmpxy=1.%4+(4.*9.)

```

# Answer
> 0 votes
# Jelly, score 74

### 1. Run, 74

```
 ||||!!!!!$$~~~~~~~~^@=@~%449:`e@`e`QAHILOQQTTZ{\\f`m`p`x`y`&`*.#1+.()))).

```

Not sure how to do any of the others.

# Answer
> 0 votes
# ///, Score: 146

## 1. Run, Score: 74

`!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~`

## 6. Quine, Score: 72

`!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ^`````````eefmpxy{||||~~~~~~~~~`

Yay, when there aren't any forward or back slashes in the code, it just prints itself.

---
Tags: string, code-challenge, number, restricted-source, quine
---


# Question
Title: Recursively concatenated cumulative sums of [N] with M iterations
Take two positive integers `N` and `M` and create the concatenated cumulative sums of `[N]`, with `M` iterations. Output the result of the last iteration.

**Definition of the concatenated cumulative sum:**

1. Start with a number `N` and define a sequence `X = [N]`
2. Append to `X` the cumulative sums of `X`
3. Repeat step 2 `M` times.

The cumulative sum of a vector, `X = [x1, x2, x3, x4]` is: `[x1, x1+x2, x1+x2+x3, x1+x2+x3+x4]`.

**Example with `N = 1` and `M = 4`:**

`P` = the cumulative sum function.

```
M = 0: [1]
M = 1: [1, 1]                    -  X = [1, P(1)] = [[1], [1]]
M = 2: [1, 1, 1, 2]              -  X = [X, P(X)] = [[1, 1], [1, 2]]
M = 3: [1, 1, 1, 2, 1, 2, 3, 5]  -  X = [X, P(X)] = [[1, 1, 1, 2], [1, 2, 3, 5]]
M = 4: [1, 1, 1, 2, 1, 2, 3, 5, 1, 2, 3, 5, 6, 8, 11, 16]

```

Note that the first `X = [1]` is not counted as an iteration. You may choose to take `M = 5` for the above example (thus counting `X = [1]` as one iteration).

This is OEIS A107946

---

### Test cases:

```
N = 5, M = 1
5, 5

N = 2, M = 3
2, 2, 2, 4, 2, 4, 6, 10

N = 4, M = 6
4, 4, 4, 8, 4, 8, 12, 20, 4, 8, 12, 20, 24, 32, 44, 64, 4, 8, 12, 20, 24, 32, 44, 64, 68, 76, 88, 108, 132, 164, 208, 272, 4, 8, 12, 20, 24, 32, 44, 64, 68, 76, 88, 108, 132, 164, 208, 272, 276, 284, 296, 316, 340, 372, 416, 480, 548, 624, 712, 820, 952, 1116, 1324, 1596

```

This is , so shortest code wins. Optional input and output formats.

# Answer
> 7 votes
# Haskell, 35 bytes

```
n!m=iterate((++)<*>scanl1(+))[n]!!m

```

Try it online!

Thanks to H.PWiz for -18 bytes

# Answer
> 6 votes
# 05AB1E, 7 bytes

```
¸IFDηO«

```

Try it online!

**Explanation**

```
¸         # wrap input_1 in a list
 IF       # input_2 times do:
   D      # duplicate the list
    η     # get prefixes of the list
     O    # sum the prefixes
      «   # concatenate to the current list

```

# Answer
> 6 votes
# Husk, ~~9~~ ~~8~~ 7 bytes

*Thanks to H.PWiz for saving 1 byte.*

```
!¡S+G+;

```

Try it online!

Uses 1-based `M`.

### Explanation

```
      ;     Wrap N in a list to get [N].
 ¡          Iterate the following function on this list and collect
            the results in an infinite list.
  S+        Concatenate the current value with...
    G+      ...the cumulative sum. We're not using the cumsum built-in ∫
            because it prepends a zero.
!           Use M as an index into the infinite list.

```

# Answer
> 5 votes
# MATL, 6 bytes

```
:"tYsh

```

Inputs are `M`, then `N`.

Try it online! Or verify all test cases.

### Explanation

```
:"      % Implicitly input M. Do the following M times
  t     %   Implicitly input N the first time. Duplicate
  Ys    %   Cumulative sum
  h     %   Concatenate horizontally
        % Implicitly end loop. Implicitly display stack

```

# Answer
> 3 votes
# Mathematica, 34 bytes

```
Nest[#~Join~Accumulate@#&,{#},#2]&

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~83~~ ~~78~~ ~~75~~ ~~71~~ ~~65~~ ~~63~~ 60 bytes

```
def f(n,m):r=n,;exec"s=0\nfor c in r:s+=c;r+=s,\n"*m;print r

```

Try it online!

Saved ~~6~~ 8 bytes thanks to Rod
Saved 3 bytes thanks to Erik

# Answer
> 3 votes
# Dyalog APL, 12 bytes

```
{(⊢,+\)⍣⍺⊢⍵}

```

Takes N on the right side and M on the left. TryAPL here!

Explanation:

```
{(⊢,+\)⍣⍺⊢⍵}
{          } an anonymous function
 (⊢,+\)      a train for a single iteration:
  ⊢           the right argument
   ,          concatenated with
    +\        the cumulative sum
       ⍣     repeated
        ⍺     left argument times
         ⊢⍵  on the right argument

```

# Answer
> 2 votes
# Java (OpenJDK 8), ~~194~~ ~~181~~ ~~175~~ ~~163~~ ~~134~~ 110 bytes

```
(n,m)->{int a[]=new int[1<<m],c=1,i;for(a[0]=n;m-->0;)for(n=0;2*n<c;c++)for(i=++n;i-->0;a[c]+=a[i]);return a;}

```

Try it online!

# Answer
> 2 votes
# jq, 51 bytes

```
reduce range(.[1])as$j([.[0]];.+[.[:keys[]+1]|add])

```

Try it online!

done with some help from the `#jq` IRC channel at libera.chat.

returns a nice JSON array.

-1 byte from ovs.

-7 bytes from Michael Chatiskatzi.

# Answer
> 1 votes
# Dyalog APL, 19 bytes

```
{0=⍺:⍵⋄(⍺-1)∇⍵,+\⍵}

```

Try it online!

Dyadic function, with `N` on the right and `M` on the left.

```
{
    0=⍺: ⍵         ⍝ if a = 0 return
    (⍺-1) ∇ ⍵,+\⍵  ⍝ recurse with the array
                   ⍝ joined with its cumsum (+\⍵)
}

```

# Answer
> 1 votes
# , 46 bytes

```
function(N,M){for(i in 1:M)N=c(N,cumsum(N))
N}

```

Try it online!

# Answer
> 0 votes
# Jelly, 5 bytes

```
;+\$¡

```

Try it online!

Suggested version by Dennis (returns `n` instead of `[n]` for singleton arrays).

# Answer
> 0 votes
# Pyth, 12 bytes

```
L+bsM._byF]E

```

Try it here.

# Answer
> 0 votes
# JavaScript (ES6), ~~55~~ 54 bytes

Takes input in currying syntax `(m)(n)`.

```
m=>g=a=>m--?g([...a=+a?[a]:a,...a.map(x=>s+=x,s=0)]):a

```

### Test cases

```
let f =

m=>g=a=>m--?g([...a=+a?[a]:a,...a.map(x=>s+=x,s=0)]):a

console.log(f(1)(5).join(', '))
console.log(f(3)(2).join(', '))
console.log(f(6)(4).join(', '))
```

# Answer
> 0 votes
## Clojure, 67 bytes

```
#(loop[c[%]i %2](if(= i 0)c(recur(into c(reductions + c))(dec i))))

```

# Answer
> 0 votes
# Julia 1.5, 31 bytes

```
n>m=m<1 ? n : [n;cumsum(n)]>m-1

```

Try it online!

---
Tags: code-golf, number, sequence
---


title: Convert Chinese numbers

text:
# Question
Title: Convert Chinese numbers
In Chinese, numbers are written as follows:

`1 一` `2 二` `3 三` `4 四` `5 五` `6 六` `7 七` `8 八` `9 九` `10 十`

For numbers above 10, it is expressed as the number of tens and the number of ones. If there is only one ten, you do not need to explicitly say one, and if there are no ones, you don't need to put anything after:

`11 十一`
`24 二十四`
`83 八十三`
`90 九十`

For numbers above 100, you use the same logic, but with the character . This time though, if there is only one hundred, you still need to write it out, and if there are no tens, you need to say .

`100 一百` `231 二百三十一` `803 八百零三` `999 九百九十九`

Your task is to convert these Chinese numerals into Arabic numerals. Given a number *N* in Chinese ( (1) \<= *N* \<= `九百九十九` (999)), convert it into an Arabic number.

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
## JavaScript (ES6), 112 bytes

```
s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d

```

Digits 一-九 are converted to decimal and saved in `d`, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in `n`.  is effectively ignored, since `d` is already zero when it is encountered.
> 4 votes

# Answer
# PHP, 225 Bytes

```
preg_match_all("#[1-9]?10+|[1-9]#",str_replace(["一","二","三","四","五","六","七","八","九","十","百"],[1,2,3,4,5,6,7,8,9,10,100],$argv[1]),$z);foreach($z[0]as$p)$s+=($b=substr_count($p,0))?$p[0]*10**$b:$p;echo$s;

```
> 2 votes

# Answer
## Perl, 110 bytes

**98 bytes code + 12 for `-plC -Mutf8`.**

Perl does hate unicode. Hopefully I haven't missed any edge cases, I had an issue with numbers like `二百十` but I've addressed that now!

```
s/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"

```

### Usage

```
perl -plC -Mutf8 -e 's/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"' <<< '一
二
三
四
五
六
七
八
九
十
十一
二十四
八十三
九十
一百
二百三十一
八百零三
九百九十九'
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999

```
> 2 votes

# Answer
# Java 7, ~~236~~ ~~233~~ 229 bytes

```
int c(String s){String x=" 一二三四五六七八九十百";int l=s.length(),i=x.indexOf(s.charAt(l-1)),j=x.indexOf(s.charAt(0)),q=j*100;return l<2?i:l<3?i==10?j*10:i>10?q:10+i:l<4?j*10+i:l<5?q+i:q+i+x.indexOf(s.charAt(2))*10;}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static int c(String s){
    String x = " 一二三四五六七八九十百";
    int l = s.length(),
        i = x.indexOf(s.charAt(l-1)),
        j = x.indexOf(s.charAt(0));
    if(l<2) return i; // 1-10
    if(l<3){
      if(i==10) return j*10; // 20,30,40,50,60,70,80,90
      if(i>10) return j*100; // 100,200,300,400,500,600,700,800,900
      return 10+i; // 11-19
    }
    if(l<4) return j*10+i; // 21-29,31-39,41-49,51-59,61-69,71-79,81-89,91-99
    if(l<5) return j*100+i; // 101-109,201-209,301-309,401-409,501-509,601-609,701-709,801-809,901-909
    return j*100+i+x.indexOf(s.charAt(2))*10; // 111-119,121-129,131-139,...,971-979,981-989,991-999
  }

  public static void main(String[] a){
    System.out.println(c("一"));
    System.out.println(c("二"));
    System.out.println(c("三"));
    System.out.println(c("四"));
    System.out.println(c("五"));
    System.out.println(c("六"));
    System.out.println(c("七"));
    System.out.println(c("八"));
    System.out.println(c("九"));
    System.out.println(c("十"));
    System.out.println(c("十一"));
    System.out.println(c("二十四"));
    System.out.println(c("八十三"));
    System.out.println(c("九十"));
    System.out.println(c("一百"));
    System.out.println(c("二百三十一"));
    System.out.println(c("八百零三"));
    System.out.println(c("九百九十九"));
  }
}

```

**Output:**

```
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999

```
> 2 votes

# Answer
# PowerShell Core, 131 bytes

```
$args|%{if($i=("一二三四五六七八九"|% I*f $_)+1){$b=$i}if($_-eq"十"){$t+=(!$b+$b)*10
$b=0}if(!$i){$t+=$b*100
$b=0}}
$t+$b

```

Try it online!

-10 bytes thanks to *Zaelin Goodman*!
> 1 votes

# Answer
# PowerShell, 107 bytes

```
switch -r($args){百{$s+=100*$d}十{$s+=10*($d+!$d)}.{$d='一二三四五六七八九'.IndexOf($_)+1}}$d+$s

```

Try it online!
> 1 votes

# Answer
# Python 3, 128 bytes

Saving 2+3 bytes thanks to Shebang and 2 for replacing `(d>9)+(d>10)` with `max(d-9,0)`

```
n=a=0
for c in input():d=" 一二三四五六七八九十百".find(c);n+=[0,10*a**(a>0),a*100][max(d-9,0)];a=d*(d<10)
print(n+a)

```

Ungolfed:

```
n=a=0
for c in input():
 d=" 一二三四五六七八九十百".find(c)
 n+=[0, 10*a**(a>0), a*100][max(d-9,0)]
 a=d*(d<10)
print(n+a)

```

Initial answer

```
n=a=0
for c in input():
 d=" 一二三四五六七八九十百".find(c)
 if d<=9:a=d
 elif d==10:n+=[1,a][a>0]*10;a=0
 elif d==11:n+=a*100;a=0
print(n+a)

```

`n` will be the final number and `a` is the previous digit.
> 0 votes

# Answer
# C#, ~~197~~ 210 bytes

```
int x(string s){if(s=="")return 0;if(s[0]=='零')s=s.Substring(1);if(s[0]=='十')s="一"+s;string t=" 一二三四五六七八九";return s.Length<2?t.IndexOf(s[0]):(t.IndexOf(s[0])*(s[1]=='百'?100:10)+x(s.Substring(2)));}

```

*Wrong byte count previously due to encoding ignored...*

Big5 Encoding

A recursive solution which pads the input if it's 10-19 for easier processing, then process from left 2 characters at a time.

Ungolfed

```
public int x(string s)
{
    if (s == "")
        return 0;   // Recursion termination when input is divisible by 10 (no unit digit character)
    if (s[0] == '零')
        s = s.Substring(1);   // Ignore '零'
    if (s[0 ]== '十')
        s = "一" + s;   // Normalize 10-19 by padding with "一"
    string t = " 一二三四五六七八九";   // Index lookup
    return s.Length < 2
        ? t.IndexOf(s[0])   // 0-9
        : (t.IndexOf(s[0]) * (s[1] == '百' ? 100 : 10) + x(s.Substring(2)));
    // Get the first character's digit, multiply by 100 or 10 depends on 2nd character, and recursively process from 3rd character onwards
}

```
> 0 votes

---
Tags: code-golf, number, natural-language
---