title: Let's play Mölkky!

text:
# Question
Title: Let's play Mölkky!
# Mölkky

Mölkky is a Finnish throwing game. The players use a wooden pin (also called "mölkky") to try to knock over wooden pins of almost similar dimensions with the throwing pin, marked with numbers from 1 to 12. The initial position of the pins is as follows:

```
   (07)(09)(08)
 (05)(11)(12)(06)
   (03)(10)(04)
     (01)(02)

```

*This description and the rules below are based on Wikipedia.*

# Simplified Mölkky rules

1. Knocking over **one pin** scores the number of points marked on the pin.
2. Knocking **2 or more pins** scores the number of pins knocked over (e.g., knocking over 3 pins scores 3 points).
3. The aim of the game is to reach exactly **50** points. Scoring more than 50 is penalized by setting the score back to **25** points.
4. For the purpose of this challenge, we will make the assumption that the pins are *always* in the exact order described above. (In a real game, the pins are stood up again after each throw in the location where they landed.)

All other Mölkky rules are ignored and only a single player is considered.

# Input

A non-empty list of lists of 12 booleans. Each list of booleans describes the outcome of a throw: **1** if the pin was knocked over and **0** otherwise. The booleans are given in the exact order of the pins, from top left to bottom right: **7**, **9**, **8**, **5**, **11**, **12**, **6**, **3**, **10**, **4**, **1**, **2**.

# Output

The score after all throws described in the input, calculated by applying rules **1**, **2** and **3**.

# Detailed example

Let's consider the following input:

```
// 07 09 08 05 11 12 06 03 10 04 01 02
[ [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],  // scores 5 (rule #1)
  [ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],  // scores 2 (rule #2), total: 7
  [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ],  // scores 7, total: 14
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],  // scores 12, total: 26
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],  // scores 12, total: 38
  [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ],  // scores 11, total: 49
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],  // scores 7, total: 56 -> 25 (rule #3)
  [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ] // scores 2, total: 27

```

The expected output is **27**.

# Challenge rules

* You may take input in any reasonable format. Instead of lists of booleans, you can use integers where the most significant bit is the pin #7 and the least significant bit is the pin #2. In this format, the above example would be passed as `[ 256, 2304, 127, 64, 64, 128, 2048, 3072 ]`.
* The input list may contain throws where no pin at all is knocked over, in which case the score is let unchanged.
* You don't have anything special to do when the score reaches *exactly* 50 points. But you can assume that no other throw will follow when it happens.
* This is , so the shortest answer in bytes wins.

# Test cases

Using lists of integers as input:

```
[ 0 ] --> 0
[ 528 ] --> 2
[ 4095 ] --> 12
[ 64, 0, 3208 ] --> 16
[ 16, 1907, 2048 ] --> 18
[ 2023, 2010, 1, 8 ] --> 29
[ 1726, 128, 35, 3136, 1024 ] --> 34
[ 32, 32, 2924, 2, 256, 16 ] --> 28
[ 64, 64, 2434, 1904, 3251, 32, 256 ] --> 25
[ 3659, 2777, 2211, 3957, 64, 2208, 492, 2815 ] --> 25
[ 2047, 1402, 2, 2599, 4, 1024, 2048, 3266 ] --> 50
[ 256, 2304, 127, 64, 64, 128, 2048, 3072 ] --> 27
[ 16, 8, 128, 1, 2048, 1, 2048, 513, 8, 3206 ] --> 30

```

You can follow this link to get these test cases in Boolean format.

# Answer
# Python 2, ~~126 111 108~~ 104 bytes

*-3 bytes thanks to Jonathan Allan*

*-4 bytes thanks to Kaya!*

```
f=lambda A,t=0:t>50and f(A,25)or A and f(A[1:],t-~(sum(A[0])-1or 762447093078/12**A[0].index(1)%12))or t

```

Try it online!

Defines a recursive function that takes a 2D array of 1s and 0s and returns an integer value. Nothing too special in the construction, and I'm sure there's a simpler solution.

### Explanation:

```
f=lambda A,t=0:    #Define the function, initialising t to 0 on the first iteration
               t>50and f(A,25)      #If t>50 then iterate again with t=25
                              or    #Else
               A and                #If A exists
                     f(A[1:],       #Iterate again without the first list of A
                        t-~         #And add to t, either
                           (sum(A[0])-1   #The sum of all elements if that's not 1
                                         or
                           762447093078/12**A[0].index(1)%12   #Else the appropriate pin value (black magic!)
               or t       #Finally, if A is finished, just return t

```
> 8 votes

# Answer
# Jelly, 25 bytes

```
“ñ€bḷ’œ?TLḢṖ?µ€+25¹>?50ɗ/

```

A monadic link accepting a list of lists of ones and zeros (each of length 12) which returns an integer.

**Try it online!** Or see the test-suite (using the integer values given in the OP)

### How?

This solution makes use of, `œ?`, which given a number, n, and a list finds the nth lexicographical permutation of the list where the list defines the sort order. First we need to work out this `n`:

```
 index:  1  2  3  4  5  6  7  8  9 10 11 12
 value:  7  9  8  5 11 12  6  3 10  4  1  2   (as defined by the question)
     P: 11 12  8 10  4  7  1  3  2  9  5  6   (our permutation lookup array)

```

...that is, `P` at index `i` is set to the original index of the value `i`.
This `P` has a lexicographical index of **438,337,469** (that is, if you took all **12!** permutations of the numbers **1** to **12** and sorted them lexicographically, the **438,337,469th** would be `P`).
This may be found using Jelly's `Œ¿` atom.
Both steps may be performed in one go using the Jelly program `ĠŒ¿`

```
“ñ€bḷ’œ?TLḢṖ?µ€+25¹>?50ɗ/ - Link: list of lists of zeros and ones
             µ€           - perform the monadic chain to the left for €ach list:
“ñ€bḷ’                    -   base 250 number = 438337469
      œ?                  -   nth permutation (reorder the 1s and 0s to their pin values)
        T                 -   truthy indices (get the pin values of the 1s)
            ?             -   if...
           Ṗ              -   ...condition: pop (length greater than 1 ?)
         L                -   ...then: length (the number of pins)
          Ḣ               -   ...else: head (the first (& only) pin value)
                        / - reduce the resulting list of integers with:
                       ɗ  -   last three links as a dyad:
               +          -     addition (add the two values together)
                     50   -     literal fifty
                    ?     -     if...
                   >      -     ...condition: greater than (sum greater than 50 ?)
                25        -     ...then: literal twenty-five
                  ¹       -     ...else: identity (do nothing - just yield the sum)

```
> 6 votes

# Answer
# Python 2, 90 bytes

Heavily inspired by Jo King's Python 2 answer and utilising Kaya's base-12 representation comment

```
t=0
for v in input():t+=sum(v)-1or 762447093078/12**v.index(1)%12;t=[t+1,25][t>49]
print t

```

**Try it online!** Or see the test-suite
> 5 votes

# Answer
# Pyth, ~~51~~ ~~48~~ 38 bytes

```
VQI>=+Z?qJsN1@.PC"îO&"S12xN1J50=Z25;Z

```

Saved 10 bytes thanks to Jonathan Allan Takes input as a list of lists of booleans.
Try it here

### Explanation

```
VQI>=+Z?qJsN1@.PC"îO&"S12xN1J50=Z25;Z
VQ                                  ;     For each input...
    =+Z                                   ... add to the total...
       ?q sN1                             ... if one pin is down...
             @.PC"îO&"S12xN1              ... the score of that pin.
         J                    J           ... otherwise, the count.
  I>                           50         If we pass 50...
                                 =Z25     ... reset to 25.
                                     Z    Output the total.

```
> 4 votes

# Answer
# Perl 5, ~~74~~ 70 bytes

```
$\+=y/1//-1||/1/g&&(0,6,8,7,4,10,11,5,2,9,3,0,1)[pos];$\=25if++$\>50}{

```

Try it online!

Takes input as a series of newline separated bitstrings.
> 4 votes

# Answer
# 05AB1E, ~~29~~ 28 bytes

```
v•CÞŸαLć•13вyOΘmyÏOO25‚¬50›è

```

Try it online!

**Explanation**

```
v                              # for each boolean list in input
 •CÞŸαLć•                      # push 13875514324986
         13в                   # convert to a list of base-13 numbers
            yO                 # push the sum of y
              Θm               # truthify and raise the pin-list to this number (0 or 1)
                yÏ             # keep those which are true in the current list
                  OO           # sum the list and the stack
                    25‚        # pair with 25
                       ¬50›    # check if the first number is larger than 50
                           è   # index into the pair with this result

```
> 4 votes

# Answer
# Java 10, ~~131~~ ~~130~~ 129 bytes

```
m->{int r=0,i,s,t;for(var a:m){for(i=s=t=0;i<12;s+=a[i++])t=a[i]>0?"    \n".charAt(i):t;r+=s<2?t:s;r=r>50?25:r;}return r;}

```

Contains 10 unprintables.
Input as integer-matrix of zeros and ones.

