title: There's no place like home

text:
# Question
Title: There's no place like home
I recently watched *The Wizard Of Oz* and thought that when Dorothy taps her shoes together three times, it would be easier if she used a program to do it. So let's help her.

## Task

Output slippers being tapped together 3 times.

## Output

Slippers being tapped together. A pair of slippers not being tapped looks like this:

```
  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

```

And a pair being tapped together looks like this:

```
         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

```

Basically, output

```
  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

```

For reference, the characters used are

```
_-.,/\()='`´
```

## Rules

* The output can have an optional leading/trailing whitespace
* While not explicitly banned, builtins detract from the competition, so please don't post an answer which is simply a single builtin*
* This is a so shortest code in *characters* wins. Characters is chosen due to the use of a multibyte character.

* For all you killjoys out there, this rule is intended for comedic effect and shouldn't be taken literally

# Answer
# SOGL V0.12, ~~113~~ ~~110~~ 108 characters

```
░╗╬)λ]cw╚╥Æ⁄║RL↓κΟiRDΨ℮≠3*s4sφ¡┐rκ⁾žχ&ν3.ΦƧ⁴ty¬`OΗΒ%Τz׀PΥω╤8⅟∆KΣ⅜4⅔⅝⁰?Z+pķcE□L6⁵/4γ⁽Κ¹‘▓:±↔Ζ`´ŗ⁴@┼⁴┼≥@┼;┼+3∙

```

Try it Here!

Explanation:

```
...‘                       push a compressed string of one slipper (one as the top left one) with a leading newline
    ▓                      convert from a multiline string to an array of lines
     :                     dulplicate a copy for reversing horizontally
      ±↔                   reverse horizontally
        Ζ`´ŗ               replace ` with ´
            ⁴              create a copy of the original slipper for the untapped part
             @┼            append a line of spaces after it horizontally
               ⁴┼          append horizontally a copy of the reversed slipper
                 ≥         move this - the untapped version - to the botton of the stack
                  @┼       append a space after the reversed slipper
                    ;┼     append the original slipper after it
                      +    join the two vertically together
                       3∙  multiply vertically three times

```
> 8 votes

# Answer
# Charcoal, ~~165~~ 127 bytes

```
Ｆ´´`«‖ＴＰ⪫⪪”}∧≕Ｉ3⁼wＸ¿↔？⁺⊖？◧χêIr﹪≦⎈X⊞c_⁹jＥτＴＣεh⌊Y﹪ＹＹ}φ⬤»[↷¢|nＸ;ＩζCHE⁷ＲrCsd～¢_⊖⦄⎚§⌈▷φＳ¤Iv}›ＲPx!∧⁵Ｆ]üC”`ι»Ｃ⁴²¦⁰Ｃ²¹¦¹²Ｔ⁴²¦²⁴Ｆ²Ｃ⁰¦²⁴

```

Try it online! Verbose approximation (I don't know how to write `´` in Verbose mode). Explanation:

```
Ｆ´´`«

```

Loop twice, once with `´`, once with ```.

```
‖Ｔ

```

Reflect the canvas, transforming the characters, except for the above two, which is why they are special-cased. Note that this causes the right slipper to end up on the left, which is actually correct for the second row.

```
⪫⪪””`ι»

```

Print the compressed slipper string, but with ```s replaced with the loop character. (Note that the compressed string includes left padding; this means that the reflected string from the first iteration doesn't touch the second string.)

```
Ｃ⁴²¦⁰

```

The right slipper is in the wrong place on the canvas, so copy it to the correct place. (This also makes an extra copy of the left slipper.)

```
Ｃ²¹¦¹²

```

The second row also needs a copy of the pair of slippers, but this is the same way around as they were originally created. (Actually both pairs get copied, so we now have eight slippers.)

```
Ｔ⁴²¦²⁴

```

Delete all unnecessary extra slippers, leaving two rows of two slippers.

```
Ｆ²Ｃ⁰¦²⁴

```

Make two additional vertical duplicates of the whole thing.
> 5 votes

# Answer
# Bash + Common Utilities **(~~268~~ ~~265~~ 258 Bytes)**

Saved a few bytes thanks to Justin Mariner

Bash **(~~31~~ 21 Bytes)**

```
gzip -d w;cat w w w

```

Additional File named w **(237 Bytes)** *(Base64 Encoded so I can paste it here)*

```
H4sICIT6rlkAA3cAbZFbDsQgCEX/WQV/ziQWV+BOTOgiu4JZ2YAWhVYSGxpOfNyDyExazPiuOQMsmIe1F5YoTHK2OCDOIEnWVzzhTYBZo5oYbuOkAXwRnNS9qTJ0e9SMOVJKneScFXWWW3bUn+XcFUWaack6krsxav2DH5QP8LaHNcxG7wkMSYUsOSenc8oIHYAy0ExRYxKCl5ByZtZLrG0ZrzZA9eSvohU54RwQUGa7CTgFEX7OIf2XhTsMveQvSeYBO9j3Rpglf2PrHgCR75Y6zgCrwGfJczBuZjgy1c1QH8Af0NuE5gAwAA

```

This might be seen as cheating, and I kind of agree :P.
> 4 votes

# Answer
# PowerShell, ~~575 bytes~~ ~~553~~ 551 characters

```
$a="3__.....__222 __.....__
 / ,1.\2233 /.1, \
(3\23\223 /23/3)
\3\2___\22 /___2/3/
 \3\3 ,'3__0.23 .´__3',3 /3/
3\30.'3='30=\2 /=´3'=3'.´3/
3 0.30.23\33 /23.´3.´
33 0.30.2 \3 /2 .´3.´
2 0.30-.___.'\ /'.___.-´3.´
23 0-._2/ \2_.-´
22 0----'3 '----´

23 __.....__33 __.....__
23/.1, \3 / ,1.\
2 /23/3) (3\23\
2/___2/3/ \3\2___\
33.´__3',3 /3/3 \3\3 ,'3__0.
3 /=´3'=3'.´3/33 \30.'3='30=\
3/23.´3.´2 0.30.23\
 /2 .´3.´233 0.30.2 \
/'.___.-´3.´223 0.30-.___.'\
\2_.-´222 0-._2/
 '----´22223 0----'"
0..3|%{$a=$a-replace$_,('`','------',333,'  ')[$_]}
,$a*3

```

Try it online!

Simple repeated character replacement. *Edit - saved two characters by using `$a` and looping the `replace` commands.*
> 3 votes

# Answer
# Python 2, ~~495~~ 468 bytes

```
r,R,s,a,b=str.replace,range(12),str.split,"/(`","\\)\xb4";A=B=r(r("  __.....__8 @ / ,------.#8@(  #8#       @#  #      ___#      @ #  #   ,'  __`.    @  #  `.'  ='  `=#   @   `.  `.8#  @     `.  `.       # @       `.  `-.___.'#@8 `-._      /@"+" "*13+"`----' @","#","\\"),"8"," "*8)
for _ in(0,1,2):B=r(r(r(B,a[_],"*"),b[_],a[_]),"*",b[_])
A,B,j=s(A,"@"),[_[::-1]for _ in s(B,"@")],"\n".join
for _ in"*"*3:print j(j(" ".join((A[_],B[_])[::p])for _ in R)for p in(1,-1))

```

Try it online!

Excited to read Mathematica 12's update notes. (`SlippersTapped@3` only requires 16 bytes!)
> 2 votes

# Answer
# 05AB1E, 140 bytes

```
"_ ./,-\)'´="•3₅Cæ¶ÿâsΣkÞ₂ÏÕ›|Y=ß°«:ws^N5%ÖΩjĆR["DĀó©›tØ¹oÜ™¾týǝàZ½aÕL.sΔÊÑû8&+››₄|wεŠ8ε¼áNsHÑŽJнi'`³Ö!èÆžIIƵò•11вèJ20ô∞¶¡ε2ä`"´"'`:‚}6FíD»,

```

Try it online!

**Explanation**

```
"_ ./,-\)'´="                                   # push this string
             •...•                              # push a base-255 compressed number
                  11в                           # convert to a list of base-11 numbers
                     èJ                         # index into the string with these and join
                       20ô                      # split in pieces of size 20
                          ∞                     # mirror, giving us a pair of shoes
                                                # both using the char "´"
                           ¶¡                   # split on newlines
                             ε                  # apply to each row
                              2ä`               # split in 2 pieces on stack
                                 "´"'`:         # replace "´" with "`" in the 2nd string
                                       ‚        # pair them up
                                        }       # end apply
                                         6F     # 6 times do
                                           í    # reverse each
                                            D», # print a copy joined on space and newline

```
> 2 votes

# Answer
# Python 2, ~~328~~ ~~326~~ 316 bytes

```
s=[''.join(' '*int(c)if'/'<c<':'else c for c in l)for l in r"2__.....__9 1/1,------.\8 (2\8\7 \2\6___\6 1\2\3,'2__`.4 2\2`.'2='2`=\3 3`.2`.8\2 5`.2`.7\1 7`.2`-.___.'\ 9`-._6/ 94`----'1 0".split()]
r=[''.join(dict(zip("`/\\(","\xb4\\/)")).get(c,c)for c in l[::-1])for l in s]
for a,b in(zip(s,r)+zip(r,s))*3:print a,b

```

Try it online!
> 2 votes

# Answer
# Bubblegum, 219 bytes

```
00000000: ec93 d1c9 8630 0c00 df33 c5bd e5ff 419b  .....0...3....A.
00000010: 09dc a410 8774 0227 fb34 a0d4 9011 7aa0  .....t.'.4....z.
00000020: 147a 88e4 08b8 b71b 7732 c39d 602c 6bd0  .z......w2..`,k.
00000030: 3a19 6b6b b0d0 e50f 5e21 9b36 1cfe a5bf  :.kk....^!.6....
00000040: 82bb 7f55 73f7 d734 2154 5814 dcf7 c643  ...Us..4!TX....C
00000050: 3b0f 77d0 e531 c3db 9bc2 a6b0 6f1d 02db  ;.w..1......o...
00000060: ce03 7403 6de7 11e6 ed11 cff8 b336 7c3a  ..t.m........6|:
00000070: 5e02 490d d30a ed15 d7e6 ee4d 3ba6 715a  ^.I........M;.qZ
00000080: 9344 2804 4627 082d 8cc1 ba50 40ef c375  .D(.F'.-...P@..u
00000090: 2b90 cba4 4e45 1218 e349 d582 4f35 a922  +...NE...I..O5."
000000a0: f0cd 25d5 f821 9792 6af6 00b9 9314 a327  ..%..!..j......'
000000b0: c899 042b bda2 93a4 f933 905b c990 2189  ...+.....3.[..!.
000000c0: b998 3c3d c8e4 7422 30f7 6bee d7dc afb9  ..<=..t"0.k.....
000000d0: 5f73 bfe6 7efd 36e4 f217 00              _s..~.6....

```

Try it online!

Format: **DEFLATE**
Maximum attempted iterations: **10000**
Decompressing iterations: **1019**
> 2 votes

# Answer
# JavaScript, 455 bytes

```
for(_="  Y#YXY WWWV#VU---T.TT, S ,TT.R__QW/PQ_O/OWPY/N%.Y%MM-.O.'L%-._WPK.´JJYJI#0H-´G/'.O.GYJFJQY',PY/EV DX#W,'YQ%.C/=´Y'=Y'JY/BX%.'Y='Y%=#AD @Q.....Q?@ >Y?>> ?0 /R#>@/SH(Y#@#>WP@/Y)0XUO#>W N0 C>E0YADB0WM.@XP@I0WYM.D#PDI0DL# F0>K U_.G0>W %T-'W'TG0>?WY?0@/S#PRHD/@/Y) (Y#@HVN XUOHW EWC0WBWYA0Y/@IDM.@H /DI>YM.DHF>VLHU_.G>> K0 'TG>>>%T-'0";G=/[>-Y]/.exec(_);)with(_.split(G))_=join(shift());f=a=>_.replace(/./g,a=>`\\\`
`['#%0'.indexOf(a)]||a).repeat(3)

```

Try it online!
> 1 votes

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


title: Let's make Diet Haskell

text:
# Question
Title: Let's make Diet Haskell
Haskell has tuples that can be written as

```
(a,b,c)

```

However this is just syntactic sugar for

```
(,,)a b c

```

In general an **n** tuple can be formed with **n-1** `,`s between `(`...`)` followed by its elements separated by spaces. For example the 7-tuple, `(1,2,3,4,5,6,7)` can be formed by

```
(,,,,,,)1 2 3 4 5 6 7

```

Since Haskell does not have 1-tuples they cannot be formed. You will also not be held responsible for empty tuples.

Nested tuples can be formed using parens to override the order of operations.

```
((1,2),3) == (,)((,)1 2)3

