title: Execute a Befunge Chess Board

text:
# Question
Title: Execute a Befunge Chess Board
Befunge Chess is an esolang mini-game I invented that is centered around the Befunge esolang. The general gist of the game is to make the instruction pointer land on a specific target cell while avoiding the opponent's target cell. Today's challenge isn't to play the game, but to simply execute arbitrary boards.

## The Rules of Befunge Chess (Context)

Quoting the Befunge esolangs article:

> A Befunge program is laid out on a two-dimensional playfield of fixed size. The playfield is a rectangular grid of ASCII characters, each generally representing an instruction. The playfield is initially loaded with the program. Execution proceeds by the means of a \[instruction pointer\]. This points to a grid cell on the playfield. The instruction pointer has inertia: it can travel to any of the four cardinal directions, and keep traveling that way until an instruction changes the direction. The instruction pointer begins at a set location (the upper-left corner of the playfield) and is initially travelling in a set direction (right). As it encounters instructions, they are executed. \[C\]ontrol flow is done by altering the direction of the \[instruction pointer\], sending it to different literal code paths.

*Source*

Befunge chess is a 2-player game. The players are called `A` and `B` At the start of the game, a board is randomly generated with two cells already filled, like so:

```
.....
.....
.A...
.....
...B.

```

The `A` and the `B` can go anywhere on the board - their position is arbitrary. However, they cannot go in the top left corner where the instruction pointer would start.

Players take turns placing commands from a modified subset of Befunge commands onto the board in an attempt to make the instruction pointer reach their target square. These commands will be described in their own section. The board is not executed during this phase.

On a player's turn, if they feel that the instruction pointer will land on their target cell, they can choose to execute the board instead of placing a command. This initiates the end sequence of the game. If the instruction pointer does reach the executing player's target piece they win. If it doesn't (i.e. it a) reaches the opponent's target piece, b) reaches a cell it's already passed or c) errors), then the other player wins. *Note: stop condition b means that there aren't any infinite loops - hence there will always be an outcome for every possible board*

If the board is completely full, then execution is automatic. Errors/reaching an already passed square lead to a tie.

## Commands

While the full mini-game I devised uses 28 commands, you'll be required to implement an 8 command subset:

```
^        Set the instruction pointer's direction to up (north)
v        Set the instruction pointer's direction to down (south)
<        Set the instruction pointer's direction to left (west)
>        Set the instruction pointer's direction to right (east)
#        Jump over the next cell
.        Do nothing (NOP)
A        Player A's target piece
B        Player B's target piece

```

## Execution

The instruction pointer starts in the top left corner (0, 0). It initially moves right (east). It transverses the board until one of the following conditions is met:

A) A player piece is reached B) An error occurs C) A cell is reached that has already been passed once

Note that if the instruction pointer would fall off the board (i.e. reach an edge), it "wraps around to the other side:

```
...>        # upon reaching the >, the instruction pointer would wrap back to the first cell in the row
....
.v..        # if the v were reached, the instruction pointer would continuing heading down and then wrap around to the second column in the first row.
....

```

Your challenge is to output the outcome of executing the board.

## Testcases

* The board is guaranteed to contain an `A` and `B` piece

```
>....v.
.....A.
..B....
.......

```

Output: `A`

---

```
>.v..v.
....>A.
.<B....
..^....

```

Output: `B`

```
....
....
.AB.
....

```

Output: `Tie`

---

```
v.
AB

```

Output: `A`

Note that this is the smallest possible board you have to handle.

---

```
.v.
>.A
^<B

```

Output: `Tie`

This is because the middle cell is passed twice.

---

```
>v....
B#....
.A....
^>....

```

Output: `B`

---

```
...^^...
..<A>...
.^.v....
<B>.....
.v......

```

Output: `Tie`

## Extra Rules

* Input/output can be given in any reasonable/convenient format
* The board size will always be rectangular (have a length and a width), will always be valid (have `A`, `B` and a mixture of commands).
* The board size will always be 2x2 or larger.
* You can use any character set you like for the different tiles, as long as you have 8 consistent characters/values.

Finally, this is , so the shortest program in each language wins.

# Answer
> 5 votes
# JavaScript (V8), 218 bytes

*-3 thanks to @Arnauld*

```
d=>eval('x=y=r=0,p=[],q=1;while(((m=d[y][x])-6)*(m-7)*!p.includes(w=x+[,y])){p.push(w);[q,r]=[[0,-1],[1,0],[0,1],[-1,0],[q,r],[q,r]][m];x=(x-q*~(m==5)+(z=d[0].length))%z;y=(y-r*~(m==5)+(z=d.length))%z};"AB"[m-6]||"T"')

```

Try it online!

# Answer
> 5 votes
# JavaScript (V8), 134 bytes

```
f=D=>eval('for(w=D[c=x=y=X=0].length,h=D.length;c--||(c=D[y][x],D[y][x]=f,c>2?c=[,X=c-4]:c<f);y=(--t%2+y+h)%h)x=-(t=X,--t%2-x-w)%w;c')

```

Try it online!

Optimized from tsh's, input map `{"A":"a","B":"b","<":"6",">":"4","^":"5","v":"7",".":"0","#":"1",}`

# JavaScript (V8), 153 bytes

```
f=D=>eval('x=y=Y=0,X=1;for(w=D[0].length,h=D.length;c=D[y][x],D[y][x]=f,+c?Y=![X=c-4]:1/c?(x+=X,y+=Y):c+1-0?Y=c+1-[X=0]:0,c<f;x=(x+X+w)%w)y=(Y+y+h)%h;c')

```

Try it online!

Rewritten from Redwolf Programs's template

# Answer
> 5 votes
# Charcoal, 55 bytes

```
ＷＳ⊞υ⪪ι¹≔⁰θＷ¬№αψ«≔§§υⅉⅈψ§≔§υⅉⅈTＦ№>^<vψ≔⊗⌕>^<ψθＭ⊕⁼#ψ✳θ»⎚ψ

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings and outputs `A` or `B`, or `T` for a tie. Explanation:

```
ＷＳ⊞υ⪪ι¹

```

Input the map and split it into characters.

```
≔⁰θ

```

Start off facing right.

```
Ｗ¬№αψ«

```

Repeat while the last seen character is not a letter.

```
≔§§υⅉⅈψ

```

Look at the current character in the map. Charcoal's array indexing is cyclic, so although I'm wandering around the canvas, I'm still seeing the correct character here.

```
§≔§υⅉⅈT

```

Replace the character with a `T` to show that we've seen it before.

```
Ｆ№>^<vψ

```

If the current character is a direction, then...

```
≔⊗⌕>^<ψθ

```

... update the direction variable.

```
Ｍ⊕⁼#ψ✳θ

```

Move one or two steps in the current direction as appropriate.

```
»⎚ψ

```

Output the winner.

# Answer
> 4 votes
# Python 3.8, 134 bytes

```
f=lambda s,r=0,c=0,d=5,*v:(g:=s[r][c])//9+((r,c)in v)or f(s,(r+(d:=g%8or d)//3*(k:=g//8+1)-k)%len(s),(c+d%3*k-k)%len(s[0]),d,*v,(r,c))

```

Try it online!

Takes advantage of the looser input/output formats. In particular the input grid is mapped in the following way: `{ '^': 1, 'v': 7, '<': 3, '>': 5, '#': 8, '.': 0, 'A': 18, 'B': 27 }`. For output, it returns `1` on a tie, `2` if `A` wins, and `3` if `B` wins.

# Answer
> 4 votes
# JavaScript (V8), 125 bytes

```
a=>eval("for(d=5,w=a[x=y=0].length,h=a.length;(c=a[y%=h][x%=w])<9;d%2?x+=w+m:y+=h+m)a[y][x]='T',d=c>2?c:d,m=(d%3-1)*-~!+c;c")

```

Try it online!

```
    '<': '3',
    '^': '6',
    '>': '5',
    'v': '8',
    '.': '2',
    '#': '0',
    'A': 'A',
    'B': 'B',

```

# Answer
> 3 votes
# APL(Dyalog Unicode), ~~149~~ 147 bytes SBCS

```
p v o g←(1 1)(0 1)⍬⎕
l←{v⊢←0 ¯1}
r←{v⊢←0 1}
u←{v⊢←¯1 0}
d←{v⊢←1 0}
b←{o,←⊂p⋄p+←v⋄p⊢←1+(⍴g)|p-1}
{o∊⍨⊂p:'T'⋄'.'=⍨x←p⌷g:b⍵⋄x∊⎕A:x⋄⍎x,'⍵⋄b⍵'}⍣{⊃⍵∊⎕A}0

```

Try it on APLgolf!

A tradfn submission which takes the grid as a character matrix. I'm sure there's multiple places to improve this.

`><^v# → rludb` and the rest of the instructions `.AB` remain the same.

Here's a testcase converter, in case there are other inputs.

# Answer
> 3 votes
# , 116 bytes