-1 byte thanks to *@JonathanFrech*, changing `\t` into an actual tab (works in TIO, doesn't work in my local IDE).

Try it online.

**Explanation:**

```
m->{                // Method with integer-matrix parameter and integer return-type
  int r=0,          //  Result-integer, starting at 0
      i,s,t;        //  Temp integers
  for(var a:m){     //  Loop over the integer-arrays of the input
    for(i=s=t=0;    //   Reset `i`, `s` and `t` to 0
        i<12;       //   Loop `i` in the range [0,12)
        s+=a[i++])  //    Increase `s` by the current value (0 or 1)
      t=a[i]>0?     //    If the current value is 1:
         "  \n".charAt(i)
                    //     Set `t` to the score at this position
        :t;         //    Else: Leave `t` the same
    r+=s<2?         //   If only a single pin was hit:
        t           //    Add its score `t` to the result
       :            //   Else:
        s;          //    Add the amount of pins `s` to the result
    r=r>50?         //   If the result is now above 50
       25           //    Penalize it back to 25
      :r;}          //   If not, it stays the same
  return r;}        //  Return the result

```
> 3 votes

# Answer
# Haskell, 96 bytes

```
foldl(\s a->([s..50]++e)!!sum(last$zipWith(*)[7,9,8,5,11,12,6,3,10,4,1,2]a:[a|sum a>1]))0
e=25:e

```

Try it online!

The wrapping is clever: I essentially index at position `s+sum(…)` into the list `([0..50]++cycle[25])`. However, a shorter way to write that is indexing at position `sum(…)` and beginning the list at `s`.
> 3 votes

# Answer
# Charcoal, 43 bytes

```
≔⁰ηＦθ«≧⁺⎇⊖ΣιΣι⌕α§”$｜#z⁸Ｕg⊗”⌕ι¹η¿›η⁵⁰≔²⁵η»Ｉη

```

Try it online! Link is to verbose version of code. Takes input as a boolean array. Explanation:

```
≔⁰η

```

Set the score to 0.

```
Ｆθ«

```

Loop over the throws.

```
⎇⊖Σι

```

Is the number of pins 1?

```
Σι

```

If not, then take the number of pins.

```
⌕α§”$｜#z⁸Ｕg⊗”⌕ι¹

```

Otherwise, translate the position of the pin to a value.

```
≧⁺...η

```

Add it to the score.

```
¿›η⁵⁰≔²⁵η

```

If the score exceeds 50 then set it back to 25.

```
»Ｉη

```

Print the final result after all the throws.
> 2 votes

# Answer
# Husk, ~~47~~ 35 bytes

-12 bytes thanks to H.PWiz (better way of generating the list encoding points)!

```
F₅0
S?25>50+?←Lε`f`+Nm+3d4652893071

```

Try it online!

### Explanation

```
F₅0  -- input is a list of boolean lists
F    -- left fold by
 ₅   -- | the function flipped (overflowing label) on line 1
  0  -- | with initial value 0

S?25>50+?←Lε`f`+Nm+3d4652893071  -- example inputs: [0,0,0,1,0,0,0,0,0,0,0,0] 0
                     4652893071  -- integer literal: 4652893071
                    d            -- digits: [4,6,5,2,8,9,3,0,7,1]
                 m+3             -- map (+3): [7,9,8,5,11,12,6,3,10,4]
              `+N                -- append natural numbers: [7,9,8,5,11,12,6,3,10,4,1,2,3,...
            `f                   -- filter this list by argument: [5]
        ?  ε                     -- if it's of length 1
         ←                       -- | take first
          L                      -- | else the length
                                 -- : 5
       +                         -- add to argument: 5
 ?  >50                          -- if the value is > 50
  25                             -- | then 25
S                                -- | else the value
                                 -- : 5

```
> 2 votes

# Answer
# Haskell, 110 bytes

```
m s|sum s==1=sum$zipWith(*)[7,9,8,5,11,12,6,3,10,4,1,2]s|1>0=sum s
f l=foldl(\b->c.(b+).m)0l
c a|a>50=25|1>0=a

```

Same length: `f l=foldl(\b a->last$b+m a:[25|b+m a>50])0l` instead of `f` and `c`

Try it online!
> 2 votes

# Answer
# Red, 189 172 bytes

```
func[b][s: 0 foreach c b[d: 0 foreach e c[if e = 1[d: d + 1]]i: find c 1
n: either i[pick[7 9 8 5 11 12 6 3 10 4 1 2]index? i][0]if 50 < s: s + either 1 < d[d][n][s: 25]]s]

```

Try it online!

## Explanation of the ungolfed code:

```
f: func[b][                                            ; a block of blocks of booleans
    s: 0                                               ; sets sum to 0
    foreach c b[                                       ; for each row of booleans
        d: 0 foreach e c[if e = 1[d: d + 1]            ; count the number of 1s
        i: find c 1                                    ; the index of the first 1
        n: either i[pick [7 9 8 5 11 12 6 3 10 4 1 2]  ; if there is 1, pick the number
                    index? i][0]                       ; at the index of 1
                                                       ; otherwise 0
        if 50 < s: s + either 1 < d[d][n][s: 25]       ; if there is only one 1, add
                                                       ; the number to the sum, otherwise
                                                       ; the number of 1s
                                                       ; if the sum > 50, reset it to 25
    ]
    s                                                  ; return the sum
]

```
> 1 votes

# Answer
# JavaScript (ES6), 98 bytes

```
a=>a.map(b=>b.map((m,i)=>(c+=m,d+=m*('0x'+'7985bc63a412'[i])),c=d=0)|(t+=c>1?c:d)>50?t=25:0,t=0)|t

```

**Test cases:**

```
f=
a=>a.map(b=>b.map((m,i)=>(c+=m,d+=m*('0x'+'7985bc63a412'[i])),c=d=0)|(t+=c>1?c:d)>50?t=25:0,t=0)|t

console.log(f([ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ])) // 0

console.log(f([ [ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 ] ])) // 2

console.log(f([ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ])) // 12

console.log(f(
[ [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ] ]
)); // 16

console.log(f(
[ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ],
  [ 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
])); // 18

console.log(f(
[ [ 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ],
  [ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ] ]
)); // 29

console.log(f(
[ [ 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0 ],
  [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ],
  [ 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
))  // 34

console.log(f(
[ [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],
  [ 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ],
  [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ] ]
))  // 28

console.log(f(
[ [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0 ],
  [ 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0 ],
  [ 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1 ],
  [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
))  // 25

console.log(f(
[ [ 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1 ],
  [ 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1 ],
  [ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1 ],
  [ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1 ],
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 ],
  [ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ] ]
)) // 25

console.log(f(
[ [ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ],
  [ 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ],
  [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 ] ]
)) // 50

console.log(f(
[ [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 ],
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
)) // 27

console.log(f(
[ [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ],
  [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
  [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ],
  [ 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 ] ]
)) // 30
```
> 1 votes

# Answer
# Python 2, ~~109~~ ~~105~~ 103 bytes

```
c=0
for l in input():a=sum(l);c+=int('7985bc63a412'[l.index(1)],16)if a==1else a;c=(25,c)[c<51]
print c

```

Try it online!

Alternative without a recursive function.

-2 with thanks to @Jo King
> 0 votes

# Answer
# Stax, 37 bytes

```
├T<↓"♥←~;▌6»≥øF←î5░U╚_π○Q▒<│∟└ù║pε♀▀æ

```

Run and debug it

Try It online!

**Explanation**

```
F:1"=EA5MQ9-I1%)"!s@c%1={h+}{%+}?c50>{d25}{}?    # Full program, unpacked

F                                                # Loop through every element
 :1                                              # Get indices of truthy elements
   "=EA5MQ9-I1%)"!                               # Push encoded [7,9,8,5,11,12,6,3,10,4,1,2]
                 s@                              # Swap the top 2 elements of stack and get elements at indexes
                   c%1=                          # Copy the top element, get length of array, compare to length of 1
                       {h+}{%+}?                 # If it has length of 1, add the element, otherwise add the length of the array to total
                                 c50>            # Compare total to 50,
                                     {d25}{}?    # If it is greater, pop it off and push 25 to reset counter, otherwise do nothing

```

Not my best work, but it works. I'm sure there is somehting I'm missing to make it a bit shorter.
> 0 votes

---
Tags: code-golf, game, binary
---


title: Assign Airliner Seats

text:
# Question
Title: Assign Airliner Seats
*Inspired by last week's APL lesson.*

Given an uppercase 2D seat map and a 1D list of customers, return the seat map and the customer list but modified as follows (to indicate occupied seats and seated customers):

For each unique letter in the input passenger list, lowercase that many (or all, if there are not enough) of that letter in the seat map, going left-to-right, top-to-bottom.

For each unique letter in the seat map, lowercase that many (or all, if there are not enough) of that letter in the passenger list, going left-to-right.

1. The input seat map only contains spaces and uppercase letters from the set {`F`,`B`,`P`,`E`}, and may be:
    1. separated into rows by line breaks
    2. a list of strings
    3. a matrix of uppercase characters
    4. in any other comparable format
2. The input customer list only contains uppercase letters from the set {`F`,`B`,`P`,`E`} and may be:
    1. a string
    2. a list of characters
    3. in any other comparable format
3. The returned seat map must be identical to the input one, except that zero or more letters have been folded to lowercase
4. The returned customer list must be identical to the input one, except that zero or more letters have been folded to lowercase
5. Leading and trailing whitespace is allowed

## Examples <sup>(shortened editions of United's aircraft)</sup>

### ERJ145

Seat map input:

```
P
E
E  PP
E  EE
E  EE
E  EE
E  EE

P  PP
E  EE
E  EE
E  EE

```

Passenger list input:

```
FFEEEEEEEEEEEEEEEE

```

Seat map output:

```
P
e
e  PP
e  ee
e  ee
e  ee
e  ee

P  PP
e  eE
E  EE
E  EE

```

Passenger list output:

```
FFeeeeeeeeeeeeeeee

```

### CRJ700

Seat map input:

```
F   FF
F   FF
PP  PP
PP  PP
PP  PP
EE  EE

PP  PP
EE  EE
EE  EE
EE  EE

```

Customer list input:

```
FFFFFFFFPPEEEEEEEEEEEEEEEEEEEEE

```

Seat map output:

```
f   ff
f   ff
pp  PP
PP  PP
PP  PP
ee  ee

PP  PP
ee  ee
ee  ee
ee  ee

```

Customer list output:

```
ffffffFFppeeeeeeeeeeeeeeeeEEEEE

```

### B757

Seat map input:

```
F F  F F
F F  F F
F F  F F

PPP
PPP  PPP
PPP  PPP
PPP  PPP
EEE  EEE
EEE  EEE
PPP  PPP
EEE  EEE
EEE  EEE
     EEE

EEE  EEE
EEE  EEE
EEE  EEE
EEE

```

Passenger list input:

```
FEEEEEEEEFEEEFEEEEEEEEFEEFFEEFEFFFEE

```

Seat map output:

```
f f  f f
f f  f f
f f  F F

PPP
PPP  PPP
PPP  PPP
PPP  PPP
eee  eee
eee  eee
PPP  PPP
eee  eee
eee  eee
     eeE

EEE  EEE
EEE  EEE
EEE  EEE
EEE

```

Passenger list output:

```
feeeeeeeefeeefeeeeeeeefeeffeefefffee

```

### B767

Seat map input:

```
 F   F   F
 F   F   F
BB  B B  BB
BB  B B  BB
BB  B B  BB
PP       BB
PP

PP  PPP  PP
PP  PPP  PP
PP  PPP  PP
PP  PPP  PP
PP  EEE  PP
EE  EEE  EE
EE  EEE  EE
EE  EEE  EE
EE  EEE  EE
EE  EEE  EE

```

Passenger list input:

```
PPFEFEEEEEEEBBEEFFPEBPEBBEEFEEEFEEEEEEFPEEEPB

```

Seat map output:

```
 f   f   f
 f   f   f
bb  b b  bb
BB  B B  BB
BB  B B  BB
pp       BB
pp

pp  PPP  PP
PP  PPP  PP
PP  PPP  PP
PP  PPP  PP
PP  eee  PP
ee  eee  ee
ee  eee  ee
ee  eee  ee
ee  EEE  EE
EE  EEE  EE

```

Passenger list output:

```
ppfefeeeeeeebbeeffpebpebbeefeeefeeeeeeFpeeepb

```

# Answer
> 5 votes
# Python 2, ~~93~~ ~~89~~ ~~84~~ ~~83~~ ~~82~~ 78 bytes

```
l=input()
for c in l[1]:l=[x.replace(c,c.lower(),c in l[0])for x in l]
print l

```

Try it online!

Takes input as two strings. Prints two strings

---

Saved

* -5 bytes, thanks to Dead Possum
* -4 bytes, thanks to Lynn

# Answer
> 5 votes
# 05AB1E, ~~22~~ ~~16~~ 15 bytes

Saved 6 bytes thanks to *Nit* noticing that the seat map could be taken as a string.

```
svDyå·Fyyl.;s]»

```

Try it online!

**Explanation**

```
s                     # setup stack as <passengerlist>,<seatmap>,<passengerlist>
 v                    # for each passenger y
  Dyå                 # does a corresponding seat exist?
     ·F               # multiplied by 2 times do:
       yyl.;          # replace the first y with a lowercase y
            s         # and swap the seatmap and passengerlist on the stack
             ]        # end loops
              »       # join seatmap and passengerlist on newline and output

```

# Answer
> 5 votes
# C (clang), 75 68 bytes

```
f(char*s,char*p){char*r;while(*s){if(r=strchr(p,*s))*r=*s+=32;s++;}}

```

Takes two `char *` (seats & passengers) whose contents are modified in-place.

Try it online!

I'm less used to golfing in C than in Python, but that's fun as well !

If anyone has an idea for a trick to shorten the `*r+=32,*i+=32` part I'd be grateful. **-\> Thanks to @Dave for helping me golf some more bytes !**

# Answer
> 4 votes
# C (gcc), 63 bytes

```
f(x,y,z)char*x,*y,*z;{for(;*y;++y)if(z=strchr(x,*y))*z=*y+=32;}

```

Try it online!

Lots of credit to etene for the basic concept. Just applied heavy golfing to his answer's strategy.

# Answer
> 3 votes
# C (gcc), 64 bytes

Borrowing from @etene's answer, I removed the `if` with the `?:` tertiary operator and reused the passenger pointer as its own index.

```
f(s,p,j)char*s,*p,*j;{for(;*p;p++)(j=strchr(s,*p))?*j=*p|=32:0;}

```

Try it online!

# Answer
> 2 votes
# Jelly, 19 bytes

```
,ṚŒlẹÐ€ḣ"ċÐ€`}Ẏʋ¦/€

```

Try it online!

# Answer
> 2 votes
# Scala, 104 bytes

```
def f(l:Array[Char]*)=(l(0).map(? =>{val i=l(1)indexOf?;if(i>=0){l(1)(i)= ?toLower;l(1)(i)}else?}),l(1))

```

Try it online!

Takes 2 seq of chars in input and returns 2 seq of chars.

Explanation:

```
def f(l: Array[Char]*) =          // input are varargs of Array[Char]; in our case 2 arrays. Arrays are chosen since mutable (the seatmap will be updated while the passenger list is mapped)
  (                               // we return a tuple with the 2 arrays of Chars
    l(0).map(                     // l(0) is the passenger list. We map (transform) each element of this list to lowercase or not and this is what's returned as 1st part of the tuple
      ? => {                      // ? is the current element of the passenger list being mapped (it's ? and not let's say m in order to be able to stick it next to functions)
        val i = l(1) indexOf ?   // i is the index (or -1) of the letter ? in the seat map
        if (i >= 0) {             // if index found
          l(1)(i) = ? toLower     // then we update the seatmap with the lower case version of this seat
          l(1)(i)                 // and the passenger list elmt is mapped to its lower case version (same as ?.toLower)
        }                         //
        else ?                    // if not found, the seatmap is not updated and the passenger list elmt stays in upper case
      }                           //
    ),                            //
    l(1)                          // the updated seat map
  )

```

# Answer
> 1 votes
# Retina, 36 bytes

```
+`(([A-Z])(.*¶)+.*?)(\2.*$)
$l$1$l$4

```

Try it online! Assumes the customer list is the last line of the input. Explanation: Finds pairs of matching uppercase characters and lowercases them using `$l` thus avoiding the intermediate characters.

# Answer
> 1 votes
# APL (Dyalog Classic), ~~29~~ 27 bytes

```
(~2∊/3⍴(⍴⍴,\∘,∩¨,)¨)819⌶¨¨⊢

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-pF`, 48 bytes

```
$\=join'',<>;say map$\=~s/$_/lc$_/e&&lc||$_,@F}{

```

Try it online!

First line of input is the passenger list. All subsequent lines are the seat map. Output is the same.

---
Tags: code-golf, string, grid, counting, classification
---


title: Fill out my Bubble Sheet

text:
# Question
Title: Fill out my Bubble Sheet
Today was AP exam registration day at my school, and while I was meticulously bubbling in the pages and pages of information required, the idea for this challenge hit me. So, given a string of letters and numbers, output an appropriately filled out bubble chart.

# Rules:

* For each character in the input string, replace that character in the corresponding column with a `#` or `@` or any other reasonable symbol (if your language can handle it, the Unicode character 'full\_block': █ looks really good)
* A space is represented by a blank column (see examples)
* Valid input will be a string which is made up of only uppercase letters, numerical digits, and spaces.
* Input will be of a length with a minimum of 1, and a maximum of 32 characters.
* Output must be *UPPERCASE*
* If the input length is less than the maximum length of 32, your program must still output the remaining blank columns
* Your program doesn’t have to handle lowercase input the same as if they were uppercase, but bonus points if it can.

## Board Format:

```
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
00000000000000000000000000000000
11111111111111111111111111111111
22222222222222222222222222222222
33333333333333333333333333333333
44444444444444444444444444444444
55555555555555555555555555555555
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999

```

## Examples:

```
CODE GOLF ->

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
█CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DD█DDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEE█EEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFF█FFFFFFFFFFFFFFFFFFFFFFF
GGGGG█GGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLL█LLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
O█OOOO█OOOOOOOOOOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
00000000000000000000000000000000
11111111111111111111111111111111
22222222222222222222222222222222
33333333333333333333333333333333
44444444444444444444444444444444
55555555555555555555555555555555
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999

ABCDEFGHIJKLMNOPQRSTUVWXYZ012345 ->

@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
B@BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CC@CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDD@DDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEE@EEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFF@FFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGG@GGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHH@HHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIII@IIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJ@JJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKK@KKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLL@LLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMM@MMMMMMMMMMMMMMMMMMM
NNNNNNNNNNNNN@NNNNNNNNNNNNNNNNNN
OOOOOOOOOOOOOO@OOOOOOOOOOOOOOOOO
PPPPPPPPPPPPPPP@PPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQ@QQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRR@RRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSS@SSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTT@TTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUU@UUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVV@VVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWW@WWWWWWWWW
XXXXXXXXXXXXXXXXXXXXXXX@XXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYY@YYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZ@ZZZZZZ
00000000000000000000000000@00000
111111111111111111111111111@1111
2222222222222222222222222222@222
33333333333333333333333333333@33
444444444444444444444444444444@4
5555555555555555555555555555555@
66666666666666666666666666666666
77777777777777777777777777777777
88888888888888888888888888888888
99999999999999999999999999999999

ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ->^^^

```

And of course, this is , so shortest answer wins

# Answer
> 4 votes
# Ruby, 62 bytes

```
->s{[*?A..?Z,*?0..?9].map{|c|(0..31).map{|i|c==s[i]??@:c}*''}}

```

Try it online!

Returns array of strings. Could be golfed further by discarding string joins and returning a 2D array of characters as is usually the norm, but I'm not sure if it is allowed here.

# Answer
> 4 votes
# Husk, 23 bytes

```
mż§?'#|=⁰mR32¤+…"AZ""09

```

Try it online or try it with the fancy █ character (but an invalid bytecount)!

Unfortunately I wasn't able to merge the two `map`s into one (except with using parentheses, costing 24 bytes)..

### Explanation

```
mż§?'#|=⁰mR32¤+…"AZ""09"  -- expects string as argument, eg. "FOO"
             ¤            -- with the two strings "AZ" "09" ..
               …          -- | fill ranges: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          -- |              "0123456789"
              +           -- .. and concatenate: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
          m               -- map the following (eg. with 'X')
                          -- | replicate 32 times: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                          -- : ["A…A","B…B",…,"Z…Z","0…0",…"9…9"]
m                         -- map the following (eg. with "F…")
 ż      ⁰                 -- | zipWith (keeping elements of longer list) argument ("FOO")
  §?   =                  -- | | if elements are equal
    '#                    -- | | | then use '#'
      |                   -- | | | else use the first character
                          -- | : ["#FF…F"]
                          -- : ["A…A",…,"#FF…F",…,"O##O…O",…,"9…9"]

```

# Answer
> 3 votes
# C (gcc), ~~132~~ 126 bytes

```
char*s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",*_,*a;f(char*x){for(_=s;*_;++_,puts(""))for(a=s;*a;)putchar(x[a++-s]-*_?*_:64);}

```

Try it online!

Thanks to Jonathan Frech for saving 6 bytes.

# Answer
> 3 votes
# Charcoal, 21 bytes

```
Ｅ⁺α⭆…αχκ⭆…◨θφ³²⎇⁼ιλ#ι

```

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

```
  α  α                  Uppercase alphabet predefined variable
      χ                 Predefined variable 10
    …                   Chop to length
   ⭆                    Map over characters and join
       κ                Current index
 ⁺                      Concatenate
Ｅ                       Map over characters into array
           θ            Input string
            φ           Predefined variable 1000
          ◨             Right pad to length
             ³²         Literal 32
         …              Chop to length
        ⭆               Map over characters and join
                 ι  ι   Current outer character
                  λ     Current inner character
                ⁼       Equals
                   #    Literal `#`
               ⎇        Ternary
                        Implicitly print each result on its own line

```

Previous version with input validation, ~~34~~ 32 bytes. Edit: saved 2 bytes thanks to @ASCII-only.

```
≔⁺α⭆…αχκαＥα⭆…◨Φθ∨⁼ι №αιφ³²⎇⁼ιλ#ι

```

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

# Answer
> 3 votes
# Jelly,  ~~18~~  17 bytes

```
ØA;ØDWẋ32ɓ,€⁶y"ZY

```

Uses a space character. To use a `#` replace  with `”#` for a cost of one byte.

**Try it online!**

### How?

```
ØA;ØDWẋ32ɓ,€⁶y"ZY - Main Link: list of characters, S   e.g.  ['S','P','A','M']
ØA                - upper-case alphabet characters           ['A','B',...,'Z']
   ØD             - digit characters                         ['0','1',...,'9']
  ;               - concatenate                              ['A','B',...,'Z','0','1',...,'9']
     W            - wrap in a list                           [['A','B',...,'Z','0','1',...,'9']]
      ẋ32         - repeat 32 times                          [['A','B',...,'Z','0','1',...,'9'],...,['A','B',...,'Z','0','1',...,'9']]
         ɓ        - start a new dyadic chain with that on the right
            ⁶     - space character                          ' '
          ,€      - pair €ach of S with a space              [['S',' '],['P',' '],['A',' '],['M',' ']]
              "   - zip with:
             y    -   translate (replace 'S' with ' ' in 1st, 'P' with ' ' in 2nd, ...) -- Note: zip is a zip-longest, so trailing lists remain
                Z  - transpose
                 Y - join with line-feeds
                   - implicit print

```

# Answer
> 3 votes
# Red, 177 bytes

```
func[s][m: copy[]foreach c a:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[insert/dup r: copy"^/"c 32 append m r]j: 0
foreach c s[j: j + 1 if c <>#" "[m/(index? find a c)/(j): #"@"]]m]

```

Try it online!

More readable:

```
f: func[s][
    m: copy[]
    a:"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    foreach c a[
        insert/dup r: copy "^/" c 32
        append m r
    ]
    j: 0
    foreach c s[
        j: j + 1
        if c <>#" "[m/(index? find a c)/(j): #"@"]
    ]
    m
]

```

# Answer
> 3 votes
# , 104 bytes

```
function(S,o=""){for(i in 1:32)o=paste0(o,`[<-`(x<-c(LETTERS,1:9),x==substr(S,i,i),"@"))
cat(o,sep="
")}

```

Try it online!

# Answer
> 2 votes
# Node.js, 85 bytes

*Port to Node.js suggested by @DanielIndie*

```
f=(s,x=544,c=Buffer([48+x/32%43]))=>x<1696?(s[x&31]==c?'@':c)+[`
`[++x&31]]+f(s,x):''

```

Try it online!

---

# JavaScript (ES6), ~~103~~ 98 bytes

```
f=(s,x=544,n=x>>5,c=String.fromCharCode(48+n%43))=>n<53?(s[x&31]==c?'@':c)+[`
`[++x&31]]+f(s,x):''

```

Try it online!

# Answer
> 2 votes
# C++14, ~~319 bytes~~ 237

This is my first time doing this, in the worst possible CodeGolf Language :P

```
char c;string k="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",s;int main(){map<char,vc>g;g[' ']=vc(32,' ');for(char c:k)g[c]=vc(32,c);getline(cin,s);for(int i=0;i<s.length();i++)g[s[i]][i]='@';for(char d:k){for(char x:g[d])cout<<x;cout<<'\n';}}

```

Try it Online!

# Answer
> 2 votes
# APL+WIN, 56 bytes

Prompts for input string and uses # character as identifier:

```
m←⍉32 36⍴⎕av[(65+⍳26),48+⍳10]⋄((,m[;1]∘.=32↑⎕)/,m)←'#'⋄m

```

Explanation:

```
m←⍉32 36⍴⎕av[(65+⍳26),48+⍳10] create the table

32↑⎕ pad the input string to 32 characters with spaces

(,m[;1]∘.=32↑⎕) use outer product with = to identify characters in table

((,m[;1]∘.=32↑⎕)/,m)←'#' replace characters with #

m display table

⋄ statement separator

```

# Answer
> 2 votes
# Perl 5 `-F`, 47 bytes

```
//,say map{$F[$_]eq$'?'*':$'}0..31for A..Z,0..9

```

Try it online!

# Answer
> 2 votes
# Haskell, 86 bytes

For a much nicer approach (and less bytes), see Laikoni's solution!

```
f x=(x#).(<$[1..32])<$>['A'..'Z']++['0'..'9']
(a:b)#(u:v)=last(u:['#'|a==u]):b#v
_#w=w

```

Try it online!

Alternatively for the same byte count we could use:

```
(a:b)#(u:v)|a==u='#':b#v|0<3=u:b#v

```

Try it online!

### Explanation / Ungolfed

The operator `(#)` is very similar to `zipWith` however the function is hardcoded, st. it uses `#` if two characters are equal and otherwise it keeps the second one, ungolfed:

```
(a:b) # (u:v)
   | a == u    = '#' : b # v
   | otherwise =  u  : b # v

```

If the first list is exhausted it just appends the remaining elements of the second one:

```
_ # w = w

```

With that helper we only need to generate the string `"A..Z0..9"`, replicate each element 32 times and zip the input with each string, ungolfed:

```
f x = map ((x#) . replicate 32) (['A'..'Z'] ++ ['0'..'9'])

```

# Answer
> 2 votes
# Haskell, 74 bytes

```
f x=[do a<-take 32$x++cycle" ";max[c]['~'|a==c]|c<-['A'..'Z']++['0'..'9']]

```

Try it online! An input string `x` is padded with spaces to a length of 32 with `take 32$x++cycle" "`. For each character `c` from `A` to `Z` and `0` to `9`, we look at the characters `a` from the padded input string and replace them by `~` when `a` and `c` are equal and by `c` otherwise. This is achieved by `max[c]['~'|a==c]`, which is e.g. `max "A" "~" = "~"` when `a = c = 'A'`, and `max "A" "" = "A"` when `c = 'A'` and `a = 'B'`. Because this yields a singleton string instead of a char, the `do`-notation is used which concatenates the singleton strings into one string.

Based on BMO's Haskell solution.

# Answer
> 2 votes
# Python 2, 138 bytes

Supports both upper and lower case chars and leaves an unfilled column for spaces.

```
def f(s):
 s=s.upper()
 for j in"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":print"".join(j if(len(s)<=i)or(s[i]!=j)else'@'for i in range(32))

```

If the bonus isn't worth it, then I'll go for 125 bytes and only support upper case inputs:

```
def f(s):
 for j in"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":print"".join(j if(len(s)<=i)or(s[i]!=j)else'@'for i in range(32))

```

# Answer
> 2 votes
# Stax, 15 bytes

```
╛dδÑ-═E↑\≈Fà±AG

```

Run and debug it

It uses `'#'` to indicate a filled bubble.

Unpacked, ungolfed, and commented, it looks like this.

```
32(     right-pad or truncate to 32
{       begin block for mapping
  VAVd+ "A..Z0..9"
  s'#+  move input character to top of stack and append "#". e.g. "C#"
  |t    translate; replace the first character with the second in string
m       perform map using block
Mm      transpose array of arrays and output each line

```

Run this one

# Answer
> 2 votes
# Retina, 64 bytes

```
$
36*
L`.{36}
.
36*@$&¶
Y`@`Ld
(.)(.*)\1
@$2
N$`\S
$.%`
L`.{32}

```

Try it online!

---

```
$
36*
L`.{36}

```

Pads the inputs string on the right with spaces to **36** characters

```
.
36*@$&¶
Y`@`Ld

```

Then, put each character on its own line and add `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` before it.

```
(.)(.*)\1
@$2

```

Match a pair of the same character on the same line, which there is one if and only if the character for that line matches one of `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`. Replace the first with `@` and remove the second.

```
N$`\S
$.%`

```

The only unmatched lines are ones with spaces, so the non-space characters is a 36×36 square block. Transpose it.

```
L`.{32}

```

Only keep the first 32 characters in each line

# Answer
> 1 votes
# Pyth, ~~23~~ 20 bytes

```
j.Tm:s+r1GUTdN.[Qd32

```

Try it here

### Explanation

```
j.Tm:s+r1GUTdN.[Qd32
              .[Qd32      Pad the input to 32 characters.
   m                      For each character...
     s+r1GUT              ... get the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"...
    :       dN            ... with the character replaced by a '"'.
j.T                       Transpose the lines and print them all.

```

# Answer
> 1 votes
# Python 2, ~~103~~ ~~96~~ 94 bytes

-7 bytes thanks to Mnemonic
-2 bytes thanks to Jonathan Frech

Uses `'` as the symbol

```
i,l=input(),17;exec"k=chr(l%43+48);print''.join(`k`[i[x:][:1]!=k]for x in range(32));l+=1;"*36

```

Try it online!

# Answer
> 1 votes
# C (gcc), 124 bytes

```
f(s,b,x,y)char*s,b[33];{sprintf(b,"%-32.32s",s);for(x=0;++x<36;puts(""))for(y=x+21+43*(x<27),s=b;*s;putchar(*s++==y?35:y));}

```

Try it online!

Instead of a hard-coded array, I replaced it with a lookup function instead. Fortunately the ASCII character set has contiguous alphabetic and numeric ranges (I'm looking at you, EBCDIC!) As well, I made sure to keep the output to exactly 32 characters using `sprintf()`: if this wasn't a requirement of the task, the function would be 97 bytes:

```
f(s,i,x,y)char*s,*i;{for(x=0;++x<36;puts(""))for(y=x+21+43*(x<27),i=s;*i;putchar(*i++==y?35:y));}

```

Try it online!

# Answer
> 1 votes
# CJam, 31 bytes

```
q32Se]{'[,65>A,s+S+_@#St);}%zN*

```

Try it online! Uses spaces as the "hole" character.

---

If trailing whitespace is allowed, then this works for **29 bytes**:

```
q32Se]{'[,65>A,s+S+_@#St}%zN*

```

Try it online!

---

Here's a 34-byte variation that uses the Unicode full block () instead:

```
q32Se]{'[,65>A,s+S+_@#'█t);}%zN*

```

Try it online!

---

## Explanation

```
q                                Input.
    e]                           Pad to a length of
 32                                32
                                 with
   S                               spaces.
      {                   }%     For each character:
                                   Get the uppercase alphabet by
            >                        dropping the first
          65                           65
                                     elements of
         ,                             the range of characters below
       '[                                '['.
                +                  Append
               s                     the string version
              ,                        of the range of numbers below
             A                           10.
                  +                Append
                 S                   a space.
                     #             Find the index of
                    @                the character.
                       t           Set this index to
                      S              a space
                   _               in the original array.
                        );         Drop the space at the end.
                                   Yield this modified array.
                                 End for. The result is an array of arrays of characters.
                            z    Transpose this array, turning rows into columns.
                             N*  Join the result on newlines.

```

# Answer
> 1 votes
# 05AB1E, 19 bytes

```
RтúR32£vžKuÙyð:})ø»

```

Try it online!

**Explanation**

```
R                     # reverse
 тú                   # prepend 100 zeroes
   R                  # reverse
    32£        }      # take the first 32 characters
       v              # for each character
        žK            # push a string of [a-zA-Z0-9]
          uÙ          # upper case and remove duplicates
            yð:       # replace current character with space
                )ø    # transpose
                  »   # join by newline

```

# Answer
> 1 votes
# MATL, 21 bytes

```
1Y24Y2vjO33(32:)y=~*c

```

Uses a space as marker character.

Try it online!

### Explanation

```
1Y2     % Push 'AB...YZ'
4Y2     % Push '01...89'
v       % Concatenate into a 36×1 column vector of chars
j       % Push unevaluated input: string of length n, or equivalently 1×n
        % row vector of chars
O33(    % Write 0 at position 33. This automatically writes a 0 at postions
        % n+1, n+2, ..., 32 too
32:)    % Keep only the first 32 entries: gives a 1×32 row vector
y       % Duplicate from below: pushes a copy of the 36 ×1 column vector
=~      % Test for non-equal entries, with broadcast. Gives a 33×32 matrix
        % containing 0 for matching entries, and 1 otherwise
*       % Multiply this matrix by the 1×32 row vector, with broadcast. This
        % changes each 1 into the corresponding character in the input
c       % Convert to char. Implicitly display. Char 0 is displayed as space

```

# Answer
> 1 votes
# Java 10, ~~120~~ ~~118~~ 117 bytes

```
s->{var r="";for(char c=65,i;c<91&c!=58;r+="\n",c+=c<90?1:-42)for(i=0;i<32;i++)r+=i<s.length&&s[i]==c?35:c;return r;}

```

Try it online (for TIO I've used '█' (`9608` instead of `35`) for better visibility).

**Explanation:**

```
s->{                   // Method with character-array parameter and String return-type
  var r="";            //  Result-String, starting empty
  for(char c=65,i;     //  Start character `c` at 'A'
      c<91&c!=58       //  Loop as long as `c` is 'Z' or smaller, and is not '9'
      ;                //    After every iteration:
       r+="\n",        //     Append a new-line to the result-String
       c+=c<90?        //     If `c` is not 'Z' yet
           1           //      Go to the next character ASCII-value-wise
          :            //     Else:
           -42)        //      Change the 'Z' to '0'
    for(i=0;i<32;i++)  //    Inner loop `i` in the range [0,32)
      r+=i<s.length    //     If we're not at the end of the input array yet,
         &&s[i]==c?    //     and the characters in the column and array are the same
          35           //      Append the filler-character '#'
         :             //     Else:
          c;           //      Append the current character instead
  return r;}           //  Return the result-String

```

# Answer
> 1 votes
# Common Lisp, 150 bytes

```
(setq s(format nil"~32a"(read-line)))(map nil(lambda(i)(map nil(lambda(j)(princ(if(eq i j)#\# i)))s)(princ"
"))"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

```

Try it online!

### Explanation

```
;; pad input to 32 spaces on the right
(setq s(format nil"~32a"(read-line)))
;; for each character in bubble sheet, for each character in input:
;; if characters are equal print "#"
;; else print bubble sheet character
(map nil(lambda(i)(map nil(lambda(j)(princ(if(eq i j)#\# i)))s)(princ"
"))"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

```

# Answer
> 1 votes
# Tcl, ~~153~~ 145 bytes

Thanks @sergiol for -8 bytes

```
lmap i [split ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ""] {puts [join [lmap j [split [format %-32s [join $argv ""]] ""] {expr {$i==$j?"#":$i}}] ""]}

```

Try it online!

### Explanation

```
# for i in list of choices
lmap i [split ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ""] {
    # print string of
    puts [join
        # list of
        [lmap j
             # for each character in first argument padded to 32 characters
             [split [format %-32s [join $argv ""]] ""]
             # return "#" if current choice and current character are equal, else current choice
             {expr {$i==$j?"#":$i}}
        ]
        ""
    ]
}

```

# Answer
> 1 votes
# Prolog (SWI), ~~235~~ ~~229~~ ~~228~~ ~~222~~ ~~214~~ ~~198~~ ~~173~~ ~~167~~ 165 bytes

-6 bytes thanks to @Cows quack, -6 bytes thanks to @ 0 '

```
X*[H|T]:-(H=X->write(#);writef("%n",[X])),X*T;nl.
_+[].
X+[H|T]:-H*X,X+T.
?-read(X),swritef(Y,"%32l",[X]),string_codes(Y,Z),Z+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.

```

Try it online!

### Explanation

```
% if head = bubble char, write "#", else write bubble char, then while tail is non-empty, recurse.
% if tail is empty then print newline
X*[H|T]:-(H=X->write(#);writef("%n",[X])),X*T;nl.
% if list is empty, then do nothing. this prevents t from being called with invalid X
_+[].
% call t, then recurse for each char in list
X+[H|T]:-H*X,X+T.
% read, pad input to 32 chars, and convert input to list
?-read(X),swritef(Y,"%32l",[X]),string_codes(Y,Z),Z+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`.

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), ~~155~~ 150 bytes

```
	I =INPUT
	U =&UCASE '0123456789'
N	U LEN(1) . K REM . U	:F(END)
	O =DUPL(K,32)
	X =
S	I LEN(X) @X K	:F(O)
	O POS(X) K =' '	:S(S)
O	OUTPUT =O	:(N)
END

```

Try it online!

Explanation:

```
	I =INPUT			;* read input
	U =&UCASE '0123456789'		;* U = uppercase concat digits
N	U LEN(1) . K REM . U	:F(END)	;* while U not empty, pop first letter as K
	O =DUPL(K,32)			;* dup K 32 times
	X =				;* set position to 0
S	I LEN(X) @X K	:F(O)		;* find the next occurrence of K and save (index - 1) as X
	O POS(X) K =' '	:S(S)		;* replace the X'th occurrence of K with space. If that's before character 32, goto S, else proceed to next line
O	OUTPUT =O	:(N)		;* output the string and goto N
END

```

# Answer
> 0 votes
# PHP, ~~63~~ 61 bytes

```
for($c=A;$p<891;)echo$argn[$p++%33]!=$c?$p%33?$c:"
".!$c++:█;

```

Run as pipe with `-nR` or try it online.

## changed specs (with digits), ~~80~~ 74 bytes:

```
for($c=A;$p<1188;)echo$argn[$p++%33]!=="$c"?$p%33?$c:"
".(++$c<B&&$c=0):█;

```

`++$c<B` is false for all letters up to `Z` and for all non-negative numbers.
`Z` incremented is `AA`; in that case `$c` is set to `0` to loop through the digits.
`&&` casts the whole expression to false, `.` casts that to the empty string.

Try it online

# Answer
> 0 votes
# SOGL V0.12, 19 bytes

```
,M↕+'»m{Z²²+;╗ŗ}⁰№I

```

Try it Here!

# Answer
> 0 votes
# Octave, 61 bytes

```
@(s)[((a=[30:55 13:22]'*~~(o=1:32)).*(a+35~=[s o](o)))+35 '']

```

Try it online!

The function works as follows:

```
@(s)[                                                     ''] %Anonymous function, taking string, outputting character array
         [30:55 13:22]'                                       %Creates the board alphabet ('A':'Z' '0':'9']) but minus 35 (value of '#')
                       *~~(o=1:32)                            %Matrix multiplication by an array of 32 1's to form the 2D board. Saves 1:32 for later.
      (a=                         )                           %Saves the board mimus 32 to a for use later.
                                            [s o](o)          %Ensures the input is 32 characters long. Missing chars replaced by 1:32 (not in board)
                                     (a+35~=        )         %Compares against board (a+35 as a=board-35). Makes 2D array where matches = 0, others = 1.
     (                             .*                )+35     %Element=wise multiplication, forcing matches to 0. Then add 35 resulting in board with #'s

```

# Answer
> 0 votes
# Perl 6, 57 bytes

```
{map {<<$^c█>>[.comb[^32]Xeq$c].join},|('A'..'Z'),|^10}

```

Try it online!

# Answer
> 0 votes
## F#, 250 bytes

```
let b(a:string)=
 let r=List.append['A'..'Z']['0'..'9']
 let mutable d=Map.empty
 for c in r do d<-Map.add c (Array.create 32 c)d
 for i=0 to a.Length-1 do if d.ContainsKey a.[i] then d.[a.[i]].[i]<-'█'
 for c in r do new string(d.[c])|>printfn"%s"

```

Try it online!

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


# Question
Title: What's the shortest way to define an anonymous recursive function in Octave?
I love functional programming in Octave, but it's rather unwieldy in practice. I'm wondering about the shortest way to define an anonymous recursive function.

I have some ideas, but I'm wondering if there is a way to combine these ideas to make them even shorter (or equally short but more versatile). For the sake of this question, let's recursively count down to zero (just to keep the payload as simple as possible).

If my reasoning is correct, none of the variable names I used in the following examples should overlap. The desired function is `q(n)`, which should always return zero. `i` is used as a counter variable, `f` is the recursive function which I have called `g` in the local scope of `f`.

### 44 bytes, "inline definition of `f`"

```
q=@(n)(f=@(g,i){@()g(g,i-1),i}{~i+1}())(f,n)

```

### 44 bytes, "argument list definition of `f`"

```
q=@(n,f=@(g,i){@()g(g,i-1),i}{~i+1}())f(f,n)

```

### 44 bytes, "separate definition of `f`"

```
f=@(i,g){@()g(i-1,g),i}{~i+1}();q=@(n)f(n,f)

```

### 41 bytes, "desired function as a return value"

```
f=@(g)@(n){@()g(g)(n-1),n}{~n+1}();q=f(f)

```

The current 'winner' is inspired by this answer by flawr. However, given the large range of different ways to do this, perhaps someone can think of an even shorter combination of methods.

The goal is of course to get it below 39 bytes for a "full" function, Try it online!

# Answer
# Octave, 39 bytes

```
q=f(f=@(g)@(n){@()g(g)(n-1),n}{~n+1}())

```

Try it online!
> 8 votes

---
Tags: code-golf, tips, octave
---


title: Evaluate a Skat-Hand

text:
# Question
Title: Evaluate a Skat-Hand
# Introduction

Skat is a traditional German card game for 3 players. The deck consists of 32 cards: Ace, King, Queen, Jack, 10, 9, 8, 7 in all 4 suits (Clubs, Spades, Hearts, Diamonds).

In every round there one player plays solo while the other two play against him. At the start of a round each player is dealt 10 cards, the remaining 2 card are called the *skat* and are put facedown in the middle. The solo player is determined by a bidding phase. This is the part of the game that you will have to deal with in this challenge, more details on this below.

The player who wins the bidding phase becomes the solo player. He picks up the skat and then drops two cards (which may be the same, the other team does not know), picks the trump suit, and the round starts.

One round consists of ten tricks. The player who wins a trick leads the next one until all cards are played. I won't explain the rules here, but you should know that having a lot of trump cards is good. If you want to learn about the rules check the Wikipedia article which I linked at the start of this post, but it is not needed for this challenge.

# The Challenge

You want to teach your two sons how to play skat. The rules are not that hard, so they quickly get into it. The only thing giving them a hard time is the bidding, specifically calculating the game value of their hand. So you decide to write a small program which outputs the maximum game value that they can bid given their current hand.

# Calculating the game value

Every hand has a certain game value. It is determined by the amount of sequential Jacks you have and the suit which you want to pick as trump. Let's start with the first factor, the jacks!

## The Jack Factor

Jacks are always trump cards, and they beat every other trump card. The order of strength between the four Jacks is:

1. Jack of Clubs (highest)
2. Jack of Spades
3. Jack of Hearts
4. Jack of Diamonds (lowest)

In the further explanation I will refer to them with the numbers I assigned to them here.

You remember that there is some kind of factor that you get from the Jacks in your hand which is parts of the game value? Great! Here is how you get it:

This Jack factor is the number of top Jacks (see order above) in sequence, plus 1. So if you have all 4 Jacks it is 4 + 1 = 5. If you have only the first 2 Jacks, it is 2 + 1 = 3.

Alternatively, to make things a bit more complicated, the Jack Factor can also be the number of top Jacks in sequence that you are **missing**, plus 1. So if you are missing the first one, it is 1 + 1 = 2. If you are missing he first 3, it is 3 + 1 = 4. Here some examples, using the numbering above:

```
[1, 4] -> 1 + 1 = 2
[1, 2, 4] -> 2 + 1 = 3
[2, 3, 4] -> 1 + 1 = 2
[1, 2, 3, 4] -> 4 + 1 = 5
[] -> 4 + 1 = 5

```

That was the first factor. Here is how you get the 2nd one:

## The Trump Suit Factor

This one is a lot simpler. The 2nd factor is determined by the trump suit that the solo player picks using the following mapping:

```
Clubs    -> 12
Spades   -> 11
Hearts   -> 10
Diamonds ->  9

```

That was easy, wasn't it?

## The Game Value

The game value is the product of the two factors. Pretty easy you think? Wrong! While the Jack-Factor is fixed, the suit-factor is not. The suit you end up picking as trump depends on the amount of trumps and the value of your non-trump cards in your hand. It would be way too complicated to explain what a good hand looks like, so you will use the following algorithm:

# The Which-Trump-do-I-Pick Algorithm

You don't have to participate in the bidding. If you decide that your hand is too bad to play solo, you can just pass. Your hand must match the following criteria to be playable:

* Have at least 6 trump cards (cards of the trump suit you pick + the number of Jacks). If this is possible for more than one suit, pick the one which would result in more trump cards. If there is *still* a tie, pick the suit with the highest rating given above.
* Out of the non-trump cards, have at least 1 Ace.

If your hand does not match both of this criteria, you will pass. If it does, you will output the calculated game value and the chosen trump suit.

*Short note: Of course this is a very simplified algorithm. There goes way too much strategy and experience into judging a hand than we could ever cover in a challenge like this.*

# Input

Every card has an unique identifier. The first part is the suit (**C**lubs, **S**pades, **H**earts, **D**iamonds), the second part is the value which is given by this mapping:

```
Ace -> A
King -> K
Queen -> Q
Jack -> J
10 -> 0
9 -> 9
8 -> 8
7 -> 7

```

Both parts combined form one card. The value comes first, then comes the suit. You may take the cards in any format as you want.

# Output

If the hand is playable, output the game value and the picked trump suit (order doesn't matter). If it's not, output "pass".

# Rules

* As mentioned you can take the input in the most convenient format for you. Examples see below in the test cases.
* Input may be provided by command line arguments, user input, or function arguments.
* Output may be provided as return value or may just be printed on the screen.
* The cards in the input may not be ordered in any way. Your program has to be able to deal with any random card order.
* Lowest byte-count wins!

# Testcases

Input in the test cases will be a list of 2-char Strings.

```
1. ["JC", "JS", "JD", "AC", "KC", "9C", "AS", "7H", "QD", "8D"] -> 36 Clubs
2. ["JD", "AS", "0S", "KS", "QS", "9S", "8S", "AD", "8C", "9C"] -> 44 Spades
3. ["JH", "JD", "0S", "KS", "9C", "8C", "QH", "KH", "AD", "9D"] -> pass
4. ["JD", "AS", "KS", "QS", "0S", "9S", "8D", "7D", "0C", "QH"] -> pass

```

Explanation:

1. Two Jacks in a row with Clubs as trump. So the game value is 3 x 12 = 36
2. Three Jacks in a row missing with Spades as trump. So the game value is 4 x 11 = 44
3. Only a maximum 4 of trump cards is possible, so you will pass.
4. Six trump cards with Spades but no non-trump ace, so you will pass.

*If some rules are unclear, go ahead and comment. I have grown up with this game, so it hard for me to judge if I described everything in enough detail.*

And now... **Happy Coding!**

**edit:** As pointed out to me in the comments (thanks to isaacg), there is a rule which counts the following top trumps after the 4 Jacks into the "Jack-factor" so it could go up to 11. To keep this challenge simple and to not confuse people, the rules I proposed originally will stay as they are. So the maximum factor stays at 5.

# Answer
> 1 votes
# Python 2, example implementation

Since there are no submissions yet, I wrote down an example implementation in Python. The input format is the same as in the testcases in the challenge.

Maybe that motivates you guys to get going, it's not that hard :)

```
def gameValue(hand):
    jacks = ""
    suits = {"C" : 0, "S" : 0, "H" : 0, "D" : 0}
    # Loop through the hand, find all jacks and count the cards of each suit
    for card in hand:
        jacks += card[1] if "J" in card else ""
        suits[card[1]] += 1 if card[0] != "J" else 0

    # Map the Jacks to numbers while 1 is the highest (Clubs) then sort them ascending
    jacks =  sorted(map(lambda j: {"C" : 1, "S" : 2, "H" : 3, "D" : 4}[j], list(jacks)))

    # Sort the suits by amount. Highest amount and value is first after that
    suits = sorted(suits.items(), key = lambda suit: suit[1], reverse = True)
    trumpSuit = suits[0][0];
    # Amount of trumps is jack-count plus trumpsuit-count
    trumpCount = len(jacks) + suits[0][1];

    # Check for at least one ace that is no trump
    hasAce  = len(filter(lambda c: c[0] == "A" and c[1] != trumpSuit, hand)) >= 1

    # If the hand  is playable, calculate jack-factor and output the result, otherwise pass
    if trumpCount >= 6 and hasAce:
        # If there no jacks the factor is 5. If there are, find the first gap
        if len(jacks) > 0:
            lastJack = 0
            for jack in jacks:
                if jack - lastJack >= 2:
                    break
                lastJack = jack

            jackFactor = jacks[0] if lastJack == 0 else lastJack + 1
        else:
            jackFactor = 5

        trumpFactor = {"C" : 12, "S" : 11, "H" : 10, "D" : 9}[suits[0][0]]
        print str(trumpFactor * jackFactor) + " " + {12 : "Clubs", 11 : "Spades", 10 : "Hearts", 9 : "Diamonds"}[trumpFactor]
    else:
        print "pass"

```

# Answer
> 0 votes
# Java, 256 bytes

```
h->{int i,j=1,m=0,t,n=0,a[]=new int[8];for(var c:h){t=c[1]-48;if(c[0]==74){j+=1<<t;n++;}else{m+=i=c[0]==65?1:0;a[--t+4]+=i;a[t]++;}}for(i=t=0;i<4;i++)t=a[i]<a[t]?t:i;return a[t]+n<6|m-a[t+4]<1?"p":(t+++9)*(5-(int)(Math.log(j>7?~j&7:j)/Math.log(2)))+" "+t;}

```

Takes input as an array of character arrays in the format `A4`, where `4` is *Clubs*, `3` is *Spades*, `2` is *Hearts* and `1` is *Diamonds*. Output is `36 4` for a bid of 36 with trump suit *Clubs*, `p` for passing.

Try it online here.

Ungolfed version:

```
h -> { // lambda taking a char[][] as argument and returning a String
    int i,                // used as a loop variable and as a temporary variable
        j = 1,            // variable storing the jacks present in the hand in its four last-to-least significant bits
        m = 0,            // number of aces in the hand
        t,                // used as a temporary variable at first, later stores the trump suit
        n = 0,            // number of jacks in the hand
        a[] = new int[8]; // in the lower 4 indices, stores the number of non-jack cards present in the hand for each suit; in the higher 4 indices, stores the number of aces present in the hand for each suit (0 or 1)

    for(var c : h) {   // loop over all the cards in the hand
        t = c[1] - 48; // determine the suit of the current card; 48 is the ASCII code for '0'
        if(c[0] == 74) { // if it's a jack; 74 is the ASCII code for 'J'
            j += 1 << t; // set the corresponding bit
            n++;         // and increment the total number of jacks
        } else {                             // if it's not a jack
            m += (i = (c[0] == 65 ? 1 : 0)); // increment the total number of aces if it's an ace (65 is the ASCII code for 'A')
            a[ --t + 4] += i;                // increment the number of aces for this suit if it's an ace
            a[t]++;                          // increment the number of non-jack cards for this suit
        }
    }

    for(i = t = 0; i < 4; i++)     // loop over the suits ...
        t = (a[i] < a[t]) ? t : i; // ... and find the one with the most cards, giving priority to higher-valued suits in case of a tie

    return (a[t] + n < 6) |                                             // if there are less than 6 trump cards
           (m - a[t + 4] < 1) ?                                         // or less than 1 non-trump ace
           "p"                                                          // return "p" to pass on the hand
           :                                                            // else return
           ((t++ + 9) *                                                 // the value of the trump suit (and increment the trump suit for output later)
           (5 - (int) (Math.log((j > 7) ? (~j & 7) : j) / Math.log(2))) // times the jack factor
           + " " + t);                                                  // followed by the trump suit
}

```

# Answer
> 0 votes
# C, 235 bytes

```
f(char*h){int i,j=1,m=0,t,n=0,a[8]={0};for(;*h;h+=2){t=h[1]-48;if(*h-74){m+=i=*h==65;a[--t+4]+=i;a[t]++;}else{j+=1<<t;n++;}}for(i=t=0;i<4;i++)t=a[i]<a[t]?t:i;printf(a[t]+n<6|m-a[t+4]<1?"p":"%d %d",(t+9)*(5-(int)log2(j>7?~j&7:j)),t+1);}

```

Port of my Java answer.

Try it online here.

Takes input as an array of characters in the format `A4`, where `4` is *Clubs*, `3` is *Spades*, `2` is *Hearts* and `1` is *Diamonds*. Output is `36 4` for a bid of 36 with trump suit *Clubs*, `p` for passing.

Ungolfed version:

```
f(char* h) { // function taking an array of characters as argument (and implicitly returning an unused int)
    int i,          // used as a loop variable and as a temporary variable
        j = 1,      // variable storing the jacks present in the hand in its four last-to-least significant bits
        m = 0,      // number of aces in the hand
        t,          // used as a temporary variable at first, later stores the trump suit
        n = 0,      // number of jacks in the hand
        a[8] = {0}; // in the lower 4 indices, stores the number of non-jack cards present in the hand for each suit; in the higher 4 indices, stores the number of aces present in the hand for each suit (0 or 1); partially initialized to zero, the compiler will do the rest

    for(; *h; h += 2) { // loop over all the cards in the hand
        t = h[1] - 48;  // determine the suit of the current card; 48 is the ASCII code for '0'
        if(*h - 74) {              // if it's not a jack; 74 is the ASCII code for 'J'
            m += (i = (*h == 65)); // increment the total number of aces if it's an ace (65 is the ASCII code for 'A')
            a[ --t + 4] += i;      // increment the number of aces for this suit if it's an ace
            a[t]++;                // increment the number of non-jack cards for this suit
        } else {         // if it's a jack
            j += 1 << t; // set the corresponding bit
            n++;         // and increment the total number of jacks
        }
    }

    for(i = t = 0; i < 4; i++)   // loop over the suits ...
        t = a[i] < a[t] ? t : i; // ... and find the one with the most cards, giving priority to higher-valued suits in case of a tie

    printf( (a[t] + n) < 6 |                             // if there are less than 6 trump cards
            (m - a[t + 4] < 1) ?                         // or less than 1 non-trump ace
            "p" : "%d %d",                               // print "p" to pass on the hand, else print two numbers
            (t + 9) *                                    // first the value of the trump suit ...
            (5 - (int) log2((j > 7) ? (~j & 7) : j)),    // ... times the jack factor,
            t + 1                                     ); // followed by the trump suit
}

```

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


title: 100 Prisoners and a light bulb

text:
# Question
Title: 100 Prisoners and a light bulb
### 100 Prisoners and a light bulb

You may have seen this puzzle over on the puzzles exchange or perhaps heard it somewhere else. If you are unfamiliar with this puzzle check out:
100 Prisoners and a Light bulb

The gist of this puzzle is that there are 100 prisoners, each one is separated from one another and must go into a room one at a time. The prisoner selected to go into the room is selected uniformly at random each time. In this room there is a light bulb and a switch, the prisoner must either turn the light on, turn the light off, or do nothing. At any given time one of the prisoners may say that all 100 prisoners have been in the room at least once. If he is correct they are all freed, if they are incorrect they are all killed. Prior to being separated the group of prisoners may discuss a strategy and they may never communicate again.

### One working strategy:

> The prisoners select one prisoner as the leader. When anyone else enters the room they do nothing unless it's the first time they enter the room and the light is off; in that case, they turn the light on. When the leader enters the room and the light is on then he turns the light off and maintains a counter, adding one to it. Once he counts 99 (the light has been turned on once for every other prisoner) he knows that all 100 (including himself) have been in the room, and he claims their freedom.

### The code challenge:

Take no input into your program.

Simulate the strategy and output the number of times a prisoner entered the room before the leader claimed their freedom.

`n` represents the number of times a prisoner enters the room for the first time.
`k` represents the leader of the prisoners.
`d` represents a data structure holding boolean values for each prisoner.
`l` represents a boolean value to hold the state of the light bulb.
`i` represents the number of iterations of the puzzle before it ends.

### Examples:

Randomly pick an element from `d`. if `l` is false and `k[rand]` is false then `l` is now true and `d[rand]` is true. `i = i + 1`

Randomly pick an element from `d`. if `l` is true and `d[rand]` is false then do nothing. `i = i + 1`

Randomly pick an element from `d`. if `l` is false and `d[rand]` is true then do nothing. `i = i + 1`

Randomly pick an element from `d`. if `d[rand] = k` and if `l` is false then do nothing. `i = i + 1`

Randomly pick an element from `d`. if `d[rand] = k` and if `l` is true, set `l` to false, add 1 to `n`. `i = i + 1`

Randomly pick an element from `d`. if `d[rand] = k` and if `l` is true and `n = 99` then end puzzle. `i = i + 1` and output `i`.

this is so the shortest code wins. Have Fun!

# Answer
# Python 2, 133 bytes

I used binary operations to keep track. I had `if(i<1)*b:...` but I think that's an off-by-one error. Not sure.

```
from random import*
L=2**99-1
b=l=c=0
while l<99:
    i=randint(0,99)
    if(i>98)*b:b=0;l+=1
    elif(L&1<<i)*(b<1):b=1;L|=1<<i
    c+=1
print c

```

**Try it online**

**Less golfed:**

```
from random import*
L=[1for _ in range(100)]
b=l=c=0
while l<99:                         # check leader's count of prisoners
    i=randint(0,99)
    if b and i==99:b=0;l+=1         # if light on and leader, turn off and count
    elif L[i] and b<1:b=1;L[i]=0    # else if new prisoner and light off, turn on
    c+=1                            # iterations
print c

```
> 2 votes

# Answer
## CJam (26 bytes)

```
100,1a*0-{{__100mr>!}g;}%,

```

### Dissection

```
100,1a*0-  e# Generate a list [1 1 1 2 1 3 1 ... 98 1 99] representing (in reverse order)
           e# the number of prisoners at each step who can advance to the next step
{          e# For each element in the list...
  {        e#   While we fail to select a suitable prisoner...
    __     e#     dup twice: once to leave on stack as a counter, and once for comparison
    100mr  e#     Select a random prisoner
    >!     e#     Test whether that prisoner is suitable
  }g
  ;        e#  Pop to avoid overcounting by one
}%
,          e# Count up the values we left on the stack

```
> 2 votes

# Answer
# Perl 5, 77 bytes

```
++$i,($s=0|rand 100)?!$a[$s]&&!$l++&&$a[$s]++:$l&&++$n&($l=0)while$n<99;say$i

```

Try it online!
> 1 votes

# Answer
## Python 3, 164 bytes, aka garbage :)

```
from random import*
d={}
a=l=n=p=0
for i in range(100):
 d[i]=0
while n<100:
 a+=1
 p=randint(0,99)
 if p==50:
  l=0
 else:
  l=1
 if d[p]==0:
  d[p]=1
  n+=1
print(a)

```
> 0 votes

---
Tags: code-golf, puzzle-solver
---


title: Take CR and LF literally

text:
# Question
Title: Take CR and LF literally
*As a celebration of good old Notepad, we are going to treat carriage returns and line feeds as what they originally meant, rather than what they are (ab-)used for today.*

Given a string consisting of printable ASCII plus line feeds (␊; LF; esc `\n`; hex 0A; dec 10) and carriage returns (␍; CR; esc `\r`; hex 0D; dec 13), **cause Try It Online to show how the printable characters would be positioned** if printed on a printer which takes those two control characters literally:

1. upon a line feed, continue printing one line further down
2. upon a carriage return continue printing from the left edge
3. multiple consecutive carriage returns behave like a single carriage return

Due to modern devices having problems with overstriking, a run of one or more of carriage returns will, except for at the beginning of the input, never occur without at least one preceding and/or following line feed. However, two runs of carriage returns may be separated by a single line feed.

Any amount of additional trailing white space is acceptable, both on the right-hand side of any lines and below the entire text, as long as at least the amount of white space given in the input is preserved.

### Examples (using `\n` and `\r` for line feed and carriage return)

`Lorem ipsum dolor sit amet,`

```
Lorem ipsum dolor sit amet,

```

---

`consectetur adipiscing\nelit, sed`

```
consectetur adipiscing
                      elit, sed

```

---

`do eiusmod\r\ntempor incididunt\n\n ut labore`

```
do eiusmod
tempor incididunt

                  ut labore

```

---

`et dolore\n\rmagna \r\r\naliqua. Ut` (notice the trailing spaces)

```
et dolore
magna
aliqua. Ut

```

---

`\nenim ad minim veniam,\n\r quis nostrud`

```

enim ad minim veniam,
     quis nostrud

```

---

`\rexercitation\r\n\rullamco laboris\n\r\nnisi ut aliquip ex\n\n\rea commodo consequat.\n\n`

```
exercitation
ullamco laboris

nisi ut aliquip ex

ea commodo consequat.

```

# Answer
> 6 votes
# Charcoal, 10 bytes

```
ＵＴＦθ«ι≡ι⸿↑

```

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

```
ＵＴ

```

Disable right padding.

```
Ｆθ«

```

Loop over the input.

```
ι

```

Print the current character. This automatically handles `\n` (which Charcoal treats as `\v` in this context) but Charcoal translates `\r` into `\r\n`, so...

```
≡ι⸿

```

... check for an `\r`...

... and if so then move back up a line.

# Answer
> 5 votes
# Ruby, ~~24~~ 17 bytes

```
->s{s.tr $/,"\v"}

```

Try it online!

It does not work on TIO, but works on the Linux console.

# Answer
> 4 votes
# Java 10, ~~211~~ ~~207~~ 206 bytes

```
s->{var a=s.replace("\r\n","\n\r").split("(?<=\n)");int i=0,p=0,j;for(var x:a){for(j=x.charAt(0)<14?0:p;j-->0;x=" "+x);j=(a[i++]=x.replace("\r","")).length()-1;p=x.matches("\\s+")?p:j;}return"".join("",a);}

```

Try it online.

**Explanation:**

```
s->{                      // Method with String as both parameter and return-type
  var a=s.replace("\r\n","\n\r")
                          //  Replace all "\r\n" with "\n\r"
        .split("(?<=\n)");//  Create String-array split by "\n",
                          //  without removing the trailing "\n" delimiter
  int i=0,                //  Index integer
      p=0,                //  Previous line-length, starting at 0
      j;                  //  Temp integer
  for(var x:a){           //  Loop over the String-array
    for(j=x.charAt(0)<14?0//   If the current line starts with either '\r' or '\n':
        0                 //    Prepend no spaces
       :                  //   Else:
        p;j-->0;x=" "+x); //    Prepand `p` amount of spaces for the current item
    j=(a[i++]=x.replace("\r",""))
                          //   Remove all "\r" from the current line
       .length()-1;       //   Set `j` to the current line-length (minus the trailing '\n')
    p=x.matches("\\s+")?  //   If the current line only contains '\r', '\n' and/or spaces:
       p                  //    Leave `p` unchanged
      :                   //   Else:
       j;}                //    Change `p` to this line-length minus 1
  return"".join("",a);}   //  Return the String-array joined together

```

---

Old answer before the challenge was changed **~~151~~ 148 bytes**:

```
s->{String a[]=s.replace("\r\n","\n\r").split("(?<=\n)"),r="";int p=0,i;for(var x:a){for(i=p;i-->0;r+=" ");i=x.length()-1;p=i<1?p:i;r+=x;}return r;}

```

**Explanation:**

```
s->{                            // Method with String as both parameter and return-type
  String a[]=s.replace("\r\n","\n\r")
                                //  Replace all "\r\n" with "\n\r"
              .split("(?<=\n)"),//  Create String-array split by "\n",
                                //  without removing the trailing "\n" delimiter
         r="";                  //  Result-String, starting empty
  int p=0,                      //  Previous line-length, starting at 0
      i;                        //  Index (and temp) integer
  for(var x:a){                 //  Loop over the String-array
    for(i=p;i-->0;r+=" ");      //   Append `p` amount of spaces to the result
    i=x.length()-1;p=i<1?p:j;   //   If the current line is not empty:
                                //    Replace `p` with the length of this current line
    r+=x;}                      //   Append the current item
  return r;}                    //  Return the result-String

```

Doesn't work on TIO, does work on Windows Command Prompt:

# Answer
> 3 votes
# Python 2, ~~150~~ ~~128~~ ~~122~~ ~~104~~ 103 bytes

```
def f(s):
 i=n=0;l=''
 for c in s:l,n,i=[l,l+c,l+' '*i*n+c,n,1,0,0,i,i+1]['\r\n'.find(c)%3::3]
 print l

```

Try it online!

---

Saved:

* -1 byte, thanks to Lynn

# Answer
> 3 votes
# JavaScript (Node.js), 85 bytes

```
s=>s[R='replace'](/(.*)([\n\r]+)/g,(_,t,b)=>t+b[R](/\r/g,_=>s='',s=t[R](/./g,' '))+s)

```

Try it online!

# Answer
> 3 votes
# C (gcc), ~~100~~ 94 bytes

```
b,c,d;f(char*s){for(b=13;b;b=*s++)b==13?c=d=0:b-10?d=!printf("%*c",++d,b),++c:putchar(b,d=c);}

```

Assumes ASCII coding (`'\r'==13`, `'\n'==10`); adjust to suit on other systems.

Try it online! (requires Javascript)

## Readable version

```
int c = 0;
int d = 0;

f(char*s)
{
    for (;*s;++s) {
        switch (*s) {
        case'\r':
            c = d = 0;
            break;
        case'\n':
            d = c;
            putchar(*s);
            break;
        default:
            printf("%*s%c", d, "", *s);
            d = 0;
            ++c;
        }
    }
}

```

`c` is the current column position; `d` is the number of spaces that must be inserted before a printable character. Both are assumed to be zero on entry to the function.

## Test program

```
int main(int argc, char **argv)
{
    char s[1024];
    if (argc <= 1)
        while (fgets(s, sizeof s, stdin))
               f(s);
    else
        for (int i = 1;  i < argc;  ++i)
            f(argv[i]);
}

```

# Answer
> 2 votes
# Python 3, ~~101~~ 94 bytes

Based on TFeld's answer.

```
def f(s):
 i=n=0
 for c in s:k='\r\n'.find(c);a=k&1;print(end=-k*' '*i*n+c*a);n=k>0;i=i*a-k//2

```

Try it online!

---

## Ungolfed

```
def f(s):
  i=0  # position of the cursor
  n=0  # was the last character LF?
  for c in s:        # iterate over the input
    k='\r\n'.find(c) # k := 0 for CR, 1 for LF and -1 for every other character
    a=k&1            # as (-1)&1 == (1)&1 == 1, this is a := abs(k)
    print(end=-k*' '*i*n+c*a) # If c is a normal character (k == -1) and the last character was LF,
                              # print leading spaces. If c is not CR, print it
    n=k>0            # n := True if c is LF, False otherwise
    i=i*a-k//2       # If c is either a newline or a printable character (a == 1),
                     # keep the cursor's position and increment it for a printable character ((-1)//2 == -1)

```

# Answer
> 2 votes
# Clean, ~~92~~ 91 bytes

**-1 thanks to Laikoni!**

*Note:* `\` in `\r` is omitted from bytecount as Linux CG handles literal `\r` and `\n`s.
*Note:* Windows CG requires `\n` and `\r` be escaped, so +3 if it has to run on Windows.

```
import StdEnv
?n['\r':t]= ?0t
?n['
':t]=['
':spaces n]++ ?n t
?n[h:t]=[h: ?(n+1)t]
?_ e=e

```

#

```
?0

```

Try it online!

A partial application of `? :: Int [Char] -> [Char]` with 0 as the initial first argument. This descends through each character keeping track of how many traversed, the count resets when it encounters a carriage return and when it encounters a newline it adds spaces equal to the number of characters traversed at that point.

# Answer
> 1 votes
# Haskell, ~~93~~ 87 bytes

```
l=0#0
(n#x)(t:r)|t=='\n'=t:(n#1)r|t=='\r'=l$r|m<-n+1=(' '<$[1..n*x])++t:(m#0)r
(_#_)e=e

```

Try it online!

---

Pretty straightforward solution. # is an infix function that recursively creates the output one character at a time while keeping a character position counter (n) and flag for when to add spaces after a newline (x).

---
Tags: code-golf, string, typography
---


title: Generalized Gray codes

text:
# Question
Title: Generalized Gray codes
**Input:** An array **I** of **k** positive integers. The integers will be no larger than 100 and **k ≤ 100**.

**Output:** Your code must output all possible arrays **O** of non-negative integers of length **k** with the restriction that **0 ≤ Oi ≤ Ii**. To get from one array to the next you may add or subtract 1 to one value in the array. Your code must not output the same array twice. If the number of different arrays to be output is very large, your code should just carry on outputting forever until it is killed.

**Examples**

* If **I** is an array of **k** ones then this is exactly the problem of iterating over all Gray codes of bit width **k**, except that the first and the last element do not need to be reachable in one step.
* If `I = [2,1]` then one possible ordering of the output arrays is `(0,0),(0,1),(1,1),(1,0),(2,0),(2,1)`
* If `I = [2,1,3]` then one possible ordering of the output arrays is `(0,0,0),(0,0,1),(0,0,2),(0,0,3),(0,1,3),(0,1,2),(0,1,1),(0,1,0),(1,1,0),(1,1,1),(1,1,2),(1,1,3),(2,1,3),(2,1,2),(2,1,1),(2,1,0),...`.

This is a code-golf challenge, the submission with the source code with the shortest length wins. Don't let the short answers in golfing languages discourage you from posting an answer in other languages. Try to come up with the shortest answer in any language.

This is also a restricted-complexity challenge. Every new array should be output with **O(k)** time elapsing since the previous outputted array (or the start of the program for the first array outputted). This means that the running time per new output array (they are each of length **k**) should be no greater than **O(k)**. That is it should take time proportion to **k** and not, for example **k2** or **2k**. Note this is not the average time per output but the worst case time for each and every array outputted.

You can assume that all arithmetic on 64 bit integers can be performed in constant time as can reading and outputting them as well as assignment and looking up and changing values in arrays.

One consequence of the restricted-complexity is that solutions that only output at program exit are not acceptable.

# Answer
# Python 3, 116 bytes

```
def f(a):
 l=len(a);t=[0]*l;d=[1]*l
 while 1:
  i=0;yield t
  while not-1<t[i]+d[i]<=a[i]:d[i]*=-1;i+=1
  t[i]+=d[i]

```

Try it online!

Thanks Mnemonic for -1 byte.

Generator function. (thanks Dennis for reminding me, I forgot the feature exists) If the output should be printed to stdout then use `print(t,flush=1)` for 9 additional bytes, or if Python is called with `-u`, `print(t)` suffices for +1 bytes.

Stops with an error (`IndexError`). If you want to call this function and then continue the program, you have to catch it.
> 4 votes

# Answer
# Stax, 22 bytes

```
▒)∙ñ╚▀NK♀F☺S(A#P`░]╪Db

```

Run and debug it

Here's a big one to show the asymptotic behavior Press run.

Unpacked, ungolfed, and commented, it looks like this.

```
,           pop from input to main stack
W           run the rest of the program repeatedly until explicitly cancelled
  cJP       copy top of stack and print, delimited by spaces
            get the index to mutate
  i^            iteration index + 1
  x{^|%}I       repeatedly apply divmod using l[k]+1 from input
                get the index of the first value that returns modulus >0
  cU=C      if the result is -1 (no match), then terminate the program
            get the direction to mutate
  s             get the "div" part of the last div operation called "d"
  ^|1           -1 ^ (d+1)
  ~{+}&     increment element in array at the index by the calculated amount

```

Run this one
> 2 votes

# Answer
# Kotlin, ~~181~~ 178 bytes

Thanks to: Anush pointed out I misunderstood the challenge saving 2 bytes. ovs pointed out a 1 byte savings.

```
val p={a:List<Int>->var l=a.size
val v=Array(l,{0})
val i=Array(l,{1})
l-=1
o@while(0<1){println(v)
var p=l
while(v[p]+i[p]!in 0..a[p]){i[p]*=-1
p-=1
if(p<0)break@o}
v[p]+=i[p]}}

```

Try it online!
> 1 votes

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

```
a=>{b=a.map(_=>0);c=a.map(_=>1);for(i=0;a[i];b[i]+=c[i]||-1){console.log(b);for(i=0;b[i]==a[i]*c[i];i++)c[i]^=1;}}

```

Try it online! Ungolfed:

```
function ggray(maxima) {
    var current = Array(maxima.length).fill(0);
    var flag = Array(maxima.length).fill(1);
    for (;;) {
        console.log(current);
        for (var i = 0; ; i++) {
            if (i == maxima.length) return;
            if (current[i] != maxima[i] * flag[i]) break;
            flag[i] = 1 - flag[i];
        }
        if (flag[i]) current[i]++;
        else current[i]--;
    }
}

```
> 1 votes

---
Tags: code-golf, restricted-complexity
---