```

As part of our pursuit to remove all syntactic sugar from Haskell I am going to ask you to write a program that removes syntactic sugar from Haskell's tuples as well.

Your program should take a tuple, an array, or a string representing a sugary tuple and should output a string representing a "sugar-free" tuple. Input tuples will only ever contain positive integers or other tuples.

Since we are golfing here your output should be short. It should not contain unnecessary

* Spaces. Spaces should be used only to separate arguments of a tuple functions and should not appear after a `)` or before a `(`
* Parentheses. Parentheses should be used only when forming tuple functions or when nesting tuples.

This is a question so answers will be scored in bytes with fewer bytes being better.

## Test cases

```
(1,2)     -> (,)1 2
(1,2,3)   -> (,,)1 2 3
((1,2),3) -> (,)((,)1 2)3
(1,2,3,4) -> (,,,)1 2 3 4
(1,(2,3)) -> (,)1((,)2 3)
(10,1)    -> (,)10 1

```

# Answer
# Haskell, ~~169~~ 148 bytes

```
init.tail.fst.([]%)
p:k="(,"
l%('(':r)|(y,x:s)<-[]%r,m<-y:l=last$m%(p:s):[(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)|x<',']
l%r=lex r!!0

```

Try it online! Takes the tuple as a string. `init.tail.fst.([]%)` is the anonymous main function. Bind it to e.g. `f` and use like `f "(3,(14,1),4,7)"`, which yields `"(,,,)3((,)14 1)4 7"`.

Why is the input not provided as a Haskell tuple, you ask? Because Haskell is strongly typed, a tuple `(1,2)` has type `(Int,Int)`1 and a tuple `(1,(2,3))` has type `(Int,(Int,Int))`. Thus a function which accepts the first kind of tuple can not be applied to the second kind, and especially there can be no function which takes an arbitrary tuple2.

### Explanation:

* `p:k="(,"` is a short way to assign `p` to `'('` and `k` to `","`.
* `(%)` is the recursive parsing and converting function. The first argument is a list of already parsed tuple entries, the second argument is the remainder of the original string. Each call returns a tuple of the current converted tuple (as a string and enclosed in brackets) and the remainder of the string.
    + `l%('(':r)` If the string starts with an opening bracket, we need to parse a new tuple entry.
    `(y,x:s)<-[]%r` We recursively apply `%` and get a tuple entry `y` and the remaining string splitted into the next character `x` and the rest of the string `s`.
    `m<-y:l` We add the new entry `y` to the current list of already found entries `l` and call the result `m`.
    + The next character `x` is now either a comma `,` or a closing bracket `)`. The `last$ <B> :[ <A> |x<',']` is just a shorter way of writing `if x == ')' then <A> else <B>`.
    + So if a `,` is next, we need to recursively parse the next entry: `m%(p:s)` We prepend an opening bracket in order to end up in the right case and pass the list of already found entries `m`.
    + If otherwise `x == ')'`, we finished the current tuple and need to do the required transformation: `(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)`
        - `p:p:(l>>k)++x:` If we have found *n* entries, then `m` has *n* elements and `y`, the list before adding the most recently found element, has *n-1* entries. This comes in handy as we need *n-1* `,` for an `n` element tuple and `l>>k` works on lists as *"concatenate the list `k` with itself as many times as `y` has elements"*. Thus this first part yields some string like `"((,,,)"`.
        - `foldl(\r x->x++[' '|x>k,r>k]++r)[x]m` concatenates the elements of `m` (in reverse order, because by adding new entries to the front `m` itself was constructed in reverse order) while adding only spaces in between two elements if they are both numbers: `[' '|x>k,r>k]` we check if the current entries `x` and `r` are numbers by lexicographically comparing them to `","` \- if they are not numbers, they are already a tuple representation enclosed in brackets, and `'(' < ','` holds.
    + If the pattern match `l%('(':r)` right at the beginning fails, then we end up on the last line: `l%r=lex r!!0`. This means we need to parse a number and return the number and the remainder of the string. Luckily there is the `lex` function which does exactly that (It parses the next valid Haskell token, not just numbers). However the resulting tuple is wrapped into a list, so we use `!!0` to get the first element of the list.
* `init.tail.fst.([]%)` is the main function which takes a string and applies `%` with an empty list to it. E.g. for an input `"(1,2)"`, , applying `([]%)` yields `("((,)1 2)","")`, so the outer tuple and brackets need to be removed. `fst` gets the first element of the tuple, `tail` removes the closing bracket and `init` the opening one.

**Edit:** Many thanks to @Ørjan Johansen for golfing a total of **21 bytes**!

---

1 Actually, the type is *(Num t1, Num t) =\> (t, t1)*, but that's a diferent story.

2 Ignoring polymorphic functions like *id*, which cannot actually work with their input.
> 17 votes

# Answer
## Haskell, ~~141 bytes~~ 138 bytes(Thanks to Ørjan Johansen)

```
import Language.Haskell.TH
f(TupE l)='(':tail(","<*l)++')':""%l
q%(LitE(IntegerL i):l)=q++show i++" "%l
_%(e:l)='(':f e++')':""%l
_%[]=[]

```

`f` has type `Exp -> String`.

* Input: a Template Haskell `Exp`ression (i.e., the standard AST representation of arbitrary-type Haskell values – basically, parsed Haskell code before type checking); must represent a tuple containing only nonnegative integer numbers and other such tuples.
* Output: a string containing the desugared syntax for that tuple expression.

Demo:

```
$ ghci TupDesugar.hs
GHCi, version 8.3.20170711: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from /home/sagemuej/.ghc/ghci.conf
Loaded GHCi configuration from /home/sagemuej/.ghci
[1 of 1] Compiling Main             ( TupDesugar.hs, interpreted )
Ok, 1 module loaded.
*Main> :set -XTemplateHaskell -XQuasiQuotes
*Main> f <$> runQ [|(1,2)|]
"(,)1 2"
*Main> f <$> runQ [|(1,2,3)|]
"(,,)1 2 3"
*Main> f <$> runQ [|((1,2),3)|]
"(,)((,)1 2)3"
*Main> f <$> runQ [|(1,2,3,4)|]
"(,,,)1 2 3 4"
*Main> f <$> runQ [|(1,(2,3))|]
"(,)1((,)2 3)"
*Main> f <$> runQ [|(10,1)|]
"(,)10 1"

```
> 9 votes

# Answer
# Haskell, 119 bytes

```
data T=I Int|U[T]
f(U t)="(("++init(t>>",")++')':foldr(\x y->f x++[' '|f x>",",y>","]++y)")"t
f(I n)=show n
init.tail.f

```

Try it online! This uses a custom data type `T` to represent tuples, that is a tuple `((1,2),3)` is represented as `U[U[I 1,I 2],I 3]`. Example usage: `init.tail.f $ U[U[I 1,I 2],I 3]` yields `(,)((,)1 2)3`.
> 8 votes

# Answer
# Python 2, 110 bytes

```
def f(t):
 s='('+','*~-len(t)+')';c=0
 for i in t:
	try:s+=' '*c+`+i`;c=1
	except:s+='(%s)'%f(i);c=0
 return s