```
g=.1#.,@]
f=._3 g@{[:,/]((*0&=),:[(]]`]`(2*[)`[@.(|@g*4>|@g)(*0&~:))](%|)@|.~0j_1+.@*(*4>|)@g)/^:a:@,:]{:@,:0,~0{,^3~:,

```

Try it online!

Will try to add explanation later. The concept is more elegant than the J itself for this one.

# Answer
> 2 votes
# Python 3, 221 bytes

```
def f(g,*a):x,y,a,b,s=a or[0,0,1,0,[]];c=g[y][x];k=(c=="#")+1;a,b=c in".#"and(a,b)or[(1,0),(0,1),(-1,0),(0,-1)][">v<".find(c)];return"T"if(x,y)in s else c in"AB"and c or f(g,(x+a*k)%len(g[0]),(y+b*k)%len(g),a,b,s+[(x,y)])

```

Try it online!

Perfectly ties Redwolf's JS, by pure coincidence, lol. This could probably be shortened a lot.

# Answer
> 2 votes
# AWK, 267 258 bytes

```
R=NR,C=NF{for(j=0;k=$++j;v=v?v:k)b[R][j]=k!="."?k:0}END{c=d=f=1;a["^"]=-3;a["v"]=3;a[">"]=4;a["<"]=-4;s["A"]=s["B"]=1;for(s[1]--;y=="#"||!s[v];z=s[v=b[d][f]]>0?v:"tie"){y=="#"?0:w=a[v]?g=c=a[v]:b[d][f]=1;d=(d+=g%2)?d>R?0:d:R;f=(f+=c%3)?f>C?0:f:C;y=v}print z}

```

Try it online!

I thought the state machine properties of AWK would help make this shorter, but this particular approach probably won't get much smaller then this...

The first clause reads in the board... The board definitions expected are as listed in the description, with spaces between each character on the board.

```
R=NR,C=NF{ ... }

```

Each time a record is read in, `R` (the max rows) is set to the line number and `C` (the max columns) is set to the number of blank delimited fields. Those are use for the wrapping code later.

```
for(j=0;k=$++j;v=v?v:k)b[R][j]=k!="."?k:0

```

The `for` loop does a couple of things, primarily it sets elements of a two dimensional array `b` to either the character in the board cell or `0` if the input character was `.`.

The `v=v?v:k` bit at the end the loop just sets `v` to the first character in the board (the top left position).

```
END{ ... }

```

On EOF, meaning once the whole board has been read in, the `END` clause runs the simulation to find the answer.

```
c=d=f=1;a["^"]=-3;a["v"]=3;a[">"]=4;a["<"]=-4;s["A"]=s["B"]=1;

```

This long mess is just initiallization I couldn't find a way to shorten. The `a` array is used to compute what deltas should be applied to the current row and column for a given character. And the `s` array is used to recognize stop conditions.

```
for(s[1]--;y=="#"||!s[v];z=s[v=b[d][f]]>0?v:"tie"){ ... }

```

This inner loop does whatever one "command" implies, stopping when the `s` value of the current board position is `A` or `B` or a number greater than 0 (meaning we've been here more than once). The `#` test is to make sure the code will ignore the current cell is the previous character was the "skip the next character" command.

The body of the loop is several statement. It should be possibly be combined into one with more ternary nesting, but I gave up after hitting my deadend limit. :)

```
y=="#"?0:w=a[v]?g=c=a[v]:b[d][f]=1

```

Speaking of nested ternaries... This statement short circuits and does nothing if we're supposed to skip the cell, when the previous command was `#`.

Otherwise if the current command implies a change in direction (the `a` check), the code uses the mapped value for this command in the `a` directory to set new row and column deltas.

The "else" logic after that, is `b[d][f]=1`, which sets the current cell to a value that will trigger the "we've been here" check and exit the loop if we come back to this spot on the board.

```
d=(d+=g%2)?d>R?0:d:R;
f=(f+=c%3)?f>C?0:f:C;

```

These two statements adjust the row and column positions respectively using the offsets associated with the current command, wrapping if the values are too big or too small. The `%2` operation gives the row change (-1, 0, 1) and the `%3` operation gives the column change, also (-1, 0, 1).

```
y=v

```

And lastly, we have to save the current command in order to skip the next character is this command it `#`.

```
print z

```

When the loop exits `z` will either be `A`, `B` or `tie`.

---
Tags: code-golf, interpreter, befunge
---


title: Topographic Strings

text:
# Question
Title: Topographic Strings
Here is some example input, so I can explain what the problem is:

```
((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))

```

Think of this line of text as a topographic map of some mountains. Each set of parentheses illustrates one unit of altitude.

If we "view" this from the side, so that we see the mountains vertically, we will see:

```
          4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

```

Given one of these topographic maps, output the map, but on a vertical scale, like the output above. Seperate the different items in the map with the number of characters to the next item. For example, there are 4 spaces in the output between `moo` and `i`. Likewise, there are 4 characters in the input between `moo` and `i`.

The code which does this in the least amount of characters wins.

# Answer
## J, 87 79 72 70 67 57 56 characters

```
'( ) 'charsub|.|:(+/\@('('&=-')'&=)(],~' '$~[)"0])1!:1[1

```

Takes input from the keyboard. Example:

```
   '( ) 'charsub|.|:(+/\@('('&=-')'&=)(],~' '$~[)"0])1!:1[1
((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))
          4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

```

Explanation:

This explanation is based on the first version of my program:

```
|.|:('( ) 'charsub x)((' '$~{.@]),[{~{:@])"1(('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1

```

`x=.1!:1[1` take input from keyboard and put it into `x` for later

`(('('&([:+/=)-')'&([:+/=))\,.i.@#)` creates a list of all indeces into the string (`i.@#`) and stitches (`,.`) it together with the result of the `(('('&([:+/=)-')'&([:+/=))\` verb.

`(('('&([:+/=)-')'&([:+/=))\` this verb is applied to all the prefixes of the string (so on input `hello` it would apply to `h`,`he`,`hel`,`hell`, and `hello`. It is a fork, which counts the number of open brackets `('('&([:+/=)` and then subtracts the number of close brackets `')'&([:+/=)`. This gives me list of indeces into the string and the level the character at that index should be at in the output. On simple input this gives me the following:

```
   (('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1
(one(two(three)))
1  0
1  1
1  2
1  3
2  4
2  5
2  6
2  7
3  8
3  9
3 10
3 11
3 12
3 13
2 14
1 15
0 16

```

`((' '$~{.@]),[{~{:@])"1` this is a verb which takes the list I just generated and also the output of `('( ) 'charsub x)` (which just does a string replacement to replace all brackets with spaces in `x`). It takes the tail of each item of the list `{:@]` and uses it as an index into the string to get the character `[{~{:@]`. Then it prefixes it `,` with the number of spaces as indicated by the head of each item in the list`(' '$~{.@])`. On the previous example this gives me:

```
   ('( ) 'charsub x)((' '$~{.@]),[{~{:@])"1(('('&([:+/=)-')'&([:+/=))\,.i.@#)x=.1!:1[1
(one(two(three)))

 o
 n
 e

  t
  w
  o

   t
   h
   r
   e
   e

```

I then transpose the array `|:` and reverse it `|.` to get the desired output.
> 11 votes

# Answer
## GolfScript  69

```
0:§;{.'()'?))3%(.§+:§' ':s*\@s\if\n}%n/.{,}%$)\;:μ;{.,μ\-s*\+}%zip n*

```

Online demo here.

Explanation:

```
0:§;                # declare the variable §, representing the
                    # current vertical level and initialize it at 0

{                   # iterate for each char in the string:

    .'()'?))3% (    # add on the stack the amount by which
                    # the current vertical level should be
                    # adjusted:
                    #   * +1 if the character is '('
                    #   * -1 if the character is ')'
                    #   * 0 otherwise

    .§+:§           # adjust the value of §

    ' ':s*          # add as many spaces as § tells us
                    # and save the space in variable s

    \@s\if\         # return current char, if it's printable,
                    # or a space if it's '(' or ')'

    n               # add a newline char

}%

n/                  # split by newline char; now we have
                    # an array of strings on the stack.
                    # Each string is a vertical line of the
                    # final output.

.{,}%$)\;:μ;        # Iterate through the strings and find the
                    # maximum length

{
    .,μ\-s*\+       # Add spaces at the end to make all the strings
                    # the same length
}%

zip                 # Transpose the strings

n*                  # Join the transposed strings by newline characters

```
> 6 votes

# Answer
## APL (59)

```
⊖↑{⊃,/T\¨⍨⍵×P=0}¨R∘=¨(⍴T)∘⍴¨⍳⌈/R←1++\P←+/¨1 ¯1∘×¨'()'∘=¨T←⍞

```

I have assumed that the 'base' needs to be usable as well. (i.e. `(a(b))c(d)` is valid). If this is not necessary two characters can be saved.

Explanation:

* `T←⍞`: store a line of input in T
* `'()'∘=¨T`: for each character in T, see if it is an opening or closing parenthesis. This gives a list of lists of booleans.
* `1 ¯1∘×¨`: multiply the second element in each of these lists by -1 (so an opening parenthesis is 1, a closing one is -1 and any other character is 0).
* `+/¨`: take the sum of each inner list. We now have the ∆y value for each character.
* `P←`: store in P.
* `R←1++\P`: take a running total of P, giving the height for each character. Add one to each character so that characters outside of the parentheses are on the first line.
* `(⍴T)∘⍴¨⍳⌈/R`: for each possible y-value, make a list as long as T, consisting of only that value. (i.e. 1111..., 2222...., etc.)
* `R∘=¨`: for each element in this list, see if it is equal to R. (For each level, we now have a list of zeroes and ones corresponding to whether or not a character should appear on that level).
* `⍵×P=0`: for each of these lists, set it to zero if P is not zero at that spot. This gets rid of the characters with a non-zero delta-y, so that gets rid of the parentheses.
* `⊃,/T\¨⍨`: for each depth, select from T the characters that should appear.
* `⊖↑`: create a matrix and put it right-side-up.
> 5 votes

# Answer
## Tcl, 50

```
puts \33\[9A[string map {( \33\[A ) \33\[B} $argv]

```

Kind of cheating, but well..

I use ascii escape sequences to get the line difference, `^[[A` means move the curser 1 line up, `^[[B` is move curser 1 line down.
> 5 votes

# Answer
# APL, 41 chars/bytes\*

```
{⊖⍉⊃(↑∘''¨-⌿+/¨p∘.=,\⍵),¨⍵/⍨1-2×⍵∊p←'()'}

```

Tested on Dyalog, with a `⎕IO←1` and `⎕ML←3` environment. It's a function that takes the required input and returns the output. Given the question's wording, I believe it's acceptable. In case it's not, here is a version that reads from stdin and writes to stdout, for 4 chars more:

```
⍞←⊖⍉⊃(↑∘''¨-⌿+/¨'()'∘.=,\a),¨a/⍨1-2×'()'∊⍨a←⍞

```

**Explanation**:

```
{                                 p←'()'}  p is the string made of two parentheses
                                ⍵∊ ______  check which characters from ⍵ are parens
                            1-2× ________  -1 for every par., 1 for every other char
                         ⍵/⍨ ____________  replace () with spaces in the orig. string
    (                 ),¨ _______________  append every char to the following items
                   ,\⍵ _____________________  for every prefix of the original string
               p∘.= ________________________  check which chars are '(' and which ')'
            +/¨ ____________________________  sum: compute the number of '(' and ')'
          -⌿ _______________________________  subtract the no. of ')' from that of '('
     ↑∘''¨ _________________________________  generate as many spaces as that number
 ⊖⍉⊃ ____________________________________  make it into a table, transpose and flip

```

**Examples:**

```
topo '((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))'
          4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

```

```
topo 'a  (  b ( c(d)e ) f  )  g'
            d
          c   e
      b           f
a                       g

```

<sub>\*: APL can be saved in a variety of legacy single-byte charsets that map APL symbols to the upper 128 bytes. Therefore, for the purpose of golfing, a program that only uses ASCII characters and APL symbols can be scored as chars = bytes.</sub>
> 5 votes

# Answer
## J, 56 chars

```
'( ) 'charsub|.|:((,~#&' ')"0[:+/\1 _1 0{~'()'&i.)1!:1]1

```

Another 56-character J solution... I count depth by translating `(` into ⁻1, `)` into 1 and all other characters into 0, and then taking the running sum of this: `[: +/\ 1 _1 0 {~ '()'&i.`. The rest is largely similar to @Gareth's solution.
> 3 votes

# Answer
## Python, 161 chars

```
S=raw_input()
R=range(len(S))
H=[S[:i].count('(')-S[:i].count(')')for i in R]+[0]
for h in range(max(H),0,-1):print''.join((' '+S[i])[H[i]==H[i+1]==h]for i in R)

```
> 2 votes

# Answer
## Ruby 1.9 (129)

Reads from stdin.

```
l=0
$><<gets.split('').map{|c|x=[?(]*99;x[l+=c==?(?-1:c==?)?1:0]=c;x}.transpose.map(&:join).*(?\n).tr('()',' ').gsub(/^\s+\n/,'')

```
> 2 votes

# Answer
# Python, 130

```
a=[""]*9
l=8
i=0
for c in raw_input():o=l;l+=c==')';l-=c=='(';a[l]=a[l].ljust(i)+c*(o==l);i+=1
print"\n".join(filter(str.strip,a))

```
> 2 votes

# Answer
## C, 132 characters

```
char*p,b[999];n;
main(m){for(p=gets(memset(b,32,999));*p;++p)*p-41?*p-40?p[n*99]=*p:++n>m?m=n:0:--n;
for(;m;puts(b+m--*99))p[m*99]=0;}

```

The description failed to specify how much input the submission had to accept in order to be accepted, so I settled on limits that were most consistent with my golfing needs (while still working with the one given example input). Allow me to take this opportunity to remind folks that it's often a good idea to specify minimum maximums in your challenge descriptions.

There are two main loops in the code. The first loop farms out all the non-parenthesis characters to the appropriate line of output, and the second loop prints each line.
> 2 votes

# Answer
# C, 149 chars

```
#define S for(i=0;c=v[1][i++];)h+=a=c-'('?c-')'?0:-1:1,
c,i,h=0,m=0;main(int a,char**v){S m=h>m?h:m;for(;m;m--){S putchar(a||h-m?32:c);putchar(10);}}

```

run with quoted arg, e.g. a.out "((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))"
> 1 votes

# Answer
# Charcoal, 14 bytes

```
ＦＳ≡ι(«↘»)«↗»«ι

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# Octave, 128

Very similar to my last answer...

```
p=1;x=[0];y=input(0);for j=1:numel(y);p-=(y(j)==")");x(p,j)=y(j);p+=(y(j)=="(");end;x(x==40)=x(x==41)=x(x==0)=32;char(flipud(x))

```

### Test

**Input:** `"((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))"`

**Output:**

```
          4 5                cherries    woohoo
  1 2  3       moo       lik          e
                      i

```
> 0 votes

# Answer
## C#, 229 bytes

If there's no restriction on leading vertical space, you can use this (indented for clarity.) It'll initialise the cursor down one line for every `(` found before printing, then move the cursor up and down as brackets are read.

```
using C=System.Console;
class P{
    static void Main(string[]a){
        int l=a[0].Length,i=l;
        while(i>0)
            if(a[0][--i]=='(')C.CursorTop++;
        while(++i<l){
            char c=a[0][i];
            if(c=='('){
                c=' ';
                C.CursorTop--;
            }
            if(c==')'){
                c=' ';
                C.CursorTop++;
            }
            C.Write(c);
        }
    }
}

```
> 0 votes

# Answer
# PowerShell, ~~120~~ 119 bytes

```
(($h=($c=$args|% t*y)|%{($l+=(1,-1)[$_-40])})|sort)[-1]..0|%{$x=0;$y=$_
-join($c|%{"$_ "[$h[$x++]-ne$y-or$_-in40,41]})}

```

Try it online!

Side effects: Chars `&` and `'` changes height as `(` and `)`, but displays. Compare results for:

```
&$f "((1 2)(3 (4 5) moo)) (i (lik(cherries)e (woohoo)))"
&$f "&&1 2'&3 &4 5' moo'' &i &lik&cherries'e &woohoo'''"

```

Less golfed:

```
$chars=$args|% toCharArray

$heights=$chars|%{
    $level+=(1,-1)[$_-40]       # 40 is ASCII for '(', 41 is ASCII for ')'
    $level
}

$maxHeight=($heights|sort)[-1]

$maxHeight..0|%{
    $x=0;$y=$_
    $line=$chars|%{
        "$_ "[$heights[$x++]-ne$y -or $_-in40,41]
    }
    -join($line)
}

```
> 0 votes

# Answer
# AWK, 145 bytes

```
x=split($0,a,b){for(;""!=e=a[++b];d+=(e=="(")-(e==")"))for(c=0;c++<x;f=f<d?d:f)z[c]=z[c](c==d?e=="("||e==")"?" ":e:" ")}END{for(;f;)print z[f--]}

```

Try it online!

This code takes advantage of the spacing rules of the contest, which makes it possible to process single characters and build up a set of output lines one character at time.

For each character in the input string, one character is appended to all the output lines. All but one line get  (space) characters. Only the line associated with the current topological height get a non-space character.

Here's a breakdown...

```
x=split($0,a,b){ ... }

```

The input line is split into a character array stored in `a` with the number of characters found saved in `x`.

```
for(;""!=e=a[++b];d+=(e=="(")-(e==")"))

```

The code block is one statement, a `for` loop with one statement, which is also a `for` loop. The outer loop just iterates over all the characters. The top of loop test `""!=e=a[++b]` stores the current character in `e` to save some characters later.

The annoying `""!=` check is needed to keep AWK from bailing if a `0` is included in the input...

The "end of loop" statement `d+=(e=="(")-(e==")"` increments and decrements the `d` topological depth indicator.

```
for(c=0;c++<x;f=f<d?d:f)

```

The inner `for` loop appends a character to all the output strings the code is assembling. It uses `x` (the number of characters in the input string) as the upper bound for the number of strings to construct since we don't know now many parenthesis are in the input. That's at least 2x too large, but the code is shorter if we just assemble lines that are never used.

The "end of loop" statement `f=f<d?d:f` just sets `f` to the maximum topological depth the code sees, which is used to figure out how many lines to print out later.

```
z[c]=z[c](c==d?e=="("||e==")"?" ":e:" ")

```

The body of the inner loop just appends a character to the current output string `z[c]`. The input character is appended only if the current line matches the topological depth, and the character isn't a paren.

```
END{for(;f;)print z[f--]}

```

One all the characters have been processed, the code just prints all the assembled lines up and including the largest topological depth reached while parsing the input.
> 0 votes

# Answer
## VB.net (For S&G)

Not the prettiest of code.

```
Module Q
 Sub Main(a As String())
  Dim t = a(0)
  Dim h = 0
  For Each m In (From G In (t.Select(Function(c)
                                     h += If(c = "(", 1, If(c = ")", -1, 0))
                                     Return h
                                   End Function).Select(Function(y, i) New With {.y = y, .i = i}))
             Group By G.y Into Group
             Order By   y Descending
            Select Group.ToDictionary(Function(x) x.i)
               ).Select(Function(d) New String(
                          t.Select(Function(c,i)If(d.ContainsKey(i),If(c="("c Or c=")"c," "c,c)," "c)).ToArray))
   Console.WriteLine(m)
  Next
 End Sub
End Module

```
> -1 votes

---
Tags: code-golf, string, balanced-string
---


title: Help me get the day of the week correct

text:
# Question
Title: Help me get the day of the week correct
Sometimes, I will think it is one day of the week (e.g Friday) when in reality, it's earlier in the week (e.g Tuesday).

Your challenge is to display the number of days my estimates are off by.

## Challenge

Given a day of the week I think it is, and the day of the week it actually is, output/return the number of days between the two.

## Test Cases

```
Incorrect date, Actual Date -> Days between
Monday, Monday -> 0
Friday, Tuesday ->  3
Saturday, Sunday -> 6
Tuesday, Friday -> 4
Thursday, Wednesday ->  1
Monday, Friday -> 3

```

## Rules

* Dates have to be taken as the actual date name (`Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday`, `Saturday` and `Sunday`). This is non-negotiable.
* Date names must be taken as strings or equivalent in your language (ADTs aren't allowed unless they store their values as the allowed strings)
* Input and output can be given/taken in any reasonable format.
* Full program or function - it doesn't matter.

And finally, this is , so the answer in each language with the fewest bytes wins.

# Answer
> 19 votes
# JavaScript (ES6), 48 bytes

Expects `(day1)(day2)`.

```
a=>b=>((g=s=>parseInt(s,34)%72%23)(a)-g(b)+21)%7

```

Try it online!

### How?

We need a hash function \\$g\\$ that turns a day string into an index. The results of this function are actually quite flexible:

* They can be in ascending or descending order: `0,1,2,3,4,5,6` or `6,5,4,3,2,1,0`. (We'll have to compute either \\$g(a)-g(b)\\$ or \\$g(b)-g(a)\\$ accordingly.)
* Day #0 may be any day of the week. For instance, `3,4,5,6,0,1,2` or `4,3,2,1,0,6,5` are also valid.
* The results may be greater than \\$6\\$ as long as they are correct modulo \\$7\\$. Because the sign of the modulo is the sign of the dividend in JS, we'll have to do something like `(g(a) - g(b) + k) % 7` anyway, where \\$k\\$ is a large enough multiple of \\$7\\$.

The following function was found by brute-force:

```
g = s => parseInt(s, 34) % 72 % 23

```

which gives:

```
 day         | base34 -> dec | mod 72 | mod 23 | mod 7
-------------+---------------+--------+--------+-------
 "Monday"    |      30369728 |   56   |   10   |   3
 "Tuesday"   |    1358300452 |    4   |    4   |   4
 "Wednesday" | 1702996445748 |   12   |   12   |   5
 "Thursday"  |   45612914380 |   52   |    6   |   6
 "Friday"    |      21127508 |   44   |   21   |   0
 "Saturday"  |   43748842416 |   24   |    1   |   1
 "Sunday"    |      38623568 |   32   |    9   |   2

```

# Answer
> 13 votes
# Bash \+ GNU utilities, 26

```
date -f- +%u|dc -e??-7+7%p

```

Inputs are read from lines 1 and 2 of STDIN.

Try it online!

### Explanation

GNU `date` reads a *mostly free format human readable date string*. With `-f` it reads multiple date strings from a file and if the file is `-`, STDIN is read. The *free format* is free enough that a single day of the week will be parsed. The parsed date is then output according to the format string. `%u` simply outputs the {1..7} numerical index of the day of the week, where 1 is "Monday".

This output is piped to a `dc` expression:

```
??          # read the first 2 converted inputted dates
  -         # find the difference
   7+       # add 7
     7%     # find the modulo-7
       p    # print the result

```

# Answer
> 11 votes
# Python 2, 42 bytes

```
lambda a,b:(hash(b*11)%69-hash(a*11)%69)%7

```

Try it online!

If we can map both weekdays to their respective values (`Monday -> 0, Tuesday -> 1, ...`), then we can calculate the days in between with \\$ (a - b) \bmod 7 \\$. To do this, we use the following formula: `hash(s*11)%69%7`.

# Answer
> 8 votes
# K (ngn/k), ~~32~~ 26 bytes

**Solution:**

```
7!-/13 1 0 2 12 7 5?15!+/'

```

Try it online!

**Explanation:**

Found a slightly better lookup. Sum of ASCII chars modulo 15.

```
7!-/13 1 0 2 12 7 5?15!+/' / the solution
                       +/' / sum (+/) each (') input string
                    15!    / 15 modulo result
                   ?       / lookup this value in left list
    13 1 0 2 12 7 5        / precalculated result of summing ASCII weekdays
  -/                       / subtract to get difference
7!                         / modulo 7 to account for negatives

```

**Edits:**

* **-6 bytes** Lookup table based on sums of ascii chars, rather than `Mo/Tu/We` etc.

# Answer
> 7 votes
# Factor, 35 bytes

```
[ [ day-names index ] bi@ - 7 rem ]

```

Doesn't run on TIO because TIO is missing the `calendar.english` vocabulary which is perfectly extant on a local copy of Factor 0.98. So have a screenshot of running the quotation in the listener:

## Explanation:

It's a quotation (anonymous function) that takes two strings on the data stack as input and leaves an integer on the data stack as output. Assuming `"Tuesday" "Friday"` is on the data stack when this quotation is called...

* `[ day-names index ]` Push a quotation for `bi@` to use later.

**Stack:** `"Tuesday" "Friday" [ day-names index ]`
* `bi@` Apply a quotation to two objects. Inside the quotation now...

**Stack:** `"Tuesday"`
* `day-names` Push a sequence containing the days of the week.

**Stack:** `"Tuesday" { "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" }`
* `index` Take an object and a sequence and return the index of that object in the sequence.

**Stack:** `2`
* Now `bi@` will do the same with the other input.

**Stack:** `2 5`
* `-` Subtract.

**Stack:** `-3`
* `7` Push `7` to the stack.

**Stack:** `-3 7`
* `rem` Like `mod`, except the result is always positive.

**Stack:** `4`

# Answer
> 7 votes
# Emotilang, 1,312 bytes

(Github repo)

Input is from the first and second lines of STDIN.

```
✏
⚖♏♑↩
✏
⚖✝⛎↩
✏
⚖〰↩♑↩
✏
⚖✝♓⛎®↩
✏
⚖®↩
✏
⚖✝⛎®↩
✏
⚖⛎♑↩
✏
⚗✏
⚗⚖♏♑↩
⚗✏
⚗⚖✝⛎↩
⚗✏
⚗⚖〰↩♑↩
⚗✏
⚗⚖✝♓⛎®↩
⚗✏
⚗⚖®↩
⚗✏
⚗⚖✝⛎®↩
⚗✏
⚗⚖⛎♑↩
⚗✏
✏➖⚗
✏

```

Online interpreter

Here is proof that it passes the test cases:

# Answer
> 6 votes
# Pari/GP, 114 bytes

```
v(s,n)=1+Vecsmall(s)[n]%4;
m=[5,x,x,7;3,2,6,1;x,x,x,x;x,x,x,4];
d(n)=m[v(n,6),v(n,1)];
p(a,b)=print((d(a)-d(b))%7)

```

Explanation: Pari/GP doesn't have calendar functions or, really, much in the way of string processing. I use the ASCII values of the 1st and 6th characters of the weekday name to index into a 4x4 matrix that encodes the weekday numbers, and then I just print the forward difference. I'm pleased with my solution, but there's probably a shorter formula I didn't think of.

Try it online!

# Answer
> 5 votes
# Jelly, 16 bytes

```
OP€%647%154%8I%7

```

Try it online!

-2 bytes thanks to Arnauld via finding the modulo chain to get the right values

Previously:

# Jelly, 18 bytes

```
OP€%17Ḥị“ØỴ¦’D¤I%7

```

Try it online!

Not convinced this is a good way of doing it, lol.

-2 bytes using integer compressing (thanks Lyxal)

# Answer
> 5 votes
# Ruby, 91 bytes

```
require"date"
w=(0..6).map{|i|Date.jd(i).strftime"%A"}
f=->i,a{(w.index(i)-w.index(a)+7)%7}

```

Testing:

```
p f["Saturday", "Sunday"]   #=> 6

```

# Answer
> 4 votes
# Java (JDK), 35 bytes

```
i->a->(7+a.ordinal()-i.ordinal())%7

```

Try it online!

Call is done like this:

```
    f.apply(MONDAY).applyAsInt(TUESDAY);

```

---

Since the answer above is not of the taste of some, here's a more "Java is verbose" answer that takes strings as input rather than built-in constants:

# Java (JDK), 113 bytes

```
i->a->(java.util.Comparator.comparing((String s)->java.time.DayOfWeek.valueOf(s.toUpperCase())).compare(a,i)+7)%7

```

Try it online!

# Answer
> 4 votes
# PowerShell, ~~43~~ 41 bytes

-2 bytes thanks @Zaelin Goodman

```
$x,$y=$args|%{+[dayofweek]$_}
($x-$y+7)%7

```

Try it online!

# Answer
> 4 votes
# MATL, ~~10~~ 9 bytes

```
23Y2&md7\

```

Inputs are in reverse order. Try it online! Or verify all test cases.

### Explanation

```
      % Implicit input: cell array of two strings
23Y2  % Push predefined literal {'Monday', 'Tuesday', 'Wednesday', 'Thursday', ...
      % 'Friday', 'Saturday', 'Sunday'}
&m    % Indices of membership. Gives a vector of two numbers
d     % Consecutive differences. Gives one number
7     % Push 7
\     % Modulus
      % Implicit display

```

# Answer
> 3 votes
# Pyth, 20 bytes

```
%-Fmx"SMansFr"@d12Q7

```

Test suite

# Answer
> 3 votes
# , 37 34 bytes

```
7|-&((678 A.i.7)i.7|318+`-/@$3&u:)

```

Try it online!

* `3&u:` Convert chars to unicode numbers
* `318...$` Reshape cyclically to length 318. I found this by brute forcing a number such that the next step will return unique numbers for each weekday.
* `+`-/` Reduce by placing `+` and `-` alternately between the numbers.
* `7|` Mod 7
* `(678 A.i.7)i.` Find index of above two numbers within `0 6 4 2 1 3 5`, which are the unique numbers the weekdays map to.
* `-&` Subtract after converting both args.
* `7|` Mod 7

## , staightforward approach, 35 bytes

```
7|-&('MoTuWeThFrSaSu'-:@I.@E.~2&{.)

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~18~~ ~~17~~ ~~15~~ 11 bytes

```
C813%60%Æ7%

```

Try it online!

Try all test cases

Takes input as a list, in order \[actual date, incorrect date\]

I'm not sure exactly how 05AB1E `C` command works for non binary strings, I just tried some stuff and it worked

uses a hash to map the days to `[4, 3, 2, 1, 0, 6, 5]` (mod 7, since we do mod 7 anyway after the subtraction). The modulos were found by brute-force

```
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
after C:
[2184, 5008, 18736, 9824, 1968, 9256, 2472]
after 813%:
[558, 130, 37, 68, 342, 313, 33]
after 60%:
[18, 10, 37, 8, 42, 13, 33]
after 7%:
[4, 3, 2, 1, 0, 6, 5]

```

# Answer
> 3 votes
# Retina 0.8.2, 42 bytes

```
T`aF\hWsMn`d
\w+
$*
,
,7$*
(1*),\1|1{7}

1

```

Try it online! Link includes test cases. Explanation:

```
T`aF\hWsMn`d
\w+
$*

```

Convert the day name to a day number. This works as follows: Certain letters in the days are replaced with digits from `0` to `6`. No two digits are adjacent, and the first digit is always the correct digit for the day of the week (but descending, because the inputs are in reverse order). When I ask Retina to convert from decimal to unary, it only sees the first digit, and so gives me the desired result.

```
,
,7$*

```

Add 7 to the second number so that it is always greater than the first.

```
(1*),\1|1{7}

```

Take the difference between the numbers and reduce modulo 7.

```
1

```

Convert to decimal.

Table of day names and their conversions:

```
Sunday          Su6d0y          6
Monday          5o6d0y          5
Tuesday         Tue4d0y         4
Wednesday       3ed6e4d0y       3
Thursday        T2ur4d0y        2
Friday          1rid0y          1
Saturday        S0turd0y        0

```

# Answer
> 3 votes
# , 78 bytes

```
function(x)diff(which(t(sapply(w,grepl,x))))%%7
w=scan(,'')
M Tu W Th F Sa Su

```

Try it online!

Well, actually 76 bytes because we could use `M Tu W h F t Su` as a shorter lookup vector, but I feel the obviousness of the code is worth the extra +2.

---

# , 80 bytes

```
function(a,b,`+`=function(d)sum(utf8ToInt(d)*169^(nchar(d):1-1))%%467)(+a-+b)%%7

```

Try it online!

Interprets ASCII values in each string as base-169 digits, then evaluates (incorrectly due to floating-point errors, but the incorrectness is taken into account by the program) modulo 467. This converts the days of the week to `5 6 0 1 2 3 4` on the TIO installation of .

Somehow my own installation of  evaluates incorrectly differently, requiring interpretation in base-134 and evaluation modulo 978 (to correct the incorrectness), but both programs come out at 80 bytes.

# Answer
> 3 votes
# Jelly, 10 bytes

```
⁽Ae,8ḥ)I%7

```

A monadic Link accepting a list of two lists of characters `[incorrect, actual]` yields an integer in \\$\[0,6\]\\$ wrapped in a list.
When run as a full program this accepts a list of two strings and prints the resulting integer (since Jelly's representation of a list containing one element is just the representation of that element).

**Try it online!**

### How?

Hashes `"Thursday"` to `1`, `"Wednesday"` to `2`, ..., `"Friday"` to 7, then takes the difference modulo \\$7\\$.

```
⁽Ae,8ḥ)I%7 - Link: list of lists of characters, [incorrect, actual]
      )    - for each (day in [incorrect, actual]):
⁽Ae        -   17352
    8      -   eight
   ,       -   pair -> [17352, 8]
     ḥ     -   hash (day) using a salt of 17352 and a domain of [1..8]
       I   - differences
        %7 - mod seven -> [(ḥ(incorrect) - ḥ(actual)) mod 7]
           - implicit print (of Jelly representation of that)

```

---

### Alternative 10 byter

```
Oḅȷ%⁽€ƈI%7

```

(Same IO as the above.)

Try it online!

Maps `"Thursday"` to `0`, `"Wednesday"` to `1`, ..., `"Friday"` to `6`, then takes the difference modulo \\$7\\$.

```
Oḅȷ%⁽€ƈI%7 - Link: list of lists of characters, [incorrect, actual]
O          - convert to a list of lists of ordinals
  ȷ        - 1000
 ḅ         - convert from base (1000) to an integer (vectorises)
    ⁽€ƈ    - 4157
   %       - modulo (4157) (vectorises)
       I   - differences
        %7 - modulo seven
           - implicit print (of Jelly representation of that)

```

# Answer
> 2 votes
# Red, 70 bytes

```
func[a b][g: func[d][index? find system/locale/days d](g a)-(g b)// 7]

```

Try it online!

# Answer
> 2 votes
# Japt, 22 bytes

Going with the numeric modulo would probably be shorter, but I enjoyed this more.

```
£7ÆÐTTX ÅÃb_øX¯3
r- u7

```

Explanation:

```
£7ÆÐTTX ÅÃb_øX¯3
 7Æ              // Generate the range [0..6] and map it to
   ÐTTX          // new Date(0, 0, X)
        ÅÃ       // stringified such as "Sun Dec 31 1899", "Mon Jan 01 1900" etc.
£                // For every input string,
          b_     // map to the index of the item that
            øX¯3 // contains the first three letters of the input.
r- u7            // Reduce with subtraction, positive modulo 7.

```

Try it here.

# Answer
> 2 votes
# , ~~68~~ ~~66~~ 53 bytes

```
function(x)diff(match(x,weekdays(Sys.Date()+0:6)))%%7

```

Try it online!

Depends on system locale.

*-13 bytes thanks to @Dominic making it work for edge cases*

# Answer
> 2 votes
# Excel, 69 bytes

```
=LET(s,TEXT(SEQUENCE(7),"dddd"),MOD(MATCH(A1,s,0)-MATCH(B1,s,0)+7,7))

```

Input is in the cells `A1` and `B1`. The formula goes anywhere else.

`LET(s,TEXT(SEQUENCE(7),"dddd")` stores an array of day names so we can reference it using just `s`.
`MATCH(A1,s,0)` & `MATCH(B1,s,0)` finds the input day names in that array.
`MOD(MATCH(~)-MATCH(~)+7,7)` finds the distance from the second day (`B1`) to the first (`A1`).
The `MOD(~+7,7)` is necessary because Mon→Fri is in the same week but Fri→Mon spans two weeks.

# Answer
> 2 votes
# Charcoal, ~~28~~ 21 bytes

```
≔⁰ηＦ²≦⁻﹪⍘Ｓγ⁸⁴⁹⁰⁷ηＩ﹪η⁷

```

Try it online! Link is to verbose version of code. Edit: Saved 7 bytes thanks to @DominicvanEssen by searching for a suitable base and large modulus which generates descending integers directly instead of needing a look-up table. Explanation:

```
≔⁰η

```

Initialise the accumulator to zero.

```
Ｆ²

```

Loop over the two days.

```
≦⁻﹪⍘Ｓγ⁸⁴⁹⁰⁷η

```

Interpret the day name as a base 95 number (this is the index into printable ASCII). The number is then reduced modulo 84907 and later modulo 7, which was chosen to result in counting downwards from Thursday so that the result is the desired sign. The accumulator is subtracted from this value, so that on the first pass the accumulator becomes the first day and on the second pass it becomes the difference.

```
Ｉ﹪η⁷

```

Reduce the difference modulo 7 to account for wrapping past the end of the week.

# Answer
> 2 votes
# Lua, 72 bytes

```
a,_,b=io.read(2,"l",2)w="SuMoTuWeThFrSa"print((w:find(a)-w:find(b))/2%7)

```

Try it online!

### Explanation

```
a,_,b=io.read(2,"l",2)

```

Take first 2 bytes of each input, discarding rest of first input, and ignoring rest of second. This leaves the remaining input, so running this twice without refreshing the environment (e.g. in a `lua` console) will not work. This could be resolved by adding `,"l"` to the `read` (+4 bytes).

To make this compatible with older Lua versions, change `l` to `*l` (+1 byte).

```
(w:find(a)-w:find(b))/2%7

```

`find` returns the index at which the input was found. `w` being `SuMoTuWeThFrSa`, representing the smallest possible unique letter representation of each day. Find the difference in indexes, divide by two (string length of 14), and modulo by 7.

---
Tags: code-golf, string, date
---


title: Circumvent this credentials validator

text:
# Question
Title: Circumvent this credentials validator
This is a program I wrote in JavaScript to validate some inputted credentials, with an intentional vulnerability. The `credentials_validator` function takes an object as input, with usernames and passwords. It returns a function, which takes a username and password and returns `true` if the credentials are valid.

Your challenge is to find a `username` and `password` which, when passed to the function returned by `credentials_validator`, cause it to return `true` without knowledge of the credentials ahead of time.

This is a , so the first valid answer wins.

**Program:**

```
var credentials_validator = (credentials) => {
    if (typeof credentials !== "object")
        throw new TypeError("'credentials' must be an object");

    for (var username in credentials)
        if (typeof credentials[username] === "object")
            throw new TypeError("Passwords may not be objects or 'null'");

    return (username, password) => {
        if (typeof password === "object")
            throw new TypeError("Passwords may not be objects or 'null'");

        if (!(username in credentials))
            return false;

        if (credentials[username] === password)
            return true;

        return false;
    };
};

/*

Run with:

    var validator = credentials_validator({
        "J. Doe": "P4ssword",
        "R. Wolf": "1234",
        "X. Ample": "wxyz#1"
    });

    validator("J. Doe", "P4ssword"); // true
    validator("R. Wolf", "123"); // false

*/

```

# Answer
> username = `'toString'`, password = `{}.toString`

Try it online!

Note: Due to a certain username pointed out by Wezl in the comments, this answer is not valid for the current challenge.

## Why this works:

> Among other properties, `Object.prototype.toString` is inherited from `Object.prototype`, even if it wasn't a part of the object literal given to the validator. Since any object inherits the same function `{}.toString` is the same as the `toString` of the credentials object.
> 6 votes

---
Tags: javascript, programming-puzzle
---


# Question
Title: Find the sum of all possible base representations
The objective of this challenge is to write a program to convert an inputed string of what can be assumed as containing *only* letters and numbers from as many bases between 2 and 36 as possible, and find the base 10 sum of the results.

The input string will be converted to all the bases in which the number would be defined according to the standard alphabet for bases up to 36: `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ`. For example, the input `2T` would be valid in only bases 30 and up. The program would convert 2T from bases 30 through 36 to decimal and sum the results.

You may assume that the input string contains only letters and numbers. Your program may use uppercase or lowercase; it can, but does not need to, support both.

---

**Test cases**

*Sample input:* `2T`

Chart of possible bases

```
Base   Value
30     89
31     91
32     93
33     95
34     97
35     99
36     101

```

Output: 665

*Sample input:* `1012`

Chart of possible bases:

```
Base   Value
3      32
4      70
5      132
6      224
7      352
8      522
9      740
10     1012
11     1344
12     1742
13     2212
14     2760
15     3392
16     4114
17     4932
18     5852
19     6880
20     8022
21     9284
22     10672
23     12192
24     13850
25     15652
26     17604
27     19712
28     21982
29     24420
30     27032
31     29824
32     32802
33     35972
34     39340
35     42912
36     46694

```

Output: `444278`

*Sample input:* `HELLOworld`

Chart of possible bases

```
Base   Value
33     809608041709942
34     1058326557132355
35     1372783151310948
36     1767707668033969

```

Output: `5008425418187214`

An input of `0` would be read as `0` in all bases between 2 and 36 inclusive. There is no such thing as base 1.

---

This is code golf. Standard rules apply. Shortest code in bytes wins.

# Answer
# Python 3, ~~72~~ ~~71~~ 69 bytes

Thanks to FryAmTheEggman for saving a byte!

Thanks to DSM for saving 2 bytes!

```
N=x=0
y=input()
while N<36:
 N+=1
 try:x+=int(y,N)
 except:0
print(x)

```
> 13 votes

# Answer
# Pyth, 20 19 11 bytes

```
sm.xizd0S36

```

Blatantly stole Adnan's idea from his Python answer.

Try it here
> 9 votes

# Answer
# Pure Bash, 26

```
((s+={36..2}#$1,))
echo $s

```

Try it online!

---

Old answer from 5 years ago:

# Pure Bash (no utilities), 38

Assuming built-in base conversions are allowed:

```
for((b=36;s+=$b#$1;b--));{ :;}
echo $s

```

This will output an error to STDERR. I'm assuming this is OK as per this meta answer.

### Test output:

```
$ for t in 0 2T 1012 HELLOworld; do ./basesum.sh $t; done 2> /dev/null
0
665
444278
5008425418187214
$

```
> 6 votes

# Answer
## Seriously, 65 bytes

```
,û;╗rk`"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`MSd:37:@x`╜¿`MΣ.

```

Contains unprintables, hexdump:

```
2c963bbb726b6022303132333435363738394142434445464748494a4b4c4d4e4f505152535455565758595a22a175604d53643a33373a407860bda8604de42e7f

```

Unfortunately I don't have a good way to filter from a list based on types. Note to self: add that.

Takes input like `"2T"`

Try it online (you will have to manually enter input)

Explanation:

```
,û    get input and convert to uppercase
;╗    make a copy and save to register 0
rk    explode string into list
`"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`M  map the function over the list:
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu    get the character's index in the string and add one to get a value in [1,36]
Sd    get maximum element (maximum base aka max_base) from list by sorting and popping the last element off and pushing it to the stack
:37:@x  push range(max_base,37)
`╜¿`M  map the function over the list:
    ╜¿    convert value in register 0 to an int, interpreting it as a base-n int (n is value from list)
Σ.    sum and print
0x7f  quit

```
> 3 votes

# Answer
# Mathematica, 57 bytes

```
#~Sum~{x,Max@CoefficientList[#,x]+1,36}&@FromDigits[#,x]&

```
> 2 votes

# Answer
# Matlab, 98 bytes

```
function y=f(s)
[~,m]=max(bsxfun(@eq,s,[48:57 65:90]'));y=0;for n=max(m):36
y=y+base2dec(s,n);
end

```
> 2 votes

# Answer
# Octave, ~~75~~ 73 bytes

```
function v=u(a) m([48:57 65:90])=0:35;v=sum(polyval(t=m(a),max(t)+1:36));

```

### Explanation:

```
function v=u(a)
   m([48:57 65:90])=0:35; %// create a map: '0'-'9' = 0-9
                          %//               'A'-'Z' = 10-35
   t=m(a);                %// convert string to mapped values
   b=max(t)+1;            %// find minimum base
   p=polyval(t,b:36);     %// calculate polynomial for each base (vectorized)
   v=sum(p);              %// and return the sum of the resulting vector

```

`polyval` has an advantage over `base2dec` in that it's vectorized, so no `for` loop is required.

Only '0'..'9' and upper-case 'A'..'Z' are supported as input.
> 2 votes

# Answer
# Scala, 64 bytes

Requires uppercase input

```
s=>(s.map(_%55%48).max+1 to 36).map(b=>(0L/:s)(_*b+_%55%48)).sum

```

Try it in Scastie

-7 bytes by using a Long (`0L`) instead of a BigInt (`BigInt(0)`)

This might have been shorter if I'd used `try`/`catch` with `BigInt(number, base)`, but I didn't want to do that. ~~Still wish I could inline `n`, but I need it to determine the first valid base.~~ Apparently, it's one byte shorter by not doing `val n=s.map(_%55%48)` and reusing `n`.

Explanation:

```
s =>                        //Input
  (s.map(_ % 55 % 48)       //Turn the characters into numbers 0-35
    .max+1                  //The maximum of that (minimum base)
      to 36)                //Range of bases up to 36
  .map(b =>                 //For each base b, interpret the input in that base
    (BigInt(0)              //Starting with 0,
              /:s)          //Fold left over the input
    (_ * b +                //Multiply the accumulator by the base
      _ % 55 % 48)          //And add the next digit (put it in the range [0, 35])
  ).sum                     //Take the sum

```
> 2 votes

# Answer
# Husk, 22 bytes

or **21 bytes** with only lowercase input

```
§ṁ`Bö-1…36→▲mö%48%87c_

```

Try it online!

```
§ṁ`Bö-1…36→▲mö%48%87c_
§                       # fork: apply 2 functions to same argument
 ṁ`B                    # function 1:
 ṁ                      # sum of elements of argument
  `B                    # interpreted as base N, with N given by
    ö-1…36→▲            # function 2:
    ö                   # combine 4 funcitions:
     -1                 # remove elements equal to 1 from
       …36              # series from 36 to
          →             # one less than
           ▲            # max value of argument
            mö%48%87c_  # fork argument:
            mö          # map 4 functions over input:
                     _  # convert to lowercase
                    c   # get ASCII value
                 %87    # MOD 87
              %48       # MOD 48

```
> 2 votes

# Answer
# Haskell, 77 bytes

```
f s|d<-[mod(fromEnum c+30)39|c<-s]=sum[foldl1((+).(b*))d|b<-[2..36],all(<b)d]

```

Try it online!
> 2 votes

# Answer
# , 44 bytes

```
sum(sapply(2:36,strtoi,x=scan(,"")),na.rm=T)

```

Try it online!

R has a builtin, `strtoi`, to convert from a string to an integer in base `2:36` using only digits and capital letters, returning `NA` if it's invalid in that base. We can then `sum` them up, removing the `NA`s with `na.rm=T`.

Luckily, `sapply` is smart enough about named arguments to make this work.
> 2 votes

# Answer
# Desmos, 85 bytes

```
f(x)=x+3.5sign(60-x)-51.5
l=i.length
\sum_{n=f(i).max+1}^{36}\sum_{m=1}^lf(i[m])n^{l-m}

```

View it on Desmos (includes a bonus version that costs 2 extra bytes)

Explanation:

Input is through an array of integers `i`, as Desmos doesn't support strings. Capital letters are required.

The first function transforms a codepoint to the value in base-36, or any other base that it's valid in. The second function simply stores `i.length`, as it's expensive to call.

The third function can be understood as such:

```
\sum_{n=f(i).max+1}^{36}    Iterate n from 1+the largest codepoint value, which will be the smallest valid base, to 36, the largest valid base
\sum_{m=1}^l                Iterate m over the indices of i (Desmos is 1-indexed)
f(i[m])                     Find the value of the mth character
n^{l-m}                     Multiply by the base to the power of its distance to the right
                            Add everything up (due to using sums earlier)

```
> 2 votes

# Answer
# Jelly, 13 bytes

```
ØBiⱮµ’ḅṀr36ƊS

```

Try it online!

Works only for uppercase letters.

## Explanation

```
ØBiⱮµ’ḅṀr36ƊS   Monadic link
   Ɱ            Map over argument:
  i             Find 1-based index in...
ØB              ...base digits: "0123456789ABCD...YZabcd...yz"
    µ           Use as argument to new monadic chain
     ’          Decrement (to get 0-based indices)
      ḅ         Convert to base... (auto-mapped)
           Ɗ    ...treat 3 preceding atoms as a single link:
       Ṁ        Maximum [of argument, which is the 1-based indices]
        r36     Inclusive range to 36
            S   Sum

```
> 2 votes

# Answer
## CJam, ~~28~~ 27 bytes

*Thanks to Reto Koradi for saving 1 byte.*

This is kinda horrible...

```
qA,s'[,65>+f#_:e>)37,>\fb:+

```

Requires upper case letters.

Test it here.

CJam doesn't have built-in base-36 conversion from strings, so we have to letters out the strings ourselves. I've been trying all sorts of divmod shenanigans, but it seems to be shortest to build a string of all 36 digits and just find the index of each character in that string.
> 1 votes

# Answer
# C function, 93 (32 bit integer output only)

Assuming its OK for the output to only go up to INT\_MAX, then we can do this:

```
i,n,x;f(char *s){char *e;for(i=36,x=0;n=strtol(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%d\n",x);}

```

---

The last testcase implies that this is probably not sufficient. If so, then with 64-bit integers we have:

# C function, 122

```
#include<stdlib.h>
f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);}

```

Unfortunately the `#include <stdlib.h>` is required so the return type of `strtoll()` is correct. We need to use `long long` to handle the `HELLOworld` testcase. Otherwise this could be a fair bit shorter.

### Test driver:

```
#include<stdlib.h>
f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);}

int main (int argc, char **argv)
{
    f("0");
    f("2T");
    f("1012");
    f("HELLOworld");
}

```

### Test output:

```
$ ./basesum
0
665
444278
5008425418187214
$

```
> 1 votes

# Answer
# Japt `-x`, ~~17~~ 16 bytes

```
36õ2 k@kUnXXÃ£nX

```

Try it
> 1 votes

# Answer
# Factor, 38 bytes

```
[ 37 iota [ base> ] with map sift Σ ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a string from the data stack as input and leaves an integer on the data stack as output.

* `37 iota` Create a range from 0 to 36 inclusive.
* `[ base> ] with map` Convert the input to base 10 from each base between 0 and 36. If the input can't be converted from particular base, `base>` returns `f`.
* `sift` Remove all the `f` from a sequence.
* `Σ` Sum.
> 1 votes

# Answer
# Pyth, 16 bytes

```
V36 .x=+ZizhN ;Z

```

Try it online

Explaination:

```
                 # Implicit: Z = 0, z = input
V36              # For N in range 36
    .x           # Try except
      =+Z        # Z = Z + izhN
         izhN    # Convert z from base N+1 to decimal
              ;  # Infinite ), for closing the for loop
               Z # Print Z

```
> 0 votes

# Answer
# Japt, 26 bytes

```
1+U¬r@XwYn36}0)o37 £UnX} x

```

Try it online!

### Ungolfed and explanation

```
1+U¬ r@   XwYn36}0)o37 £    UnX} x
1+Uq rXYZ{XwYn36}0)o37 mXYZ{UnX} x

           // Implicit: U = input string
Uq rXYZ{   // Split U into chars, and reduce each item Y and previous value X by:
XwYn36     //  Choosing the larger of X and parseInt(Y,36),
}0         // starting at 0.
1+   )o37  // Add 1 and create a range from this number to 36.
mXYZ{UnX}  // Map each item X in this range to parseInt(U,X)
x          // and sum.
           // Implicit: output last expression

```
> 0 votes

# Answer
# Python 3, 142 bytes

Adnan has me soundly beat with their solution, but I did want to add my own attempt.

```
def f(s):
 t=0
 for x in range(37):
  n=0
  for i in s:
   try:m=int(i)
   except:m=ord(i)-55
   if x<=m:n=0;break
   n=n*x+m
  t+=n
 return t

```

This function only handles uppercase inputs. Add `.upper()` to `for i in s`, and it will handle both uppercase and lowercase.
> 0 votes

# Answer
# Scala 2.11, 93 bytes

This is run on the scala console.

```
val i=readLine
var s=0
for(j<-2 to 36)try{s=s+Integer.parseInt(i,j)}catch{case _:Exception=>}

```
> 0 votes

# Answer
## Haskell, 97 bytes

```
i c|'_'<c=fromEnum c-87|1<2=read[c]
f s=sum$map((`foldl1`map i s).((+).).(*))[1+i(maximum s)..36]

```

Supports only lowercase characters. Usage example:

```
f "2t"           -> 665
f "helloworld"   -> 5008425418187214

```

It's so massive, because I have to implement both char-to-ASCII and base conversion myself. The corresponding pre-defined functions are in modules which require even more expensive imports.

How it works: `i` converts a character `c` to it's digit value (e.g. `i 't'` -\> `29`). `f` calculates the value of the input string for every possible base and sums it. A non-pointfree version of the inner loop is `map (\base -> foldl1 (\value digit -> value*base + digit) (map i s)) [ ...bases... ]`.
> 0 votes

# Answer
# JavaScript (ES6), 86 bytes

```
s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`)

```

## Explanation

```
s=>
  eval(`                     // use eval to enable for loop without return keyword or {}
    p=parseInt;
    b=2;                     // b = minimum base of s
    [...s].map(d=>           // iterate through each digit d
      (v=p(d,36))            // get it's base-36 value
        >b?b=v:0             // set b to the max value
    );
    for(r=0;++b<37;)         // r = sum of all base values
      r+=p(s,b)              // add each base value from b to 36 to r
  `)                         // implicit: return r

```

## Test

```
<input type="text" id="input" value="HELLOworld" />
<button onclick="result.textContent=(

s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`)

)(input.value)">Go</button>
<pre id="result"></pre>
```
> 0 votes

# Answer
## Ceylon, ~~100~~ 96 bytes

```
Integer b(String s)=>sum(((any(s*.letter)then 11else 2)..36).map((r)=>parseInteger(s,r)else 0));

```

I first had this simpler version taking just 69 bytes:

```
Integer b(String s)=>sum((2..36).map((r)=>parseInteger(s,r)else 0));

```

But this fails with the first test case, returning `2000000000665` instead of `665`. (The reason is that the `T` in `2T` is parsed as Tera, i.e. multiplies the 2 with 10^12, when the radix is 10.) Therefore we need to catch this case separately. Thanks to Neil for suggesting a different way of doing this which saved 4 bytes.

Formatted:

```
// Find sum of all possible base representations.
//
// Question:  https://codegolf.stackexchange.com/q/65748/2338
// My Answer: https://codegolf.stackexchange.com/a/65836/2338

Integer b(String s) =>
// take the sum of ...
        sum(
    // span from 2 to 36. (Though
    // if there are letters in there, we start at 11,
    // because the other ones can't be valid.
    // Also, parseInteger(s, 10) behaves a bit strange in Ceylon.)
    ((any(s*.letter) then 11 else 2) .. 36)
    // map each r of them to ...
        .map((r) =>
            // try parsing s as a number using base r
            parseInteger(s, r)
            // if that didn't succeed, use 0.
                    else 0
    )
);

```
> 0 votes

# Answer
## Perl 6, 35 bytes

```
{[+] map {+(":$^a"~"<$_>")||0},^37}

```

usage:

```
# store it somewhere
my &code = {[+] map {+(":$^a"~"<$_>")||0},^37}

say code 'HELLOworld' # 5008425418187214

say map &code, <2T 1012>
# (665 444278)

say code 'qwertyuiopasdfghjklzxcvbnm1234567890'
# 79495849566202185148466281109757186006261081372450955140

```
> 0 votes

# Answer
# K (ngn/k), ~~38~~ 35 bytes

```
{+/t{y/x}/:(|/t:x+7*3>x-:55)_1+!36}

```

Try it online!

Takes capitalized input, e.g. "2T".

* `t:x+7*3>x-:55` map input from characters to 0..35, storing in `t`
* `(|/t...)_1+!36` identify the valid bases (those larger than the largest value in the input)
* `t{y/x}/:` convert `t`, interpreted as each valid base, to decimal
* `+/` take the sum and return
> 0 votes

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


title: Repetend length in 1/n

text:
# Question
Title: Repetend length in 1/n
This problem is based on non-terminating, repeating decimal points.

Let \\$n\\$ be any positive integer \\$(n \> 1 \text{ and } n \< 10000)\\$, say \\$7\\$. Then, \\$1/n = 1/7 = 0.142857142857142857...\\$

We see a pattern like, `0. 142857 142857 142857 ...`
In this, the `142857` part is always repeating, which has length of \\$6\\$. Or, if \\$n = 11\\$, then \\$1/n = 1/11 = 0.0909090909090909...\\$

Here the length of the pattern is `2`. So, here goes the problem!

# Task

Given a positive integer \\$n\\$, \\$(n \> 1 \text{ and } n \< 10000)\\$, find the length of pattern in \\$1/n\\$, if it's repeating. Otherwise, return *any non-positive integer* (e.g., cases: \\$1/5, 1/94, 1/22\\$). **Note that,** the pattern should start just after the decimal point. Hint: \\$1/22 = 0.04545454545454545454545\\$.

## Sample I/O

* `5 -> -1`
* `13 -> 6`
* `21 -> 6`
* `27 -> 3`
* `33 -> 2`
* `37 -> 3`
* `94 -> -1`
* `22 -> -1`
* `69 -> 22`
* `197 -> 98`
* `65 -> -1`
* \\$1/9979\\$
* \\$1/9967\\$

This is a , so the fewest bytes will win!

# Answer
# Jelly, 6 bytes

```
R⁵*%i1

```

Try it online!

Basically compute `10**[1..n] % n` and get the 1-based index of `1`.
> 14 votes

# Answer
# JavaScript (Node.js), 39 bytes

Expects a BigInt. Returns \\$0\\$ if there's no repeating pattern.

```
f=(n,k=1n)=>10n**(k%=n)%n-1n?f(n,-~k):k

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
L.Δ°I%

```

Port of *@Bubbler*'s Jelly answer, so make sure to upvote him!
-1 byte thanks to *@ovs*.

Outputs `-1` if it's non-repeating.

Try it online or verify all test cases (times out for the final test case).

**Explanation:**

```
L       # Push a list in the range [1, (implicit) input-integer]
 .Δ     # Find the first value in this list which is truthy for:
        # (results in -1 if none are found)
   °    #  Take 10 to the power the current integer
    I%  #  Modulo the input-integer
        #  (Note: Only 1 is truthy in 05AB1E)
        # (after which the result is output implicitly as result)

```
> 3 votes

# Answer
# K (ngn/k), ~~16~~ ~~23~~ 19 bytes

```
{1+(x(x!10*)\10)?1}

```

Try it online!

As suggested by @traws (returns INT\_MIN+1 if there's no repeating pattern), adapted to work with longer patterns that would otherwise overflow 64-bit integers.

* `x(...)\10` set up a monadic-do-scan, run for `x` iterations and seeded with `10`
* `(x!10*)` multiply the current value by 10, modding by the original `x` input
* `(...)?1` get the index of the first `1` showing up in the result (returns `0N` if no `1` is present, i.e. if there is no repeating pattern)
* `1+` add one to that result; converts `0N` to `-9223372036854775807`
> 3 votes

# Answer
# Jelly, 21 bytes

```
R⁵*’ḍ@¹TṂȧ@⁸g10¤’¬¤o-

```

Try it online!

This is probably very suboptimal (edit yes it is, i don't know why i didn't think to combine the two checks together cuz that would've given Bubbler's algorithm which is pretty smart).
> 2 votes

# Answer
# Husk, 8 bytes

```
€1m%¹↑İ⁰

```

Try it online!

Same approach as Bubbler's answer.

```
€1m%¹↑İ⁰
€1          # index of first '1' in
  m         # list of results of applying
   %¹       # MOD n
     ↑      # to first n elements of
      İ⁰    # series of powers of 10 (starting at 10)

```
> 2 votes

# Answer
# Perl 5 (`-p` `-Mbigint`), 31 bytes

```
$_=++$i<$_?9x$i*1%$_?redo:$i:-1

```

Try it online!
> 2 votes

# Answer
# GolfScript, ~~20~~ 19 bytes

```
~:x,{10\?x%1=},0+1=

```

Try it online!

```
~:x                   # Assign the input to x                  13
   ,                  # Make an array from 0 to x-1            [0 1 2 3 4 5 6 7 8 9 10 11 12]
    {        },       # Find all numbers that pass this test
     10\?x%           # (10^k)%x                               [1 10 9 12 3 4 1 10 9 12 3 4 1]
           1=         # Is it 1?                               [1  0 0  0 0 0 1  0 0  0 0 0 1]
                      # Only the index of the 1s are kept      [0 6 12]
               0+     # Append 0                               [0 6 12 0]
                 1=   # Get the second number                  6

```

If it doesn't repeat, the array will be `[0 0]` and `0` will be outputted.
> 2 votes

# Answer
# C (gcc), ~~55~~ 52 bytes

Saved 3 bytes thanks to the man himself Arnauld!!!

```
i;m;f(n){for(i=m=1;(m*=10)%n&&m%n-1;++i);m=m%n?i:0;}

```

Try it online!

Returns either the length of repeated pattern of \\$\frac{1}{\space n \space}\\$ or \\$0\\$ for no repeated pattern.
> 1 votes

# Answer
# Python 3, 50 bytes

```
f=lambda n,i=1:i*(10**i%n==1)or~(i<n and~f(n,i+1))

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~45~~ ~~41~~ 39 bytes

```
n_:>Lookup[Mod[10^#,n]->#&~Array~n,1,0]

```

Try it online!

Defined as a delayed rule that can be applied to any integer.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 29 bytes

```
0&@@10~MultiplicativeOrder~#&

```

Try it online!
> 1 votes

# Answer
# Retina, 68 bytes

```
.+[1379]$
_,$&*_,;
\d+
0
{`;
;_
\G_
10*
+`(_+,)\1
,$1
^_,.+;(_+)
$.1

```

Try it online! Link includes faster test cases. Explanation:

```
.+[1379]$
_,$&*_,;

```

If the number is coprime to `10`, then create a work area with the values `p=1`, `n` and `k=0` (in unary).

```
\d+
0

```

But if it is not coprime to `10` then set the answer to `0` immediately.

```
{`

```

Repeat until the answer is found.

```
;
;_

```

Increment `k`.

```
\G_
10*

```

Multiply `p` by `10`.

```
+`(_+,)\1
,$1

```

Reduce `p` modulo `n`.

```
^_,.+;(_+)
$.1

```

If `p=1`, then set the answer to `k` converted to decimal, which allows the loop to exit.
> 0 votes

# Answer
# Charcoal, 13 bytes

```
ＮθＩ⊕⌕﹪Ｘχ…¹θθ¹

```

Try it online! Link is to verbose version of code. Basically a port of @Bubbler's answer, except that my range goes from `1` to `n-1`. Explanation:

```
Ｎθ              Take input as a number
        …       Exclusive range
         ¹      From literal `1`
          θ     To input number
      Ｘ         Vectorised raise to power
       χ        Predefined variable `10`
     ﹪          Vectorised reduce modulo
           θ    Input number
    ⌕           Find index of
            ¹   Literal `1`
   ⊕            Increment
  Ｉ             Cast to string
                Implicitly print

```
> 0 votes

# Answer
## Batch, 91 bytes

```
@set/ap=1,k=0
:g
@set/ak=-~k%%%1,p=p*10%%%1
@if %k% neq 0 if %p% neq 1 goto g
@echo %k%

```

Explanation: Repeatedly increments the answer and multiplies the power by 10 until (modulo the input) the answer wraps around to zero or the power reduces to 1.
> 0 votes

---
Tags: code-golf, math, number-theory, rational-numbers
---


title: I don't like curry

text:
# Question
Title: I don't like curry
I don't like curry. Help me reverse the effects of this evil question - Make me some curry \- by uncurrying functions.

# Task

* Given a blackbox curried function, output its uncurried equivalent.
* The curried function will take a single argument and output either another curried function or a value of another type.
* The uncurried function you create will take the same number of arguments as the curried function, but all at once.

# Rules

* In languages without first-class functions, you can use an object with a method in place of a curried function - but please specify this.
* The curried function may also output a function pointer instead.
* If your language does not allow function pointers or makes passing around functions hard to work with, but allows evaluating strings to make functions (e.g. APL), you can use strings to represent both curried functions and your uncurried output function.
* You can also take the number of arguments of the functions as an input to help you determine the depth of currying.
* You may choose to return a function that takes a tuple, list, or other single value containing all the arguments.
* You may constrain the arguments **and return type** to a data type of your choosing, but that type should have more than 1 possible value.
* If `f` is the inputted curried function and `g` is your uncurried function, `f(a1)(a2)...(aN)` must always equal `g(a1, a2, ..., aN)`.
* The order of arguments in the uncurried function should be the same as in the original curried function.

For example, given the function `a -> b -> c -> a + b + c`, you can return a function that looks like `(a, b, c) -> a + b + c` or `arr -> arr[0] + arr[1] + arr[2] -> ...` but not `(c, b, a) -> ...` (wrong order). If you also take the number of arguments of the function as input, then `(a, b) -> c -> ...` would be an acceptable output given the input 2 (2 arguments are curried).

# Bounty

Since Rust is the language of the month, I will be offering a 50 rep bounty on Rust answer to this question if you haven't used Rust before.

# Answer
> 9 votes
# Python 3, 46 bytes

```
lambda g,i:lambda*l,g=g:eval(f'g{"(%a)"*i%l}')

```

Try it online!

# Python 3, 48 bytes

```
f=lambda g:lambda x,*a:f(g(x))(*a)if a else g(x)

```

Try it online!

# Answer
> 9 votes
# Haskell, ~~129~~ 127 bytes, thanks to Wheat Wizard

```
{-#Language GADTs#-}
data N c u o where Z::N o()o;S::N c u o->N(i->c)(i,u)o
(!)::N c u o->c->u->o
(Z!o)_=o
(S n!g)(i,u)=n!g i$u

```

Try it online! An unobfuscated version looks like this:

```
{-# Language GADTs #-}

data Natural curried uncurriedArguments output where
    Zero :: Natural output () output
    Successor ::
        Natural curried uncurriedArguments output ->
        Natural (input -> curried) (input, uncurriedArguments) output

deepUncurry ::
    Natural curried uncurriedArguments output ->
    curried ->
    uncurriedArguments -> output
deepUncurry Zero output () = output
deepUncurry (Successor n) g (input, uncurriedArguments)
    = deepUncurry n (g input) uncurriedArguments

```

The caller must specify the number of arguments they want uncurried as a natural number, where `Z` represents 0 and `S` adds one to a number. For example, to uncurry two arguments, you would use `S (S Z)`:

```
> :t S (S Z) ! (+)
S (S Z) ! (+) :: Num o => (o, (o, ())) -> o

```

# Answer
> 8 votes
# JavaScript (Node.js), 34 bytes

```
g=>(...a)=>a.reduce((h,x)=>h(x),g)

```

Try it online!

-1 byte, thanks to ASCII-only.

---

# JavaScript (Node.js), 31 bytes

```
g=>(...a)=>(a.map(x=>g=g(x)),g)

```

Try it online!

This 31 byte version, the returned function is not reusable. I'm not sure if this is allowed in this question...

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

```
Fold[#@#2&]~Curry~2

```

Try it online!

Returns a function of a list of arguments, i.e. `u[f][{a,b,...}]=f[a][b]...`.

Ironically, a short uncurrying involves `Curry`. Then again, functions curried with Mathematica's `Curry` built-in can accept arguments in uncurried form - per the docs, "the structure of brackets is not relevant, only the number of arguments."

---

To accept a sequence of arguments, i.e. `u[f][a,b,...]=f[a][b]...`, **20 bytes**:

```
f#@#2&~Fold~f?##&

```

Try it online!

# Answer
> 5 votes
# , ~~68~~ ~~67~~ 71 bytes

*Edit: -1 byte thanks to Giuseppe, but then +4 bytes to fix a bug spotted by ASCII-only*

```
function(f)function(...,g=f)el(rev(sapply(c(...),function(a)g<<-g(a))))

```

Try it online!

This is a horrible bit of  code, but my attempts using `for` or `while` have so far failed.

Creates a function that uses `sapply` to loop over all its arguments, updating the passed function `f` in each iteration using the `<<-` assignment operator to assign in the 'parent' scope. This generates a list of all the intermediate values (all except the last one are partially-uncurried versions of `f`), so we `rev`erse it and return the new first element (so, effectively the last element), which is the result of the fully uncurried function call.

```
uncurry=                        # define 'uncurry' as
function(f)                     # a function taking argument f, a curried function,
    function(...){              # that returns an anonymous function
                                # with an undefined number of arguments, denoted as '...'.
        x=                      # define x as
            sapply(             # the results of applying a function (see below) to each element of
                c(...),         # the concatenation of all the elements of '...' (so: the arguments)
                function(a)     # this is the function to apply, taking argument 'a' as each element:
                    f<<-f(a))   # the value of f(a)
                                # while updating 'f' to this value, in the parent scope
                                # (so the next iteration will use this new version of 'f')
        rev(x)[[1]]             # now, output the last element of x
                                # (which is the value final, uncurried output;
                                # the earlier elements of x are all the partially-uncurried
                                # versions of f)
    }

```

Note that since we use `c()` to concatenate the argument list `...` into a vector (rather than into a list), the arguments are constrained to be all of the same type (as allowed by the challenge rules). For a more-general version that can accept argments of different types, exchange `c` for `list` (at the cost of an extra 3 bytes).

---

# , ~~65~~ 61 bytes

*Edit: -5 bytes thanks to Giuseppe*

```
g=function(f)function(a,...)`if`(nargs()>1,g(f(a))(...),f(a))

```

Try it online!

Alternative recursive version: shorter, easier to understand, and without horrible scoping hacks. Heavily based on comment by ASCII-only, and made nicer (as well as even shorter) by Giuseppe.

# Answer
> 5 votes
# Underload, 11 bytes

```
((^)~^~a~*)

```

Try it online!

Function submission (because Underload full programs can't take input).

The TIO link shows a curried function `a(*a(*)*)*` that concatenates its three arguments in reverse order (calling it three times by using the `(argument)~^` function call syntax that calls a function with one literal argument). Then it uses the program above, calling it with arguments 3 (`(::**)`) and the same curried function, producing the output `(a(*a(*)*)*)^^^`. The final line runs this input on the same three literal arguments (`(arg3)~(arg2)~(arg1)~^`), demonstrating that it produces the same result.

## Explanation

```
((^)~^~a~*)
(         )   define function literal:
    ~^          call {argument 1} with argument
 (^)              lambda f, x: f(x)
                {replacing argument 1 with the return value}
      ~ ~       replace argument 2 with
       a          uneval(argument 2)
         *      compose argument 1 and argument 2
                  {and return the function newly created}

```

The basic idea here is to exploit the fact that Underload is generally very polymorphic with respect to how many arguments a function takes. In particular, we can take a function which takes two arguments and produces one return value, and call it in a loop in order to create a function that takes more than two arguments; each iteration will steal an additional argument from the argument stack.

Numbers in Underload are basically curried loops with a specific number of iterations; you can think of the number 3 as having an effect similar to `lambda f: lambda x: f(f(f(x)))` (except with the number of arguments being more flexible than this). So by executing the first argument on `lambda f, x: f(x)`, we effectively end up creating a loop that uncurries a function via simply just calling it repeatedly, consuming an extra argument each time.

This could have been just 8 bytes if not for an off-by-one error: if a function takes 1 argument, it's the same curried and uncurried; if it takes 2 arguments, we have to call it one more time; if it takes 3 arguments, we have to call it twice more, etc.. Arithmetic (other than multiplication and exponentiation) is very verbose in Underload, so instead of fixing the off-by-one error with subtraction, we uneval the function we're uncurrying. The uneval'ed function will consume no arguments and output the original function, so this neatly cancels out one level of uncurrying and thus fixes the off-by-one error.

# Answer
> 4 votes
# JavaScript (Node.js), 42 bytes

```
f=g=>(x,...a)=>a.length?f(g(x))(...a):g(x)

```

Try it online! Resulting function assumes that you give it the correct number of arguments.

# Answer
> 4 votes
# , ~~60~~ ~~58~~ 51 bytes

-2 bytes thanks to Dominic van Essen. Nicer form thanks to Giuseppe

```
function(f)function(a)Reduce(function(f,a)f(a),a,f)

```

Try it online!

# Answer
> 4 votes
# Ruby, ~~27~~ ~~25~~ 24 bytes

-3 bytes thanks to vrintle

```
->f{->a{a.inject f,:[]}}

```

Try it online!

# Answer
> 3 votes
# Common Lisp, ~~54~~ 48 bytes

```
(lambda(f)(lambda(a)(reduce'funcall(cons f a))))

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 14 bytes (SBCS)

Anonymous tacit prefix function taking the name of a Curried function as right argument, and returning the source of the un-Curried function.

```
⎕NR⊃⍨4-2⍳⍨183⌶

```

Try it online!

For example, with the function `f ← (~,∩)∘' '`, which consists of the function `~,∩` with a space character as curried right-argument, passing the name `"f"` gives:

`183⌶` explain representation; a structure identical to the structure of the target function, but with integers indicating the name class of the components
`[[3,3,3],4,2]` (3 is function, 4 is higher-order function, 2 is array)

`2⍳⍨` index of `2`
`3`

`4-` subtract that from 4
`1`

`⊃⍨` use that index to pick from:

`⎕NR` the Nested Representation, `["~,∩","∘"," "]`

This picks out our result, `"~,∩"`.

# Answer
> 2 votes
# Java (JDK), 81 bytes

(-9 bytes thanks to user. -2 bytes after removing curly braces from for loop.)

```
f->a->{var g=f;for(int i:a)g=((java.util.function.Function)g).apply(i);return g;}

```

Try it online!

Accepts an arbitrary depth `Function<Integer, ?>` where `?` is either `Integer` or `Function<Integer, ?>`, and returns a `Function<int[], Object>`.

I can't really find rules on Java submissions. I tried to mostly follow the format for what counts as the header and what the code body has to look like from an answer on the inspiration for this question. Let me know if I got anything wrong

# Answer
> 2 votes
# Attache, 11 bytes

```
Fold&:`!##V

```

Try it online!

Anonymous function that takes input like `f[curried, a1, a2, ..., aN]`.

## Explanation

With some more whitespace:

```
(Fold&:`!) ## V

```

`V` is a function that converts its arguments into a list. `V[1, 2, 3]` yields `[1, 2, 3]`. `Fold` is given the execute operation `!` as a function (``!`) for its first argument, via `f&:n`. `##` composes these two functions.

# Answer
> 2 votes
# , 56 bytes

```
g=function(f)function(a,...)`if`(nargs(),g(f(a))(...),f)

```

Try it online!

Credit to Dominic van Essen and ASCII-only for a decent part of this, so please upvote their submissions as well.

The `...` aka dots is a special R construct for functions with arbitrary number of inputs.

# Answer
> 2 votes
# Julia, 22 bytes

```
!f=x->foldl(map,[f;x])

```

`g = !f` will expect an array

Try it online!

# Answer
> 1 votes
# PHP, 84 bytes

```
function u($f){return function($a,...$b)use($f){return$b?u($f($a))(...$b):$f($a);};}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 54 bytes

```
sub f($n,$g){--$n?sub($p,@p){&{f($n,&$g($p))}(@p)}:$g}

```

Try it online!

Parameter `$n` is the number of arguments to uncurry, `$g` is the input function which has to be uncurried.

# Answer
> 1 votes
# C++ (gcc), 189 bytes

```
#define T template
T<class F>struct U{F f;auto operator()(){return f;}T<class A,class...B>auto operator()(A a,B...b){return U<decltype(f(a))>{f(a)}(b...);}};T<class F>U<F>u(F f){return{f};}

```

Try it online!

Function `u` takes in a curried callable object, and returns another callable object which is uncurried.

(I don't see any allowance for a restriction on the return type of the curried function, just on the argument types. If it were allowed, we could save two bytes by replacing both instances of `auto` with `int`.)

---
Tags: code-golf, functional-programming
---