```

Try it online!

Takes a `tuple`.
> 6 votes

# Answer
# GNU sed, ~~149~~ 82 + 2 = 84 bytes

+2 bytes for `-r` flag.

```
y/(),/<>'/
:
s/([^<>']+)'/,\1 /
t
s/ ?<(,+)([^>]+)>/((\1)\2)/
t
s/^.|(\)) |.$/\1/g

```

Try it online!

## Explanation

```
y/(),/<>'/                   # Replace parens and commas with brackets and apostrophes
:
  s/([^<>']+)'/,\1 /.          # Remove each apostrophe and insert comma after <
  t                            # Branch to : if substitution was made
  s/ ?<(,+)([^>]+)>/((\1)\2)/  # Change <,,,...> to ((,,,)...)
  t                            # Branch to : if substitution was made
s/^.|(\)) |.$/\1/g           # Remove outermost ()s and extra spaces

```
> 4 votes

# Answer
# JavaScript, 75 bytes

```
f=a=>`(${t=a.map(x=>'')})${a.map(v=>t=1/v?1/t?' '+v:v:`(${f(v)})`).join``}`

```

Input array of number|array, output string.

Thanks to Neil, save 2 bytes
> 3 votes

# Answer
# Mathematica, 94 bytes

```
{"(",","&/@Most@#,")",c=1>0;(xIf[j=ListQ@x,c=j;"("<>#0@x<>")",If[c,c=j;x," "<>x]])/@#}<>""&

```

Contains an unprintable `U+F4A1`, a builtin `Function` function.

Takes a `List` of integer `String`s. If this is not allowed, this can be fixed by adding 10 more bytes (this version takes a `List` of `List`s/`Integer`s):

```
{"(",","&/@Most@#,")",c=1>0;(xIf[j=ListQ@x,c=j;"("<>#0@x<>")",If[c,c=j;""," "]<>ToString@x])/@#}<>""&

```
> 2 votes

# Answer
## JavaScript (ES6), ~~88~~ 84 bytes

```
f=a=>a.reduce((s,e)=>s+=e[0]?`(${f(e)})`:/\)$/.test(s)?e:' '+e,`(${[...a].fill``})`)

```

Takes an array of integers and arrays. Edit: Saved 1 byte by using `s+=` instead of two separate uses of `s+`. Saved a further 3 bytes now that I can simplify the inner ternary. If I steal @tsh's ideas then I can get it down to 76 bytes:

```
f=a=>a.reduce((s,e)=>s+=t=1/e?1/t?' '+e:e:`(${f(e)})`,`(${t=a.map(_=>``)})`)

```
> 2 votes

# Answer
# Pip, 45 bytes

```
{Y"()"b:yJ',X#a-1Fcab.:c>0?s.cyJ(fc)bR") "')}

```

This is a function that takes a list as an argument. Try it online!

### Commented version

```
; Define an anonymous function (the argument is available inside as the variable a)
{
  ; Yank the string "()" into y variable
  Y "()"
  ; Create a string of len(a)-1 commas, join y on it, and assign to b
  b: y J ',X#a-1
  ; For each item c in a
  F c a
    ; Concatenate to b the following expression
    b .:
      ; Is c integer or list?
      ; (If c is a positive integer, c>0 is true; but if c is a list, c>0 is false)
      c>0 ?
        ; If c is integer, concatenate space followed by c
        s.c
        ; If c is list, call function recursively on c and use the result to join y
        yJ(fc)
  ; Replace ") " with ")" in b and return the resulting string
  b R ") " ')
}

```
> 2 votes

# Answer
# R, 316 bytes?

(Have to head out and not sure the proper way to count bytes... plus it's not a great solution but wanted to post it since I spent the time making it...)

```
p=function(x){
x=eval(parse(text=gsub("\\(","list(",x)))
f=function(j,r=T){
p=paste
s=if(r){"("}else{"(("}
o=paste0(s,p(rep(",",length(j)-1),collapse=""),")")
n=lengths(j)
for(i in seq_along(n)){
v=j[[i]]
if(n[i]>1){v=f(v,F)}
o=p(o,v)}
if(!r){o=p(o,")")}
o=gsub(" *([()]) *","\\1",o)
return(o)}
f(x)
}

```

Test cases:

```
> p("(1,2)")
[1] "(,)1 2"
> p("(1,2,3)")
[1] "(,,)1 2 3"
> p("((1,2),3)")
[1] "(,)((,)1 2)3"
> p("(1,2,3,4)")
[1] "(,,,)1 2 3 4"
> p("(1,(2,3))")
[1] "(,)1((,)2 3)"
> p("(10,1)")
[1] "(,)10 1"

```
> 1 votes

# Answer
## JavaScript (ES6), 72 bytes

```
f=(a,b="",c="")=>a.map?b+"("+a.map(x=>'')+")"+a.map(x=>f(x,"(",")"))+c:a

```

Input: Array containing numbers and/or arrays

Output:string

Usage: f(\[...\])

Completes all test cases, improvements welcome
> 1 votes

# Answer
# C, 308 or 339 bytes

```
#include <ctype.h>
#define p putchar
f(s,e,c,i,l)char*s,*e,*c;{i=1,l=40;if(*s++==l){p(l);for(c=s;i;i+=*c==l,i-=*c==41,i+*c==45&&p(44),c++);p(41);}for(;s<e;s=c){for(i=0;isdigit(*s);s+=*s==44)for(i&&p(32),i=1;isdigit(*s);s++)p(*s);*s==l&&p(l);for(c=s,i=1;++c,c<=e&&i;i+=*c==l)i-=*c==41;f(s,c-1);*s==l&&p(41);}}
#define g(x) f(x, x+strlen(x))

```

308 or 339 bytes, depending on whether or not passing a pointer to the end of the input string is allowed; the last line is only there to allow passing a string literal directly without having to calculate its length.

## Explanation

A pretty simple algorithm. It counts the number of commas at the current depth, prints them as a tuple constructor, then follows up with the tuple's arguments, escaped (spaces between numbers, nested tuples between parenthesis), recursively.

```
#include <stdio.h>
#include <ctype.h>
typedef enum { false, true } bool;

void tup2ptsfree(char *s, char *e)
{
  int depth;
  char *c;

  if (*s++ == '(') { /* If we are at the start of a tuple, write tuple function `(,,,)` (Otherwise, we are at a closing bracket or a comma) */
    putchar('(');
    /* do the search for comma's */
    c=s; /* probe without moving the original pointer */
    for (depth=1; depth != 0; c++) {
      if (*c == '(') depth++;
      if (*c == ')') depth--;
      if (*c == ',' && depth == 1) putchar(','); /* We have found a comma at the right depth, print it */
    }
    putchar(')');
  }
  while (s < e) { /* The last character is always ')', we can ignore it and save a character. */
    bool wroteNumber;
    for (wroteNumber=false; isdigit(*s); wroteNumber = true) {
      if (wroteNumber) p(' ');           /* If this is not the first number we are writing, add a space */
      while (isdigit(*s)) putchar(*s++); /* Prints the entire number */
      if (*s == ',') s++;                /* We found a ',' instead of a ')', so there might be more numbers following */
    }
    /* Add escaping parenthesis if we are expanding a tuple (Using a small if statement instead of a large branch to prevent doing the same thing twice, since the rest of the code is essentially the same for both cases). */
    if (*s == '(') putchar('(');
    /* Find a matching ')'... */
    c=s+1;
    for (depth=1; c <= e && depth != 0; c++) {
      if (*c == '(') depth++;
      if (*c == ')') depth--;
    }
    /* Found one */
    /* Note how we are looking for a matching paren twice, with slightly different parameters. */
    /* I couldn't find a way to golf this duplication away, though it might be possible. */
    /* Expand the rest of the tuple */
    tup2ptsfree(s, c-1);
    /* idem */
    if (*s == '(') putchar(')');
    /* Make the end of the last expansion the new start pointer. */
    s=c;
  }
}

#define h(x) tup2ptsfree(x, x+strlen(x))

```

## Test cases and application

```
#include <stdio.h>

#define ARRAYSIZE(arr) (sizeof(arr)/sizeof(*arr))
static char *examples[] = {
  "(1,2)",
  "(10,1)",
  "(1,2,3)",
  "(1,2,3,4)",
  "((1,2),3)",
  "(1,(2,3))",
  "(1,(2,3),4)",
  "((1,2),(3,4))",
  "((1,(2,3)),4,(5,6))",
  "((1,((2,3), 4)),5,(6,7))",
  "(42,48)",
  "(1,2,3,4,5,6,7)"
};

int main(void)
{
  int i;
  for (i=0; i < ARRAYSIZE(examples); i++) {
    printf("%-32s | \"", examples[i]);
    g(examples[i]); /* Test with golfed version */
    printf("\"\n");
    printf("%-32s | \"", examples[i]);
    h(examples[i]); /* Test with original version */
    printf("\"\n");
  }
}

```
> 0 votes

---
Tags: code-golf, string, haskell
---


title: Simple State Sales Tax Calculator

text:
# Question
Title: Simple State Sales Tax Calculator
Sales taxes in the United States are complicated, to say the least. Generally, there's a state sales tax (there are a handful of states that do not collect a state sales tax), but there could also be a county sales tax, a school district sales tax, a municipal (city) sales tax, or a metropolitan area sales tax. There could even be different sales taxes in different parts of a city. For the purposes of this challenge, however, we're going to focus on just the state sales tax.

Given a U.S. dollar amount greater than zero (accurate to two decimal places) and a state (either the full name or the two-letter abbreviation, your choice, case doesn't matter), and using the below chart of sales tax percentages, output the corresponding state sales tax required to be collected for that particular sale, accurate and truncated to two decimal places. Please specify how your code handles rounding.

***Edit: The abbreviation for Washington was listed incorrectly as WS instead of WA. Answers may use either abbreviation, since that was my goof.***

```
State          Abbr   %
Alabama         AL  4.00%
Alaska          AK  0.00%
Arizona         AZ  5.60%
Arkansas        AR  6.50%
California      CA  6.00%
Colorado        CO  2.90%
Connecticut     CT  6.35%
Delaware        DE  0.00%
Florida         FL  6.00%
Georgia         GA  4.00%
Hawaii          HI  4.00%
Idaho           ID  6.00%
Illinois        IL  6.25%
Indiana         IN  7.00%
Iowa            IA  6.00%
Kansas          KS  6.50%
Kentucky        KY  6.00%
Louisiana       LA  5.00%
Maine           ME  5.50%
Maryland        MD  6.00%
Massachusetts   MA  6.25%
Michigan        MI  6.00%
Minnesota       MN  6.875%
Mississippi     MS  7.00%
Missouri        MO  4.23%
Montana         MT  0.00%
Nebraska        NE  5.50%
Nevada          NV  4.60%
New Hampshire   NH  0.00%
New Jersey      NJ  6.88%
New Mexico      NM  5.13%
New York        NY  4.00%
North Carolina  NC  4.75%
North Dakota    ND  5.00%
Ohio            OH  5.75%
Oklahoma        OK  4.50%
Oregon          OR  0.00%
Pennsylvania    PA  6.00%
Rhode Island    RI  7.00%
South Carolina  SC  6.00%
South Dakota    SD  4.50%
Tennessee       TN  7.00%
Texas           TX  6.25%
Utah            UT  4.70%
Vermont         VT  6.00%
Virginia        VA  4.30%
Washington      WA  6.50%
West Virginia   WV  6.00%
Wisconsin       WI  5.00%
Wyoming         WY  4.00%

```

Example for California at 6% state sales tax --

```
CA
1025.00

61.50

```

Example for Minnesota at 6.875% --

```
MN
123.45

8.49

```

# Answer
# Mathematica, ~~112~~ ~~103~~ ~~77~~ ~~76~~ 66 bytes

<sup>*Mathematica has a builtin for everything*</sup>

```
NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

```

Takes a state name (any format; abbreviation or full name) and the dollar amount.

Try it on Wolfram Sandbox

### Usage

```
f = NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

```

```
f["CA", 1025.00]

```

> 61.50

```
f["miNnNesToA", 123.45]

```

> 8.49

### Explanation

```
Interpreter["USState"][#]

```

Interpret the input as a US State name and generate an `Entity`.

```
... @"StateSalesTaxRate"

```

Get the sales tax rate.

```
... #2

```

Multiply that by the second input.

```
NumberForm[..., {9,2}]

```

Format the result into a number with 9 digits to the left of the decimal and 2 digits to the right.
> 16 votes

# Answer
# 05AB1E, 134 bytes

```
.•2=Šλ₁ÙH ’€9¿FîβïLT_s€¤Ôтαxì8ÜuK8º'DιÒ—pcλ¯øÒÔ\’þü€ŒβÞéΣŽZê•#.å1kUX0‹i6*т/ëX•Ž½ì∞в’±₃C¸wiα·¥žYÉúžĆƵ˜šŸ‰Ê‡†Σgλ&/ûjDĆв₆•hR„AB„ .‡#è*т/}

```

Try it online!

---

RIP Mathematica wins.

---

All this does is compresses the following strings:

```
AKDEMTNHOR CO ALGANYHIWY MO VA SDOK NV UT NC LANDWI NM MENE AZ OH ILMATX CT ARKSWS MN NJ INMSRITN

```

And:

```
0 2.9 4 4.23 4.3 4.5 4.6 4.7 4.75 5 5.13 5.5 5.6 5.75 6.25 6.35 6.5 6.875 6.88 7

```

Then uses the index of the input state to determine the index of the rate, defaulting to 6, because there are so many states with 6%.

---

For others to consume:

```
AKDEMTNHOR 0
CO         2.9
ALGANYHIWY 4
MO         4.23
VA         4.3
SDOK       4.5
NV         4.6
UT         4.7
NC         4.75
LANDWI     5
NM         5.13
MENE       5.5
AZ         5.6
OH         5.75
CAFLIDIAKYMDMIPASCVTWV 6
ILMATX     6.25
CT         6.35
ARKSWS     6.5
MN         6.875
NJ         6.88

```

---

Note this only works because I ordered the states such that no intersection of 2 states creates a different state E.G. (`OHIN` contains `[OH,IN,HI]` whereas `INOH` only contains `[IN,OH]`)

---

Most of the ideas for this came from my previous state-based entry.
> 5 votes

# Answer
# , ~~219~~ 212 bytes

```
function(S,m)sprintf("%.2f",c(4,0,5.6,6.5,6,2.9,6.35,0,6,4,4,6,6.25,7,6,6.5,6,5,5.5,6,6.25,6,6.875,7,4.23,0,5.5,4.6,0,6.88,5.13,4,4.75,5,5.75,4.5,0,6,7,6,4.5,7,6.25,4.7,6,4.3,6.5,6,5,4)[match(S,state.abb)]*m/100)

```

Takes the state as an abbreviation (all caps).

`state.abb` is the builtin R data with the state abbreviations in alphabetical order, so it hardcodes the sales taxes, finds the index of the state, calculates the sales tax, and formats to 2 decimal places (output as a string).

Try it online!
> 5 votes

# Answer
# Java 8, ~~486~~ ~~467~~ ~~309~~ ~~299~~ ~~290~~ 289 bytes

```
s->a->{float r=6;for(String x:"AKDENHORMT0 CO2.9 ALGANYHIWY4 MO4.23 VA4.3 SDOK4.5 NV4.6 UT4.7 NC4.75 LANDWI5 NM5.13 MENE5.5 AZ5.6 OH5.75 ILMATX6.25 CT6.35 ARKSWS6.5 MN6.875 NJ6.88 MSRINTN7".split(" "))if(x.contains(s))r=new Float(x.replaceAll("[A-Z]",""));return s.format("%.2f",a*r/100);}

```

-19 bytes thanks to *@MagicOctopusUrn* by removing the semicolons.

**Explanation:**

Try it here.

```
s->a->                    // Method with String and float parameters and String return-type
  float r=6;              //  Float starting at 6 (most states had 6.00 as tax)
  for(String x:"...".split(" "))
                          //  Loop over all states + amounts
    if(x.contains(s))     //   If the input-state is found in String `x`:
      r=new Float(x.replaceAll("[A-Z]",""));
                          //    Set float `r` to the amount of this state
                          //  End of loop (implicit / single-line body)
  return s.format("%.2f", //  Return result rounded to 2 decimal points:
     a*r/100);            //   Float input multiplied by `r` divided by 100
}                         // End of method

```
> 3 votes

# Answer
# Java (OpenJDK 8), ~~594 + 19~~ ~~592~~ ~~580~~ ~~575~~ 412 bytes

```
s->a->{float[]r={0};java.util.Arrays.asList("AL4`AK0`AZ5.6`AR6.5`CA6`CO2.9`CT6.35`DE0`FL6`GA4`HI4`ID6`IL6.25`IN7`IA6`KS6.5`KY6`LA5`ME5.5`MD6`MA6.25`MI6`MN6.875`MS7`MO4.23`MT0`NE5.5`NV4.6`NH0`NJ6.88`NM5.13`NY4`NC4.75`ND5`OH5.75`OK4.5`OR0`PA6`RI7`SC6`SD4.5`TN7`TX6.25`UT4.7`VT6`VA4.3`WS6.5`WV6`WI5`WY4".split("`")).forEach(e->{if(e.contains(s))r[0]=a/100*new Float(e.substring(2));});return s.format("%.2f",r[0]);}

```

Try it online!
> 3 votes

# Answer
## Pyth, ~~270~~ ~~258~~ ~~233~~ 219 bytes

```
*c@[6Z5.75K6.25 5.5 5 4Z7 6.5J6 7J6.875 7 4J6.35Z6 7 5 4.75 4 4.23J5J5.13 4.6JJ4J4 4.3 4.5Z5.6J.5 4.7K4.5KZ6.5 6.88 5.5J2.9)xc."AZ-íâFT34r7²¨cK'ÉT?Ú5Ï)}4Që7ËÅÖpuªXTiÖ¶7×ìÉÍ¨."2w100

```

Must be passed parameters like so:

```
1025
CA

```

Explanation:

```
*c@[...)xc."..."2w100
          ."..."       Decompress the string
         c      2      Cut the string in chunks of size 2 (states abbreviations)
        x        w     Get the index of the second parameter in that string
  @[    )              Index into the tax array
 c                100  Generate a percentage
*                      Multiply that with the implicit input at the end
Alas, `.Z` makes this longer. Maybe there's a way to write the array more efficiently, by repeating the keys, but I havn't found one yet.

```

Thanks to @Mr.Xcoder.
> 3 votes

# Answer
## Perl 6, 341 bytes

```
my%a=((<ME NE>X=>5.5),CO=>2.9,MO=>4.23,MN=>6.875,NJ=>6.88,(<LA ND WI>X=>5),(<AK DE MT NH OR>X=>0),(<IN MS RI TN>X=>7),(<AR KS WS>X=>6.5),AZ=>5.6,(<AL GA HI NY WY>X=>4),VA=>4.3,UT=>4.7,(<IL MA TX>X=>6.25),(<CA FL ID IA KY MD MI PA SC VT WV>X=>6),(<OK SD>X=>4.5),NV=>4.6,NM=>5.13,CT=>6.35,OH=>5.75,NC=>4.75).flat;{round $^a*(%a{$^b}/100),0.01}

```

So, huh. This is pretty contrived, I guess. This uses Perl 6's meta-operators, like `X=>` here, which is `X` (cross product) combined with `=>`.

That means `<ME NE> X=> 5.5` (where `<ME NE>` means `('ME', 'NE')`) gets `=> 5.5` applied on each element of the array, yielding `ME => 5.5, NE => 5.5`. The parentheses are merely here for precedence...

---

As a golfer (erm...), I obviously didn't write that one by hand (except the actual function). So I wrote a meta-golfer to generate the most efficient combination!

```
my %values;
my %simple;
for lines() {
  my $abb = m/<[A .. Z]> ** 2/.Str;
  my $val = m/\d\.\d+/.Str;
  %values{$val}.push: $abb;
  %simple{$abb} = $val;
}

say "(", (join ',', do for %values.kv -> $key, @vals {
  my $int-key = +$key;
  if @vals > 1 {
    "(<{@vals}>X=>$int-key)"
  } else {
    "{@vals}=>$int-key"
  }
}), ").flat";

say();

say join ',', do for %simple.kv -> $key, $val {
  "$key=>" ~ +$val
}

```

It generates both the `X=>` cases and the more simple case (with each one being enumerated), and I picked the shortest one (the former).
> 2 votes

# Answer
# JavaScript (ES6), ~~227~~ 224 bytes

Takes input in currying syntax `(s)(v)` where ***s*** is the state and ***v*** is the amount. Uses floor rounding.

```
s=>v=>(v*(p=s=>parseInt(s,36))('3344bk50k4mo28k4we4tm5eg3uw48s5az39i3js5b43yi3ny4fq3h03mk3bg'.substr(p('k039017k00038f00030022h00g000j00k600k080k707h30706800ba0030305ic0303303930460000e00d2'[p(s)*84%943%85])*3,3))/1e3|0)/100

```

### Demo

```
let f =

s=>v=>(v*(p=s=>parseInt(s,36))('3344bk50k4mo28k4we4tm5eg3uw48s5az39i3js5b43yi3ny4fq3h03mk3bg'.substr(p('k039017k00038f00030022h00g000j00k600k080k707h30706800ba0030305ic0303303930460000e00d2'[p(s)*84%943%85])*3,3))/1e3|0)/100

console.log(f("CA")(1025))
console.log(f("MN")(123.45))
```
> 2 votes

# Answer
# Kotlin, 444 bytes

```
val S="0|AK|DE|MT|NH|OR#2.9|CO#4|AL|GA|HI|NY|WY#4.23|MO#4.3|VA#4.5|OK|SD#4.6|NV#4.7|UT#4.75|NC#5|LA|ND|WI#5.13|NM#5.5|ME|NE#5.6|AZ#5.75|OH#6|CA|FL|ID|IA|KY|MD|MI|PA|SC|VT|WV#6.25|IL|MA|TX#6.35|CT#6.5|AR|KS|WS#6.875|MN#6.88|NJ#7|IN|MS|RI|TN"
fun c(t:String,d:Double){
val m=mutableMapOf<String,Double>()
S.split("#").map{val s=it.split("|")
for (item in s.subList(1, s.size))m.put(item, s[0].toDouble())}
System.out.printf("%.2f", m[t]!!*d*.01)}

```

Try it online!

## Beautified

```
// Tax rate followed by states with that rate separated by pipes, with hashes in between
val STATES="0|AK|DE|MT|NH|OR#2.9|CO#4|AL|GA|HI|NY|WY#4.23|MO#4.3|VA#4.5|OK|SD#4.6|NV#4.7|UT#4.75|NC#5|LA|ND|WI#5.13|NM#5.5|ME|NE#5.6|AZ#5.75|OH#6|CA|FL|ID|IA|KY|MD|MI|PA|SC|VT|WV#6.25|IL|MA|TX#6.35|CT#6.5|AR|KS|WS#6.875|MN#6.88|NJ#7|IN|MS|RI|TN"

fun function(targetState: String, amount: Double) {
    // Stores data
    val m = mutableMapOf<String, Double>()
    // For each rate
    STATES.split("#").map {
        // Split the data out
        val rateData = it.split("|")
        // For each state with that rate
        for (stateCode in rateData.subList(1, rateData.size)) {
            // Put it in the dataset
            m.put(stateCode, rateData[0].toDouble())
        }
    }

    // Print out the tax rate
    System.out.printf("%.2f", m[targetState]!! * amount * .01)
}

```
> 1 votes

# Answer
# Python 3, 303 bytes

```
import re
t=re.split("(\d+)","AL4AK0AZ56AR65CA6CO29CT635DE0FL6GA4HI4ID6IL625IN7IA6KS65KY6LA5ME55MD6MA625MI6MN6875MS7MO423MT0NE55NV46NH0NJ688NM513NY4NC475ND5OH575OK45OR0PA6RI7SC6SD45TN7TX625UT47VT6VA43WS65WV6WI5WY4")
f=lambda s,a:"%.2f"%({t[i-1]:float(t[i])/10**-~len(t[i])for i in range(1,len(t),2)}[s]*a)

```

Try it online!

Very simple: the data is stored data as two chars + list of digits: every percentage is less than 10, thus it can be stored as integer part (1 digit) + decimal part (0-... digit(s)).
> 1 votes

# Answer
## C#, ~~318~~ 309 bytes

---

### Data

* **Input** `String` `s` The 2 letter abbreviation of the state uppercase.
* **Input** `Double` `v` The value
* **Output** `String` The tax value to be collected rounded to 2 decimal places

---

### Golfed

```
(s,v)=>{for(int i=0;i<21;i++)if("NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split(',')[i].Contains(s))return $"{v*(new[]{0,2.9,4,4.23,4.3,4.5,4.6,4.7,4.75,5,5.13,5.5,5.6,5.75,6,6.25,6.35,6.5,6.875,6.88,7}[i]/100):F2}";return "";};

```

---

### Ungolfed

```
( s, v ) => {
    for( int i = 0; i < 21; i++ )
        if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) )
            return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}";
    return "";
};

```

---

### Ungolfed readable

```
// Takes a 2 letter abbreviation state ( 's' ) and a value ( 'v' )
( s, v ) => {

    // Cycles through an array with the states grouped by tax value
    for( int i = 0; i < 21; i++ )

        // Checks if the state group at the current index contains the state 's'
        if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) )

            // Returns the value 'v' * the corresponding state percentage divided by 100
            return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}";

    // If the state isn't found, return an empty string
    return "";
};

```

---

### Full code

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBench {
    public static class Program {
        private static Func<String, Double, String> f = ( s, v ) => {
            for( int i = 0; i < 21; i++ )
                if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) )
                    return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}";
            return "";
        };

        static void Main( string[] args ) {
            List<KeyValuePair<String, Double>>
                testCases = new List<KeyValuePair<String, Double>>() {
                    new KeyValuePair<String, Double>( "CA", 1025.0d ),
                    new KeyValuePair<String, Double>( "MN", 123.45d ),
                };

            foreach( KeyValuePair<String, Double> testCase in testCases ) {
                Console.WriteLine( $" STATE: {testCase.Key}\n VALUE: {testCase.Value}\nOUTPUT: {f( testCase.Key, testCase.Value )}\n" );
            }

            Console.ReadLine();
        }
    }
}

```

---

### Releases

* **v1.0** \- `318 bytes` \- Initial solution.
* **v1.1** \- `- 9 bytes` \- Changed the `.ToString("F2")` used in the first return to interpolated strings.

---

### Notes

* None
> 1 votes

# Answer
# AWK, 277 bytes

```
{split("LANDWI 5 VA 4.3 IACAFLIDKYMDMIPASCVTWV 6 SDOK 4.5 MO 4.23 CO 2.9 NM 5.13 NV 4.6 UT 4.7 NJ 6.88 MENE 5.5 AZ 5.6 ARKSWA 6.5 MN 6.875 MSINRITN 7 ILMATX 6.25 NC 4.75 CT 6.35 ALGANYWYHI 4 OH 5.75 AKDEMTORNH 0",T)
for(i in T)if(T[i]~s=".*"$1".*")printf"%.2f\n",$2*T[i+1]*.01}

```

Try it online!

A respectable score, but nowhere near Mathematica. I did add 2 bytes by having a newline print after each check, but I think it's prettier that way :)

(Hopefully it's obvious that input should be the state abbreviation and a value on one line. )
> 0 votes

---
Tags: code-golf, arithmetic, compression
---


title: Implement Anyfix Notation!

text:
# Question
Title: Implement Anyfix Notation!
In prefix notation, the operator comes before the arguments, so you can kind of imagine that the operator calls `next()` which is recursively called. In infix notation, the operator goes between the arguments, so you can imagine it simply as a parse tree. In postfix notation, the operator comes after the arguments, so you can just imagine it as stack-based.

In anyfix notation, the operator can go anywhere*. If an operator shows up and there aren't enough arguments, then the operator waits until there are enough arguments. For this challenge, you are to implement a very basic anyfix evaluator. (Note that anyfix is a recreational language that I abandoned that you can play around with here or check out here)

You will need to support the following commands:

### (Arity 1)

* duplicate
* negative

### (Arity 2)

* addition
* multiplication
* equality: returns `0` or `1`.

You may choose to use any five non-whitespace symbols for these commands. For demonstrational purposes, I will use `"` as duplicate, `×` as multiplication, and `+` as addition.

For literals, you only need to support non-negative integers, but your interpreter must be able to contain all integers (within your language's (reasonable) integer range).

Let's take a look at an example: `10+5`. The storage should behave as a stack, not a queue. So first, the stack starts at `[]`, and the queued operator list starts at `[]`. Then, the literal `10` is evaluated which makes the stack `[10]`. Next, the operator `+` is evaluated, which requires two arguments. However, there is only one argument on the stack, so the queued operator list becomes `['+']`. Then, the literal `5` is evaluated which makes the stack `[10, 5]`. At this point, the operator `'+'` can be evaluated so it is, making the stack `[15]` and the queue `[]`.

The final result should be `[15]` for `+ 10 5`, `10 + 5`, and `10 5 +`.

Let's take a look at a harder example: `10+"`. The stack and queue start as `[]` and `[]`. `10` is evaluated first which makes the stack `[10]`. Next, `+` is evaluated, which doesn't change the stack (because there are not enough arguments) and makes the queue `['+']`. Then, `"` is evaluated. This can run immediately so it is, making the stack `[10, 10]`. `+` can now be evaluated so the stack becomes `[20]` and the queue `[]`. The final result is `[20]`.

What about order of operations?

Let's take a look at `×+"10 10`. The stack and queue start both as `[]`:

* `×`: The stack is unchanged and the queue becomes `['×']`.
* `+`: The stack is unchanged and the queue becomes `['×', '+']`.
* `"`: The stack is unchanged and the queue becomes `['×', '+', '"']`.
* `10`: The stack becomes `[10]`. Even though `×` should be the first operator to be evaluated since it appears first, `"` can run immediately and none of the operators before it can, so it is evaluated. The stack becomes `[10, 10]` and the queue `['×', '+']`. `×` can now be evaluated, which makes the stack `[100]` and the queue `['+']`.
* `10`: The stack becomes `[100, 10]`, which allows `+` to be evaluated. The stack becomes `[110]` and the queue `[]`.

The final result is `[110]`.

The commands used in these demonstrations are consistent with that of the anyfix language; however, the last example will not work due to a bug in my interpreter. (Disclaimer: Your submissions will not be used in the anyfix interpreter)

# Challenge

Select a set of 5 non-whitespace non-digit characters and create an anyfix interpreter according to the specifications above. Your program can either output the singular array or the value contained by it; it is guaranteed that the stack of values will only contain a single value at the end of execution and that the queue of operators will be empty at the end of execution.

This is so the shortest code in bytes wins.

# Test Cases

For these test cases, duplicate is `"`, negative is `-`, addition is `+`, multiplication is `×`, and equality is `=`.

```
Input -> Output
1+2×3 -> 9
1"+"+ -> 4
2"××" -> 16
3"×+" -> 18
3"+×" -> 36
123"= -> 1 ("= always gives 1)
1+2=3 -> 1
1"=2+ -> 3
1-2-+ -> -3
-1-2+ -> 3 (hehe, the `-1` becomes `+1` at the `-` rather than making the `2` a `-1`)
+×"10 10 -> 200 (after the 10 is duplicated (duplication is delayed), 10 + 10 is performed and then 20 * 10, giving 200)

```

# Rules

* Standard Loopholes Apply
* You may take the anyfix official interpreter and golf it if you would like. Expect to lose horribly.

Input will be given as a string and output as an array, a single integer, out the string representation of either. You may assume that the input will only contain spaces, digits, and the 5 characters you choose.

* not actually

# Answer
# JavaScript (ES6), ~~204~~ ~~203~~ 200 bytes

Returns an integer.

```
e=>e.replace(/\d+|\S/g,v=>{for((1/v?s:v>','?u:b)[U='unshift'](v);!!u[0]/s[0]?s[U](u.pop()>'c'?s[0]:-S()):!!b[0]/s[1]?s[U](+eval(S(o=b.pop())+(o<'$'?'==':o)+S())):0;);},s=[],u=[],b=[],S=_=>s.shift())|s

```

Characters used:

* `+`: addition
* `*`: multiplication
* `#`: equality
* `d`: duplicate
* `-`: negative

### Test cases

```
let f =

e=>e.replace(/\d+|\S/g,v=>{for((1/v?s:v>','?u:b)[U='unshift'](v);!!u[0]/s[0]?s[U](u.pop()>'c'?s[0]:-S()):!!b[0]/s[1]?s[U](+eval(S(o=b.pop())+(o<'$'?'==':o)+S())):0;);},s=[],u=[],b=[],S=_=>s.shift())|s

;[ '10+5', '10+d', '*+d10 10', '1+2*3', '1d+d+', '2d**d', '3d*+d', '3d+*d', '123d#', '1+2#3', '1d#2+', '1-2-+', '-1-2+' ]
.forEach(e => console.log(e, '-->', f(e)))
```

### Formatted and commented

```
e => e.replace(                     // given an expression e, for each value v matching
  /\d+|\S/g, v => {                 // a group of digits or any other non-whitespace char.
    for(                            //   this loop processes as many operators as possible
      (                             //   insert v at the beginning of the relevant stack:
        1 / v ? s : v > ',' ? u : b //     either value, unary operator or binary operator
      )[U = 'unshift'](v);          //     (s[], u[] or b[] respectively)
      !!u[0] / s[0] ?               //   if there's at least 1 value and 1 unary operator:
        s[U](                       //     unshift into s[]:
          u.pop() > 'c' ?           //       for the duplicate operator:
            s[0]                    //         a copy of the last value
          :                         //       else, for the negative operator:
            -S()                    //         the opposite of the last value
        ) :                         //     end of unshift()
      !!b[0] / s[1] ?               //   if there's at least 2 values and 1 binary operator:
        s[U](                       //     unshift into s[]:
          +eval(                    //       the result of the following expression:
            S(o = b.pop()) +        //         the last value, followed by the
            (o < '$' ? '==' : o) +  //         binary operator o with '#' replaced by '=='
            S()                     //         followed by the penultimate value
          )                         //       end of eval()
        ) : 0;                      //     end of unshift()
    );                              //   end of for()
  },                                // end of replace() callback
  s = [],                           // initialize the value stack s[]
  u = [],                           // initialize the unary operator stack u[]
  b = [],                           // initialize the binary operator stack b[]
  S = _ => s.shift()                // S = helper function to shift from s[]
) | s                               // return the final result

```
> 6 votes

# Answer
# JavaScript (ES6), ~~162~~ ~~152~~ ~~143~~ 150 bytes

```
(s,N=s.replace(/(-?\d+)-|-(-)/g,'- $1 ').match(/(- ?)*?\d+|R/g))=>+eval(`R=${N[0]>'9'?N[1]:N[0]},${s.match(/[+*=]/g).map((o,i)=>'R=R'+o+'='+N[i+1])}`)

```

**Slightly ungolfed:**

```
(s,
 N=s.replace(/(-?\d+)-|-(-)/g,'- $1 ').      //change postfix negatives to prefix,
                                             //and change "--" to "- - "
     match(/(- ?)*?\d+|R/g)                  //grab numbers and duplicates
)=>+eval(`R=${N[0] > '9' ?  N[1] : N[0]},    //handle a delayed duplicate
          ${s.match(/[+*=]/g).               //grab the operators
              map((o,i)=>'R=R'+o+'='+N[i+1]) //create a comma-separated list of assignments
           }
         `)

```

**Explanation**

I'm using `*` for multiplication and `R` for duplicate. The other operators are the same as in the question.

`N` becomes the array of the numbers (including the duplicates).

The `replace` handles the case where the negative sign comes *after* the number. For example, it will change `1-` to `- 1`  and `-1-` to `- -1` .

Within the `eval`, `s.match` creates the array of binary operators. Note that this will always have one fewer elements than `N`.

The result of the function is the `eval` of the mapping of the numbers and operators.

Here is what is `eval`ed for each of the test cases:

```
0+2*3        R=0,R=R+=2,R=R*=3        = 6
1+2*3        R=1,R=R+=2,R=R*=3        = 9
1R+R+        R=1,R=R+=R,R=R+=R        = 4
2R**R        R=2,R=R*=R,R=R*=R        = 16
3R*+R        R=3,R=R*=R,R=R+=R        = 18
3R+*R        R=3,R=R+=R,R=R*=R        = 36
123R=        R=123,R=R==R             = 1
1+2=3        R=1,R=R+=2,R=R==3        = 1
1R=2+        R=1,R=R==R,R=R+=2        = 3
1-2-+        R=- 1,R=R+=- 2           = -3
-1-2+        R=1,R=R+=2               = 3
*+R10 10     R=10,R=R*=10,R=R+=10     = 110
+*R10 10     R=10,R=R+=10,R=R*=10     = 200
-1+--2       R=-1,R=R+=- -2           = 1
-1+-2        R=-1,R=R+=-2             = -3

```

The comma operator in a JavaScript expression returns the result of its last expression, so the `map` automatically returns a usable expression.

The `+` sign is needed before the `eval` to change `true` to `1` and `false` to `0`.

Using `R` as both the variable *and* the duplicate operator greatly simplifies the `map`'s sub-expressions.

**Test cases:**

```
let f=

(s,N=s.replace(/(-?\d+)-|-(-)/g,'- $1 ').match(/(- ?)*?\d+|R/g))=>+eval(`R=${N[0]>'9'?N[1]:N[0]},${s.match(/[+*=]/g).map((o,i)=>'R=R'+o+'='+N[i+1])}`)

console.log(f('1+2*3'))    // 9
console.log(f('1R+R+'))    // 4
console.log(f('2R**R'))    // 16
console.log(f('3R*+R'))    // 18
console.log(f('3R+*R'))    // 36
console.log(f('123R='))    // 1
console.log(f('1+2=3'))    // 1
console.log(f('1R=2+'))    // 3
console.log(f('1-2-+'))    // -3
console.log(f('-1-2+'))    // 3
console.log(f('*+R10 10')) //110
console.log(f('+*R10 10')) //200
console.log(f('-1+--2'));  // 1
console.log(f('-1+-2'));  // -3
```
> 3 votes

# Answer
# JavaScript, ~~321~~ 311 bytes

```
_="f=a=>(a.replace(/\\d+|./g,mq!~(b='+*=\"- '.indexOf(a))|b>2j3j4j5&&o+aw1/y?(y*=-1wcz:1/y?oywcz:hz,rql.map(z=>m(lki,1)[0],i)),hq1/s[1]?sk0,2,+eval(`y${a=='='?a+a:a}s[1]`)):cz,cqlki,0,a),s=[],l=[],e='splice'),s)z(a,i)ys[0]w)^r``:q=z=>os.unshift(k[e](j?b-";for(i of"jkoqwyz")with(_.split(i))_=join(pop());eval(_)

```

Try it online!

The five characters are the same as in the question, except `*` is for multiplication.
The script is compressed using RegPack. The original script is stored in the variable `_` after evaluation.
> 2 votes

# Answer
# 6502 machine code (C64), 697 bytes

```
00 C0 A2 00 86 29 86 26 86 27 86 28 86 4B 86 4C 86 CC 20 E4 FF F0 FB C9 0D F0
10 C9 20 30 F3 A6 27 9D B7 C2 20 D2 FF E6 27 D0 E7 C6 CC A9 20 20 1C EA A9 0D
20 D2 FF 20 95 C0 20 09 C1 20 95 C0 A6 26 E4 27 F0 4E BD B7 C2 E6 26 C9 20 F0
E8 C9 2D D0 09 A6 4C A9 01 9D B7 C3 D0 32 C9 22 D0 09 A6 4C A9 02 9D B7 C3 D0
25 C9 2B D0 09 A6 4C A9 81 9D B7 C3 D0 18 C9 2A D0 09 A6 4C A9 82 9D B7 C3 D0
0B C9 3D D0 0D A6 4C A9 83 9D B7 C3 E6 28 E6 4C D0 A3 4C 8A C2 A6 29 F0 6F A4
28 F0 6B CA F0 4B C6 28 A6 4B E6 4B BD B7 C3 F0 F5 30 14 AA CA D0 0B 20 7B C2
20 E1 C1 20 4D C2 D0 D9 20 5C C2 D0 D4 29 0F AA CA D0 0B 20 6D C2 20 08 C2 20
4D C2 D0 C3 CA D0 0B 20 6D C2 20 16 C2 20 4D C2 D0 B5 20 6D C2 20 F4 C1 20 4D
C2 D0 AA A4 4B B9 B7 C3 F0 02 10 AC C8 C4 4C F0 0F B9 B7 C3 F0 F6 30 F4 AA A9
00 99 B7 C3 F0 A6 60 A0 00 A6 26 E4 27 F0 15 BD B7 C2 C9 30 30 0E C9 3A 10 0A
E6 26 99 37 C4 C8 C0 05 D0 E5 C0 00 F0 08 A9 00 99 37 C4 20 39 C2 60 A2 FF E8
BD 37 C4 D0 FA A0 06 88 CA 30 0A BD 37 C4 29 0F 99 37 C4 10 F2 A9 00 99 37 C4
88 10 F8 A9 00 8D 3D C4 8D 3E C4 A2 10 A0 7B 18 B9 BD C3 90 02 09 10 4A 99 BD
C3 C8 10 F2 6E 3E C4 6E 3D C4 CA D0 01 60 A0 04 B9 38 C4 C9 08 30 05 E9 03 99
38 C4 88 10 F1 30 D2 A2 06 A9 00 9D 36 C4 CA D0 FA A2 10 A0 04 B9 38 C4 C9 05
30 05 69 02 99 38 C4 88 10 F1 A0 04 0E 3D C4 2E 3E C4 B9 38 C4 2A C9 10 29 0F
99 38 C4 88 10 F2 CA D0 D6 C0 05 F0 06 C8 B9 37 C4 F0 F6 09 30 9D 37 C4 E8 C8
C0 06 F0 05 B9 37 C4 90 F0 A9 00 9D 37 C4 60 A9 FF 45 FC 85 9F A9 FF 45 FB 85
9E E6 9E D0 02 E6 9F 60 A2 00 86 9F A5 FB C5 FD D0 07 A5 FC C5 FE D0 01 E8 86
9E 60 A5 FB 18 65 FD 85 9E A5 FC 65 FE 85 9F 60 A9 00 85 9E 85 9F A2 10 46 FC
66 FB 90 0D A5 FD 18 65 9E 85 9E A5 FE 65 9F 85 9F 06 FD 26 FE CA 10 E6 60 20
33 C1 A6 29 AD 3D C4 9D 3F C4 AD 3E C4 9D 3F C5 E6 29 60 A6 29 A5 9E 9D 3F C4
A5 9F 9D 3F C5 E6 29 60 A6 29 BD 3E C4 9D 3F C4 BD 3E C5 9D 3F C5 E6 29 60 C6
29 A6 29 BD 3F C4 85 FD BD 3F C5 85 FE C6 29 A6 29 BD 3F C4 85 FB BD 3F C5 85
FC 60 A6 29 BD 3E C5 10 13 20 7B C2 20 E1 C1 20 4D C2 A9 2D 20 D2 FF A6 29 BD
3E C5 8D 3E C4 BD 3E C4 8D 3D C4 20 8B C1 A9 37 A0 C4 4C 1E AB

```

**Online demo**

**Usage** `sys49152`, then enter the anyfix expression and press return.

* close to no error checking, so expect funny outputs on invalid expressions.
* the symbol for multiplication is `*`, all others as suggested.
* maximum input length is 256 characters, there can be no more than 127 operators queued.
* The input routine **doesn't** handle control characters, so don't mistype ;)
* integers are 16bit signed, overflow will silently wrap around.
* byte count is a bit large because this CPU doesn't even know multiplication and the C64 OS / ROM doesn't give you **any** integer arithmetics or conversions to/from decimal strings.

Here's the readable ca65-style assembler source code.
> 2 votes

# Answer
# Haskell, 251 bytes

```
(#([],[]))
(x:r)#(o,n)|x>'9'=r#h(o++[x],n)|[(a,t)]<-lex$x:r=t#h(o,read a:n)
_#(o,n:_)=n
h=e.e
e(o:s,n:m:r)|o>'N'=e(s,g[o]n m:r)
e(o:s,n:r)|o=='D'=e(s,n:n:r)|o=='N'=e(s,-n:r)
e(o:s,n)|(p,m)<-e(s,n)=(o:p,m)
e t=t
g"a"=(+)
g"m"=(*)
g"q"=(((0^).abs).).(-)

```

Try it online! Uses the following characters: `a` for addition, `m` for multiplication, `q` for equality, `D` for duplicate and `N` for negation. (I wanted to use `e` for equality, but ran into the problem that `lex` parses `2e3` as a number.) Example usage: `(#([],[])) "2a3 4m"` yields `20`.
> 1 votes

# Answer
# VB.NET (.NET 4.5) ~~615~~ 576 bytes

*-39 bytes thanks to Felix Palmen by changing `\r\n` to `\n`*

Requires `Imports System.Collections.Generic` (included in byte count)

```
Dim s=New Stack(Of Long),q=New List(Of String),i=Nothing,t=0,c=0
Function A(n)
For Each c In n
If Long.TryParse(c,t)Then
i=i &"0"+t
Else
If c<>" "Then q.Add(c)
If i<>A Then s.Push(i)
i=A
End If
If i=A Then E
Next
If i<>A Then s.Push(i)
E
A=s
End Function
Sub E()
c=s.Count
If c=0Then Exit Sub
For Each op In q
If op="-"Or op="d"Or c>1Then
Select Case op
Case"*"
s.Push(s.Pop*s.Pop)
Case"+"
s.Push(s.Pop+s.Pop)
Case"="
s.Push(-(s.Pop=s.Pop))
Case"-"
s.Push(-s.Pop)
Case"d"
s.Push(s.Peek)
End Select
q.Remove(op)
E
Exit Sub
End If
Next
End Sub

```

The entry point is Function `A`, which takes a string as input and returns a `Stack(Of Long)`.

Symbols:

* Addition - `+`
* Multiplication - `*`
* Equality - `=`
* Negation - `-`
* Duplication - `d`

Overview:

Function `A` takes the input and tokenizes it. It uses a `Long?` to do a running total for multi-digit integers, which `Nothing` signifying we are not currently reading an integer.

Subroutine `E` takes the stack of integers and queue of operators, and evaluates the anyfix notation. It calls itself recursively until there are no actions left.

I declare global params all at once to save bytes on both declaration and parameter passing.

The return value from `A` is set by assigning a value to the matching variable `A`.

VB `True` is equivalent to `-1`, so that operation has to negate the result to get the correct value.

Try it online!
> 1 votes

---
Tags: code-golf, string, interpreter
---


# Question
Title: Max power of 2 such that 2^m divides n. (The ruler sequence)
### Input:

A positive integer **N**.

### Challenge:

Suppose you have a list of integers **n = 1, 2 ... N**. Output a list of integers, where each number is the maximum power of 2, **m**, such that **2^m** divides each number of **n**.

---

Test cases:

```
1
0

15
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0

100
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2

```

This is OEIS A007814.

# Answer
> 10 votes
# Python 2, 46 bytes

Saved a couple of bytes thanks to nwellnhof.

```
lambda k:[len(bin(t+1&~t))-3for t in range(k)]

```

Try it online!

---

**Python 2, 51 bytes**

```
lambda k:[len(bin(t-~-(t&-~t)))-3for t in range(k)]

```

Try it online!

# How?

The formula for **a(k)** is **log2(k - (k & (k - 1)))**. That's quite fluffy, but fortunately it can be shortened significantly. In Python, **floor(log2(N)) = len(bin(N)) - 3**, because `bin()` appends `0b` to the binary representation of an integer. As a side note, `len(bin(N))-3` can be replaced by `N.bit_length()-1`, but that is not really beneficial for golfing purposes. That gives us the opportunity to get rid of the `import math` and the use of `math.log`. Another part that can be shortened is **k & (k-1)**. Using more bitwise operations, we get **k&~-k** instead, and then we subtract this from the actual **k**. But that would make us iterate over the range **\[1, k\]**, which would waste bytes because Python lacks inclusive ranges. In order to save a few bytes, we iterate over the integers in **\[0, k)** instead and modify the formula, obtaining **k+1-(k&-~k) = k-~-(k&-~k)**. However, than can be simplified further to **k+1&~k** (as @nwellnhof pointed out).

# Answer
> 8 votes
# Pyth, 6 bytes

```
m/Pd2S

```

Try it online: Demonstration

### Explanation:

```
m/Pd2S
     S   range [1, 2, ..., input]
m        map each number to
 /  2       the count of two in
  Pd        its prime factorization

```

# Answer
> 6 votes
# Mathematica, 29 bytes

```
#~IntegerExponent~2&~Array~#&

```

Try it online!

# Answer
> 6 votes
# , ~~60~~ ~~59~~ ~~55~~ 40 bytes

```
n=1:scan();cat(log2(n-(bitwAnd(n,n-1))))

```

Reads from stdin, writes to stdout. Implements the formula referenced in Mr. Xcoder's solution, which fortunately vectorizes nicely in R.

Try it online!

# Answer
> 6 votes
# Haskell, 29 bytes

```
($l).take
l=0:do x<-l;[x+1,0]

```

Try it online!

Recursively generate the infinite list `l`.

# Answer
> 5 votes
# JavaScript (ES6), ~~42~~ 39 bytes

*Saved 3 bytes thanks to @Shaggy*

A straight-forward version using Math.clz32(). Returns a comma-delimited string.

```
f=n=>--n&&f(n)+[,31-Math.clz32(++n&-n)]

```

### Test cases

```
f=n=>--n&&f(n)+[,31-Math.clz32(++n&-n)]

console.log(f(1))
console.log(f(15))
console.log(f(100))
```

---

# Alternate version, ~~42~~ 41 bytes

*Saved 1 byte thanks to @Shaggy*

```
f=n=>--n&&f(n)+[,(g=n=>n&1&&1+g(n/2))(n)]

```

### How?

This is based on the recursive formula:

```
a(n) =
  0 if n is odd
  a(n / 2) + 1 if n is even

```

For golfing purposes, the function ***g*** is actually doing almost the opposite:

```
g(n) =
  g(n / 2) + 1 if the least significant bit of n is set
  0 if the least significant bit of n is clear

```

We do it that way because ***n*** has already been decremented when ***g*** is invoked, so it's off by 1. This generates floats, but testing the LSB rather than computing a modulo ensures that the decimal part is ignored.

The function ***f*** is just a wrapper that invokes ***g*** for all values from ***n - 1*** to ***1***, appending the results in reverse order, and eventually appending a leading ***0*** when the recursion stops.

### Test cases

```
f=n=>--n&&f(n)+[,(g=n=>n&1&&1+g(n/2))(n)]

console.log(f(1))
console.log(f(15))
console.log(f(100))
```

# Answer
> 5 votes
# C (gcc), ~~49~~ 44 bytes

```
f(n){n-1&&f(n-1);printf("%.f ",log2(n&-n));}

```

Try it online!

# Answer
> 5 votes
# x86 Machine Code, 10 bytes

```
0F BC C1
49
89 04 8A
75 F7
C3

```

The above bytes of machine code define a function that takes an array of length *n* as input, and then replaces the value at each index with the maximum power of 2, *m*, such that 2m divides each number of *n*. each number is the maximum power of 2, m, such that 2^m divides each number of n.

It follows the `__fastcall` register-based calling convention, passing the first parameter (the length of the array, *n*) in the `ECX` register and the second parameter (a pointer to the beginning of the array) in the `EDX` register. I posit that this is legal because, like C, arrays/lists are represented at the machine-code level as a pointer to the first element and a length.

As stipulated in the challenge, *n* is assumed to be a strictly positive integer.

**Ungolfed assembly mnemonics:**

```
                ; void RulerSequence(unsigned len, unsigned * pSequence);
                ;                                     ECX  = len
                ;                                     EDX  = pSequence
             Top:
0F BC C1        bsf   eax, ecx                      ; EAX  = log2(ECX)
49              dec   ecx                           ; ECX -= 1
89 04 8A        mov   DWORD PTR [edx+ecx*4], eax    ; pSequence[ECX] = EAX
75 F7           jnz   Top                           ; loop to 'Top' if ECX != 0
C3              ret

```

As you can see, the logic is embarrassingly simple. The only thing even slightly tricky is the use of the `BSF` instruction, which obtains the index of the least-significant set bit. This is the shortest and fastest way to compute log2(n).

**Try it online!**

---

**Bonus alternate solution, also 10 bytes**

```
                ; void RulerSequence_Alt(unsigned len, unsigned * pSequence);
                ;     ECX = len
                ;     EDX = pSequence
             Top:
0F BC C1        bsf   eax, ecx
89 44 8A FC     mov   DWORD PTR [edx+ecx*4-4], eax
E2 F7           loop  Top
C3              ret

```

Instead of separate `DEC`+`JNZ` instructions, we use the long-obsolete CISC-style `LOOP` instruction, which decrements `ECX` and loops to the specified label as long as `ECX` != 0. `LOOP` takes the same 2 bytes to encode as `JNZ`, so this saves us 1 byte from `DEC`. However, to compensate for the decrement being done *after* the array offset calculation, we need to add an additional subtraction to the indexing, which costs us an additional byte. So it's a wash.

# Answer
> 4 votes
# Jelly, 5 bytes

```
RÆEḢ€

```

Try it online!

\*Saved 1 byte thanks to miles!

Definitely not as short as the built-in answer with *Order, multiplicity, valuation*, but I think it's worth it posting.

# How?

```
RÆEḢ€  - Full program.

R      - The range [1, input].
 ÆE    - Compute the array of exponents of the prime factorization, including 0's.
    €  - For €ach.
   Ḣ   - Head.
       - Implicitly output the result.

```

# Answer
> 4 votes
# Husk, 6 bytes

```
†#2†pḣ

```

Try it online!

# How?

It's my first "non-trivial" attempt in Husk, so patient with me :-)

```
†#2†pḣ   - Full program.

     ḣ   - The range [1, input].
   †p    - Map with prime factorisation.
†#2      - Count the 2's in each.
         - Implicitly output.

```

Alternative, suggested by Erik the Outgolfer: `m#2mpḣ`.

# Answer
> 4 votes
# C, 48 bytes

Using GCC's builtin to count trailing zeros:

```
f(v,n)int*v;{while(n--)v[n]=__builtin_ctz(n+1);}

```

Input in integer `n`, and output to the supplied array `v` (which must be at least `n` long).

## Test program:

```
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv) {
        int n = atoi(*argv);
        if (n>0) {
            int *v = malloc(sizeof *v * n);
            if (!v) continue;
            f(v,n);
            printf("\n%d:\n", n);
            for (int i = 0;  i < n;  ++i)
                printf("%d ", v[i]);
            free(v);
            puts("");
        }
    }
}

```

# Answer
> 3 votes
# Jelly, 3 bytes

```
ọ€2

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~86 + 26~~ ~~75~~ ~~81~~ ~~79~~ ~~77~~ ~~76~~ 74 bytes

```
n->{for(int i=0;i<n;System.out.println(n.toString(++i&-i,2).length()-1));}

```

Try it online!

# Answer
> 3 votes
# Octave, ~~42~~ 37 bytes

*5 bytes removed thanks to @StewieGriffin!*

```
@(n)([~,y]=max(mod(x=1:n,2.^x')>0))-1

```

**Try it online!**

### Explanation

Let `n` be the input. The code computes each number `k` in the range `1`, ..., `n` modulo each number `d` in `1`, `2`, `4`, ..., `2^n`. This gives an `n`×`n` matrix, where `k` is the column index and each `d` corresponds to a row.

This matrix is compared for inequality with 0. As a result, nonzeros are transformed into `1`, and zeros remain as `0`.

For each column `k`, finding the (1-based) row index of the maximum value and subtracting 1 gives the solution. In other words, the number of initial zeros in each column is the desired `m` for each `k`.

# Answer
> 3 votes
# Pari/GP, 29 bytes

```
n->[valuation(x,2)|x<-[1..n]]

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 5 bytes

Patched a bug thanks to Emigna (`Ý` -\> `L`).

```
LÒε2¢

```

Try it online!

# How?

```
LÒε2¢   - Full program.

L       - The range [1, input].
 Ò      - Prime factors with duplicates.
  ε     - For εach.
   2¢   - Count the 2's.
        - Output (implicitly).

```

Alternative:

```
LεÒ2¢

```

# Answer
> 3 votes
# Japt, 7 bytes

A port of Jakube's solution.

```
õ_k è¶2

```

Try it

---

## Explanation

Implicit input of integer `U`.

```
õ_

```

Generate an array of integers from 1 to `U` and pass each through a function.

```
k

```

Get an array of the prime factors of the current element.

```
è¶2

```

Count (`è`) the number of elements that are strictly equal to () 2.

# Answer
> 3 votes
# Retina, 34 bytes

```
.+
$*
\B1
¶$`1
+`(1+)\1
$+0
%r`0\G

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
\B1
¶$`1

```

Create a triangle.

```
+`(1+)\1
$+0

```

Start converting each row to base 2...

```
%r`0\G

```

...but instead of completing the conversion, just count the trailing zeros.

# Answer
> 3 votes
# Perl 6, ~~27~~ ~~17~~ 15 bytes

-2 bytes thanks to Brad Gilbert b2gills

```
{(1..$_)».lsb}

```

Try it online!

# Answer
> 2 votes
## Haskell, 36 bytes

```
a 0=[0]
a n|q<-a$n-1=q++n:q
take<*>a

```

An adaption of my answer from a similar challenge.

Try it online!

# Answer
> 1 votes
# Pyth, 9 bytes

```
msl-hd.&h

```

**Verify the test cases.**

If returning as floats was allowed, then **8 bytes**:

```
ml-hd.&h

```

# Explanation

```
msl-hd.&h  - Full program. Q means input.

m          - Map over the implicit range [0, Q) with a variable d.
 sl        - The integer part of logarithm base 2 of...
   -hd.&h  - ... The Logical OR between d and d + 1, subtracted from d + 1.
           - Output implicitly.

```

The formula for **a(k)** is **log2(k - (k & (k - 1)))**, if we were to work with **\[1, Q\]**. By mapping over **\[0, Q)** instead, we modify the formula accordingly, **log2(k + 1 - (k & (k + 1))**. This allows us to abuse implicit ranges at the end of the program.

# Pyth, 6 bytes

```
/R2PMS

```

An alternative to Jakube's approach.

```
/R2PMS   - Full program. Q means input.

     S   - The range [1, Q].
   PM    - Get prime factors of each.
/R2      - Count the number of 2's.

```

# Answer
> 0 votes
# Pyth, 10 bytes

```
mlec.Bd\1S

```

Try it here.

# Answer
> 0 votes
# Pyke, 5 bytes

Port of Jakube's Pyth answer, and my 05AB1E answer.

```
SFP2/

```

Try it here!

# How?

```
S     - The range [1, input]
 F    - For each.
  P   - Prime factors.
   2/ - Count the number of 2's.
      - Output implicitly.

```

# Answer
> 0 votes
# , 10 bytes

```
_{.@q:1+i.

```

Try it online!

## Explanation

```
_{.@q:1+i.  Input: n
        i.  Range, [0, n)
      1+    Add 1
_   q:      Exponents of each prime in the factorization of each
 {.@        Head each (Get the exponent of 2)

```

# Answer
> 0 votes
# Perl 50 + 2 bytes

```
perl -E'say+sprintf("%b",$_)=~s/.*1//r=~y===c for 1..shift'

```

50 bytes for the program proper, and 2 for the command line switch.

The largest m such that 2^m divides n is just the number of trailing 0s in the binary representation of n. We get the latter by removing everything up to the last 1 of the binary representation, and taking the length of that. `y===c` happens to do that (it replaces every character by itself, returning the number characters it replaced).

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


# Question
Title: Implement the Fibonacci sequence... Shifted to the right
# Background

We all know the famous Fibonacci sequence, where each term is the sum of the previous two, with the first term being `0` and the second one being `1`. The first few elements are:

```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765

```

What we are going to implement today is a similar sequence, starting at `0` and `1` as well, and each term is the sum of the previous two, but *the sum's digits* are shifted by one place to the right. **What does "shifted" mean?** – A digit shifted to the right is basically that digit + 1, unless it equals `9`, which maps to `0` instead. Just as a reference, here is the full list of mappings:

```
0 -> 1;  1 -> 2;  2 -> 3;  3 -> 4;  4 -> 5;  5 -> 6;  6 -> 7;  7 -> 8;  8 -> 9;  9 -> 0

```

---

With all that being said, these are the first terms of our Fibonacci-shifted sequence:

```
0, 1, 2, 4, 7, 22, 30, 63, 4, 78, 93, 282, 486, 879, 2476, 4466, 7053, 22620, 30784, 64515

```

Given an integer **N** (non-negative if 0-indexed and positive if 1-indexed), finds the **N**th term of the Fibonacci-shifted sequence.

# Rules

* The output may contain leading zero(es), in case `9` is the first (few) digit(s).
* Input and output can be handled using any **default mean**.
* Take note that **Loopholes** are forbidden.
* This is , hence your program will be scored in bytes, with *less* bytes being better.

# Answer
# Python 2, ~~78~~ 72 bytes

```
f=lambda n:n>1and int(''.join(`-~int(i)%10`for i in`f(n-1)+f(n-2)`))or n

```

Try it online!

Saved 6 bytes thanks to Halvard Hummel.
> 4 votes

# Answer
# Jelly, 9 bytes

```
ð+D‘%⁵Ḍø¡

```

Try it online!

-2 thanks to Dennis.

Explanation:

```
ð+D‘%⁵Ḍø¡ Full program. Takes input through STDIN.
ð         Start new dyadic chain
 +        Add the left (f(n - 1)) and right (f(n - 2)) arguments
  D       Get list of decimal digits
   ‘      Increment each
    %⁵    Modulo ⁵ (10)
      Ḍ   Convert from decimal to integer
       ø  Start new niladic chain
        ¡ Repeat previous chain z times (where z is taken from STDIN as there are no arguments)

```
> 3 votes

# Answer
# JavaScript (ES6), ~~63~~ 62 bytes

This is what I'd come up with before the challenge was deleted, don't have time to golf it further now.

Returns the `n`th number in the sequence, 0-indexed.

```
f=(n,x=0,y=1)=>n?f(--n,y,+[...x+y+""].map(z=>++z%10).join``):x

```
* 1 byte saved thanks to Conor.

Try it online

---

## Alternative, 55 bytes

A quick port of VoteToReopen's excellent Python solution.

```
f=n=>n>1?+[...f(--n)+f(--n)+""].map(x=>++x%10).join``:n

```

Try it online
> 3 votes

# Answer
# , 40 bytes

```
[`(-&2(10|>:)&.(10&#.inv)@+&$:<:)@.(1&<)

```

Try it online!

Highlighted following is the standard Fibonacci husk:

```
[`(-&2                    +&$:<:)@.(1&<)

```

Then, we compose the following function with the result of adding the previous two terms:

```
      (10|>:)&.(10&#.inv)@

```

This, in turn, is the function `10|>:` atop `10&#.inv`, which gets the digits of a number. That is to say, the digits are obtained, then the function `10|>:` is applied, then the digits are combined to make a number again. `10|>:` is a fork that is equivalent to `(y + 1) % 10` in a conventional language for input `y`.
> 1 votes

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


title: Totalling Troublesome T's

text:
# Question
Title: Totalling Troublesome T's
Given a "T" shape on an x * y number grid, with length W on the top bar and H on the stem of the T, with the bottom of the T on the square numbered n: calculate the total of all of the numbers in the T shape. W must be an odd number and all must be positive integers.

Here are some examples of valid T's on a 9\*9 grid:

Looking at the T where `n=32, W=3 & H=4`, you can see that the total is:
`4 + 5 + 6 + 14 + 23 + 32 = 84`.

# The Challenge

Your challenge is to create a program which, when given five positive integers, x, y, W, H and n, output the total of the T with those values (W must be odd, given an even number the program can output anything or even crash). The numbers may be inputted in any reasonable format. If the T does not fit on the given grid, then any output is acceptable.

# Example Code (Python 3.6.2)

```
x = int(input())
y = int(input())
W = int(input())
H = int(input())
n = int(input())

total = 0

#"Stem" of the T
for i in range(H - 1):
    total += n - (x * i) #Decrease increment by length of row each time

#Top of the T
for i in range(-W//2 + 1, W//2 + 1): #Iterate over the width offset so that the center is zero
    total += (n - (x * (H - 1))) + i #Add the top squares on the T, one less to the left and one more to the right

print(total)

```

As with most challenges here this is , so the answer with the shortest code in bytes wins.

# Answer
# Jelly, 10 bytes

A construction technique, which ends up much like Luis Mendo's MATL answer

```
Ḷ×ạ⁵µṪ×⁶+S

```

A full program taking `H`, `x`, `n`, `W` in that order (`y` may be appended if one so wishes).

**Try it online!**

### How?

```
Ḷ×ạ⁵µṪ×⁶+S - Main link: H, x
Ḷ          - lowered range                         [0,1,2,...,H-2,H-1]
 ×         - multiply (vectorises)                 [0,x,2x,...,(H-2)x,(H-1)x]
   ⁵       - program's 5th argument (3rd input)    n
  ạ        - absolute difference (vectorises)      [n,n-x,n-2x,...,n-(H-2)x,n-(H-1)x]
           -  (note: for an in-range T n>(H-1)x)   (cells of the stem)
    µ      - monadic chain separation (call this stem)
     Ṫ     - tail (pop from AND modify stem)       n-(H-1)x
           -                                       (cell at intersection of stem and top)
       ⁶   - program's 6th argument (4th input)    W
      ×    - multiply                              Wn-W(H-1)x
           -                                       (total value of the top)
         S - sum (the modified stem)               n+n-x+n-2x+...+n-(H-2)x
           -                                       (total value of the stem w/o top cell)
        +  - add (add top to the stem w.o top cell)

```
> 0 votes

# Answer
## JavaScript (ES6), ~~32~~ 30 bytes

*Saved 2 bytes thanks to @Shaggy*

```
(w,h,x)=>Q=n=>--h?n+Q(n-x):n*w

```

Takes input in a curried format: `f(W,H,x,y)(n)`

```
let f =
(w,h,x)=>Q=n=>--h?n+Q(n-x):n*w;

console.log(
  f(3, 4, 9, 9)(32)
);
```

### How?

First we note that the sum of the T starting at **n** with height **H** can be broken down into two sums:

* **n**
* The sum of the T starting one row higher with height **H - 1**

By repeatedly adding **n** to the total, moving one row up, and subtracting **1** from **H** until it reaches **1**, we end up summing the vertical stem of the T. Moving one row up is accomplished by subtracting **x** from **n**, since it can be observed that the difference between any cell and the one above is **x**.

When **H** reaches **1**, we now have only the crossbar of width **W** left to sum. At this point **n** represents the center of the crossbar. We *could* sum the crossbar recursively as we did with the stem, but instead we take advantage of a fairly simple formula:

```
sum(n - a : n + a) = (n - a) + (n - (a-1)) + ... + n + ... + (n + (a-1)) + (n + a)
                   = (n - a) + (n + a) + (n - (a-1)) + (n + (a-1)) + ... + n
                   = 2n + 2n + ... + n
                   = n * (2a + 1)

```

In this case, our **a** is **(W - 1) / 2**, which makes

```
n * (2a + 1) = n * (((W - 1) / 2) * 2 + 1)
             = n * ((W - 1) + 1)
             = n * W

```

which is the sum of the crossbar.
> 9 votes

# Answer
# C# (Visual C# Compiler), ~~64~~ 52 bytes

```
(x,y,W,H,n)=>{for(y=0;H-->1;n-=x)y+=n;return y+W*n;}

```

Try it online!

The non-recursive answer did indeed turn out significantly shorter. Gross misuse of for loops and the fact that `y` is officially a mandatory input even though it's not used.
> 5 votes

# Answer
# Python 3, 38 bytes

```
lambda x,W,H,n:~-H*(x*(1-H/2-W)+n)+W*n

```

Try it online!

-4 bytes thanks to Jonathan Allan
-4 bytes thanks to Kevin Cruijssen/Ayb4btu
> 2 votes

# Answer
# MATL, 12 bytes

```
:q*-t0)iq*hs

```

Inputs are: `H`, `x`, `n`, `W`.

**Try it online!**

### Explanation

```
:     % Implicit input: H. Push [1, 2, ..., H]
q     % Subtract 1. Gives [0, 1, ..., H-1]
*     % Implicit input: x. Multiply. Gives [0, x, ..., x*(H-1)]
-     % Implicit input: n. Subtract. Gives [n-0, n-x, ..., n-x*(H-1)]. This is
      % the stem, bottom to top
t     % Duplicate
0)    % Get last element, that is, n-x*(H-1). This is the center top of the "T"
i     % Input: W
q     % Subtract 1
*     % Multiply. Gives n-x*(H-1)*(w-1). This is the sum of the vertical bar
      % excluding its center, which is already accounted for in the stem
h     % Concatenate into a row vector
s     % Sum of vector. Implicit display

```
> 2 votes

# Answer
# Jelly,  ~~18 16~~  15 bytes

-1 byte thanks to Erik the Outgolfer (use of chain separator)

```
S’×⁵_ðc2Ḣ+⁸’P¤×

```

A full program taking `[H,W]`, `x`, `n` in that order (you can add `y` to the arguments if you like, it's not used).

**Try it online!**

### How?

The total is:

* `n` multiplied by the number of squares used in the **T** (which is `W+H-1`)
* minus the width of the grid, `x`, times the triangle number of the height (`1+2+3+...+h`) to account for the lack as we go up the stem
* minus the width of the grid, `x`, times one less that the height (`H-1`) times one less that the width (`W-1`) to account for the lack at the top of the **T**, excluding the lack we already accounted for at the top of the stem.

That is:

```
(W + H - 1) * n - ((H - 1) * (W - 1) + Triangle(H)) * x

```

The triangle number of `H` is its binomial with **2** A.K.A. `H-choose-2`.

```
c2Ḣ+⁸’P¤× - Link 1: the x * (Triangle(H) + (H-1)*(W-1)): [H,W]; x
S’×⁵_ðc2Ḣ+⁸’P¤× - Main link: [H,W], x
S               - sum                                    H+W
 ’              - decrement                              H+W-1
   ⁵            - program's fifth argument (3rd input)   n
  ×             - multiply                               (H+W-1)*n
     ð          - dyadic chain separation
      c2        - choose-2 (vectorises)                  [Triangle(H), Triangle(W)]
        Ḣ       - head                                   Triangle(H)
             ¤  - nilad followed by link(s) as a nilad:
           ⁸    -    chain's left argument               [H,W]
           ’    -    decrement (vectorises)              [H-1,W-1]
            P   -    product                             (H-1)*(W-1)
         +      - add                                    (H-1)*(W-1)+Triangle(H)
              × - multiply (by chain's right arg, x)     ((H-1)*(W-1)+Triangle(H))*x
    _           - subtract                               (H+W-1)*n-((H-1)*(W-1)+Triangle(H))*x

```
> 1 votes

# Answer
# Perl 5, 52 bytes

```
($x,$y,$w,$h,$n)=<>;say$h*($n+$x*(.5-$h/2-$w))+$w*$n

```

Try it online!
> 1 votes

# Answer
# Python 3, 38 bytes

```
lambda x,W,H,n:~-H*(n-x*(W-1+H/2))+n*W

```

Try it online!

HyperNeutrino's arithmetic expression with improved grouping.
> 1 votes

# Answer
# C# (.NET Core), 49 37 bytes

```
(x,y,W,H,n)=>~-H*(x*(1-H/2d-W)+n)+W*n

```

Try it online!

A direct formula avoiding the need for looping or recursion. Unfortunately I had to use `2d` otherwise it was going to do integer division and truncate the fractional component. The `y` param is completely redundant and could be removed.

### Explanation

```
(n-x*(H-1))*W             // Calculates the Top of the T

```

`(n-x*(H-1))` gets the cell index by subtracting from `n` the number of rows to go up multiplied by the grid width. Multiplying this by `W` gets the sum of the top bar of the T.

```
n*(H-1)-x*(H-2)*(H-1)/2   // Calculates the Stem of the T

```

I got this by using mathematical induction by trying to calculate the sum of *1, 10, 19, 28* where `n=28, H=4, x=9`. Which can be written as:

```
28 + (28-9) + (28-9-9) + (28-9-9-9)
28-9*0 + 28-9*1 + 28-9*2 + 28-9*3
28*4 -9*(0+1+2+3)
n*H -x*(1+2+3)
n*H -x*(3*(3+1)/2)
n*H -x*((H-1)*((H-1)+1)/2)
n*H -x*((H-1)*H/2)

```

but because we don't want to include the top cell of the stem (included in the formula for the Top of the T), `H` needs to be `H-1`. Making the formula

```
n*(H-1)-x*((H-2)*(H-1)/2)

```

Combining these two formulas gives

```
(n-x*(H-1))*W + n*(H-1)-x*((H-2)*(H-1)/2)

```

and simplifying it gives the formula used for the answer (though how it is rearranged can change how it looks).

### Acknowledgements

Saved 12 bytes thanks to Kevin Cruijssen. Though I'm not sure if the `;` should be included or not.
> 1 votes

# Answer
# Pyth, 23 bytes

```
+-*KEQ**JEQctQ2*tE-K*Jt

```

**Try it here!** (note the order of the inputs)

# How?

```
+-*KEQ**JEQctQ2*tE-K*Jt    Full program. Q is input, E is evaluated input (reads a new line)

  *KEQ                     The second input * the first input.
       *JEQ                The third input * the first input.
           ctQ2            Float division of the the first input decremented by 1, by 2.
      *                    Product.
 -                         Difference.
                tE         The fourth input.
                    *Jt    The product of the third input and the first input decremented by 1...
                 -K        ... Subtracted from the second input
               *           Product.
+                          Sum.
                           Output implicitly.

```
> 0 votes

# Answer
# Japt, 14 bytes

I tried a few different solutions based on ETH's observations but the shortest I've come up with (so far) is a straight port.

Takes input in the order `n,H,W,x`.

```
´V©ßXnU)+UªU*W

```

Try it
> 0 votes

# Answer
# Java 8, 35 bytes

```
(x,W,H,n)->~-H*(x*(1-H/2d-W)+n)+W*n

```

Port of *@Ayb4btu* .Net C# answer, after I golfed it a bit.

Try it here.

---

If `y` is a mandatory input-parameter, it will be **37 bytes** instead (Try it here):

```
(x,y,W,H,n)->~-H*(x*(1-H/2d-W)+n)+W*n

```

If outputting a double isn't allowed, it will be **40 bytes** instead (Try it here):

```
(x,W,H,n)->~-H*(x*(int)(1-H/2d-W)+n)+W*n

```

If having a function instead of a full program isn't allowed, it will be **160 bytes** instead (Try it here):

```
interface M{static void main(String[]a){Integer W=new Integer(a[2]),H=W.decode(a[3]),n=W.decode(a[4]);System.out.print(~-H*(W.decode(a[0])*(1-H/2d-W)+n)+W*n);}}

```
> 0 votes

# Answer
# Java (OpenJDK 8), ~~100~~ ~~99~~ ~~96~~ 91 bytes

```
x->W->H->n->{int t=n,i=0,j=-W/2;for(;++i<H;t+=n-x*i);for(;j<W/2;t+=n-x*~-H+j++);return-~t;}

```

Try it online!
> 0 votes

# Answer
# QBIC, 32 bytes

```
[0,:-1|i=:-(a*:)┘g=g+i}?i*:+g-i

```

This takes parameters in the order `h, n, x, w`, and `y` is ignored.

## Explanation

Each time a variable is read from the cmd line in QBIC, using the `:` command, it is assigned a letter (a-z). For clarity, I will use `h, n, x, w` in the explanation instead of the `b,c,d,e` they would be assigned (`a` gets taken by the FOR-loop).

```
First, we want to know the total of the stem
[0,h-1|     FOR a = 0 to the height - 1
  i=n-(a*x)     helper i holds an increment value: this is n, minus the
                grid-width once for every row we go up.
  g=g+i         helper g is incremented by i for each row
  }         NEXT
  ?         PRINT
   i*w          the center on the top bar times the width (ie the average)
   -i           corrected for that ione i we already counted in the stem
   +g           plus the stem itself

```
> 0 votes

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


title: Cooking with Code

text:
# Question
Title: Cooking with Code
You're a chef and you love cooking with your spices, but recently you've taken a liking to organizing your spices based on how often you use them. But you have no time to be writing down when you used your spice last. Simply, you swap and move spices around, and this seems to do the trick.

But of course you're a chef and that means you have some cooks with you. You decide to tell them the simple rules of engagement with your spices.

1. If you recently used a spice, move it up one in the spice rack
2. If you didn't use any spices at all, e.g. `[]` empty movement list, then the spice list is not affected.
3. You may put any spice into my spice holder, but if you use it, make sure to move it.
4. The list can contain anything. But because these are spices we are working with. It is preferred that you use names of spices.
5. Spices should be unique. Too many of the same spices spoil the broth... or however that saying goes

Normal code-golf rules apply.

### Example of Oregano being used again and again.

```
pepper  pepper  pepper  pepper  oregano
paprika paprika paprika oregano pepper
salt    salt    oregano paprika paprika
cumin   oregano salt    salt    salt
oregano cumin   cumin   cumin   cumin

```

## Task

Input a list of spices, and a list of what spices got used, then output the final list.

## Example

Input

```
[pepper, paprika, salt, cumin, oregano], [oregano, cumin, cumin, salt, salt, salt]

```

Output

```
[salt, pepper, paprika, cumin, oregano]

```

How this looks

```
pepper  pepper  pepper  pepper  pepper  pepper  salt
paprika paprika paprika paprika paprika salt    pepper
salt    salt    salt    cumin   salt    paprika paprika
cumin   oregano cumin   salt    cumin   cumin   cumin
oregano cumin   oregano oregano oregano oregano oregano

```

Input

```
[pepper, paprika, salt, cumin, oregano], [salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, oregano]

```

Output

```
[salt, pepper, paprika, oregano, cumin]

```

# Answer
# Husk, ~~15~~ 14 bytes

```
Fλṁ↔`C⁰tMo→=¢⁰

```

Inputs are lists of strings (it also works on other kinds of lists). Try it online!

-1 byte thanks to H.PWiz

## Explanation

```
Fλṁ↔`C⁰tMo→=¢⁰  Implicit inputs (two lists).
F               Fold second input using the first as initial value
 λ              with this anonymous function:
                 Arguments x (list of spices) and s (used spice).
                 For example, x=["a","b","c","d"] and s="c".
            ¢⁰   Repeat x infinitely: ["a","b","c","d","a","b","c","d"..
        M        For each item,
           =     test equality to s: [0,0,1,0,0,0,1,0..
         o→      and increment: [1,1,2,1,1,1,2,1..
       t         Drop first element: [1,2,1,1,1,2,1..
    `C⁰          Cut x to these lengths: [["a"],["b","c"],["d"]]
  ṁ↔             Reverse each slice and concatenate: ["a","c","b","d"]

```

I have to repeat `x` infinitely, since otherwise the list would lose its last element when we use the topmost spice. It would be enough to add a trailing 1, but repetition takes fewer bytes. A better way would be to rotate the list instead of dropping its first element, but Husk has no built-in for that.
> 5 votes

# Answer
# Haskell, 48 bytes

`foldl(?)` is an anonymous function taking two list arguments and returning a list, with all elements of the same (`Eq`-comparable) type.

Use as `foldl(?)["pepper", "paprika", "salt", "cumin", "oregano"]["oregano", "cumin", "cumin", "salt", "salt", "salt"]`.

```
foldl(?)
(x:y:r)?n|y==n=y:x:r|s<-y:r=x:s?n
s?n=s

```

Try it online!

* `foldl(?) s m` starts with the (spice rack) list `s` and combines it with each element (spice) from `m` in order, using the operator `?`.
* `s?n` uses the spice `n` from the spice rack `s` and returns the resulting spice rack.
    + If `s` has at least two elements, `?` checks whether the second one is equal to `n`, and if so switches the first two elements. If not equal, `?` keeps the first element fixed and recurses on the rest.
    + If `s` has at most one element, `?` returns it unchanged.
> 8 votes

# Answer
# Chef, ~~875~~ 843 bytes

```
S.

Ingredients.
1 g T
0 g Z
J
I

Method.
Put Z into mixing bowl.Take I from refrigerator.B I.Put I into mixing bowl.Take I from refrigerator.B until bed.Take I from refrigerator.V I.Put Z into 2nd mixing bowl.N T.Fold J into mixing bowl.Put J into mixing bowl.Remove I.Fold T into mixing bowl.Put J into 2nd mixing bowl.N until ned.Fold T into mixing bowl.Put T into mixing bowl.Fold J into 2nd mixing bowl.Put J into mixing bowl.C T.Stir for 1 minute.Put Z into mixing bowl.Fold T into mixing bowl.C until ced.Fold T into 2nd mixing bowl.G T.Put T into mixing bowl.Fold T into 2nd mixing bowl.G until ged.Put I into mixing bowl.Fold T into mixing bowl.Take I from refrigerator.V until ved.Fold T into mixing bowl.L T.Put T into 2nd mixing bowl.Fold T into mixing bowl.L until led.Pour contents of 2nd mixing bowl into baking dish.

Serves 1.

```

-32 bytes thanks to *Jonathan Allan* by removing `the` where I wouldn't think it will work.

Chef has no string types, so the ingredients are positive integers. 0 is used to separate the starting list from used ingredients and to end the used ingredients list. See the TIO link for an example.

**Pseudocode explaination:**

```
A, B: stack
T, J, IN: int
T = 1
A.push(0) // used as the marker for the bottom of the stack
IN = input() // input the first list
while(IN):
    A.push(IN)
    IN = input()
IN = input() // for each used ingredient
while(IN):
    B.push(0)
    while(T): // move all ingredients up to and including the one we are moving right now to the second stack
        T = A.peek() - IN
        B.push(A.pop())
    A.push(B.pop())
    if(A.peekUnderTop() != 0):
        A.swapTopTwoItems()
    T = B.pop() // move the ingredients from the second stack back to the first
    while(T):
        A.push(T)
        T = B.pop()
    T = IN // to make it non-zero for next iteration
    IN = input(0
print(A.inverted())

```

Try it online!
> 7 votes

# Answer
# JavaScript, 61 bytes

```
a=>b=>b.map(v=>(p=a.indexOf(v))&&a.splice(p-1,2,a[p],a[p-1]))

```

Input format:

* f(list\_of\_spices)(list\_of\_what\_spices\_got\_used)
* two list are array of string

Output:

* list\_of\_spices is modified in-place.

```
f=
a=>b=>b.map(v=>(p=a.indexOf(v))&&a.splice(p-1,2,a[p],a[p-1]))

a = ['pepper', 'paprika', 'salt', 'cumin', 'oregano'];
b = ['salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'oregano'];
f(a)(b);
document.write(JSON.stringify(a))
```
> 6 votes

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

New answer, in the spirit of my original attempt.

```
r,u=input()
for x in u:i=r.index(x);r.insert(i/~i+i,r.pop(i))
print r

```

Try it online!

Other solution:

# Python 2, 69 bytes

```
r,u=input()
for x in u:i=r.index(x)-1;r[i:i+2]=r[i:i+2][::-1]
print r

```

Try it online!
> 5 votes

# Answer
# Python 2, 80 bytes

```
def g(r,q):
 for s in q:
  i=r.index(s)
  if i:r[i-1],r[i]=r[i],r[i-1]
 return r

```

Try it online!
> 4 votes

# Answer
# Java 8, ~~87~~ ~~86~~ 76 bytes

```
a->b->b.forEach(x->{int i=a.indexOf(x);a.set(i,a.set(i>0?i-1:i,a.get(i)));})

```

Takes two inputs as `ArrayList<String>` and modifies the first List instead of returning a new one to save bytes.

-10 bytes thanks to *@Nevay*.

**Explanation:**

Try it here.

```
a->b->{                  // Method with two ArrayList<String> parameters and no return-type
  b.forEach(x->{         //  Loop over the second input-List
    int i=a.indexOf(x);  //   Get the index of the current item in the first input-List
    a.set(i,a.set(       //    Swap items:
      i>0?               //     If the current item is not the top item yet:
       i-1               //      Use the item above it
      :                  //     Else:
       i,                //      Use itself
         a.get(i)));     //     And swap it with the current item
  })                     //  End of loop
                         // End of method (implicit / single-line body)

```
> 4 votes

# Answer
# 05AB1E, ~~20~~ 18 bytes

```
vDyk>Ig‚£`U`2(@)X«

```

Try it online!

**Explanation**

```
v                    # for each used spice
 D                   # duplicate current spice order
  yk                 # get the index of the current spice
    >                # increment
     Ig‚             # pair with the number of unique spices
        £            # split the spice list into pieces of these sizes
         `           # split as 2 separate lists to stack
          U          # store the list of spices below the current one in X
           `         # push the current spice and all above separately to stack
            2(@      # swap the second item to the top of the stack
               )     # wrap in a list
                X«   # append the rest of the spices

```
> 2 votes

# Answer
## C#, 125 117 81 79 bytes

```
(c,n)=>{foreach(var i in n){var j=c.IndexOf(i);if(j!=0){c[j]=c[--j];c[j]=i;}}};

```

Try it on .NET Fiddle

golfed off 36 bytes thanks to raznagul
> 2 votes

# Answer
# 05AB1E, 16 bytes

```
vÐyk©DĀ-DUè®ǝyXǝ

```

Try it online!
> 1 votes

# Answer
# Mathematica, 52 bytes

but it is my first post here so please be kind if counted incorrectly :)

```
Keys@Sort@Merge[{PositionIndex@#,-Counts@#2},Total]&

```

And an example:

```
Keys@Sort@Merge[{PositionIndex@#, -Counts@#2}, Total] &[
    {pepper, paprika, salt, cumin, oregano}
  , {oregano, cumin, cumin, salt, salt, salt}
]

```

> {salt, pepper, paprika, cumin, oregano}
> 1 votes

# Answer
# CJam, 18 bytes

```
l~{a\_@#__g-e\}%~`

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Fabricate Frequently Factored Functions

text:
# Question
Title: Fabricate Frequently Factored Functions
In one of this question's bonuses I asked you to design a permutation on the natural numbers such that the probability of a random term being odd was \\$1\\$. Now let's kick it up a notch. I want you to design and implement a permutation, \\$f\\$, on the natural numbers such that, for every integer \\$n\\$ greater than 0, the probability on \\$f\\$ of a member being divisible by \\$n\\$ is \\$1\\$.

### Definition of Probability

To avoid confusion or ambiguity I am going to clearly lay out what is meant by probability in this question. This is adapted directly from my original question.

Let us say we have a function \\$f\\$ and a predicate \\$P\\$. The probability of a number fulfilling \\$P\\$ will be defined as the limit of the number of members of \\$f\\{1..n\\}\\$ fulfilling the predicate \\$P\\$ divided by \\$n\\$.

Here it is in a nice Latex formula

$$ \lim\_{n\to\infty} \dfrac{\left|\left\\{x : x\in \left\\{1\dots n\right\\}\right\\},P(f(x))\right|}{n} $$

---

In order to have a probability of something being \\$1\\$ you don't need every member to satisfy the predicate, you just need the ones that don't to get farther apart the bigger they are.

This is so answers will be scored in bytes with less bytes being better.

You may take the natural numbers to either include or exclude 0. Both are fine.

# Answer
# Husk, 11 bytes

```
!uΣz:NCNmΠN

```

Try it online! Or showing the stats for the first `100` n in the first `5000` terms

### Explanation

```
        mΠ     Map factorial over
          N    the Natural numbers
      CN       Cut into lists of lengths corresponding to the natural numbers
   z:N         ZipWith append the natural numbers and ^
  Σ            Concatenate into one list
 u             Remove duplicates
!              Index

```

### Proof (Without the `u`)

For triangle numbers : `f(½n*(n+1))=n`

Otherwise : `f(n)=k!` for some `k`.

As the density of triangular numbers is zero, this has the same probability as the sequence of factorials: `1`
> 3 votes

---
Tags: code-golf, math, open-ended-function
---