title: How many syllables in that number?

text:
# Question
Title: How many syllables in that number?
I'd love to take a number and know how many syllables are in it, when spoken in English.

Let's limit this to positive integers which are less than one thousand.

I'm British, so we're going to follow the hundreds column with an 'and' when there are any non-zero digits after it.

# The Challenge

* Write some code which will accept a positive integer lower than 1000 and output the number of syllables in the words which represent that number in British English.
* It DOES NOT need to generate the words to represent the numbers, only the number of syllables they contain.
* It's code golf, attempt to achieve this in the fewest bytes.
* Use any language you like.
* The standard loopholes are forbidden.

# Test Cases

```
|  N  | In words                             | Syllables |
|   1 | one                                  |         1 |
|   2 | two                                  |         1 |
|   3 | three                                |         1 |
|   4 | four                                 |         1 |
|   5 | five                                 |         1 |
|   6 | six                                  |         1 |
|   7 | sev-en                               |         2 |
|   8 | eight                                |         1 |
|   9 | nine                                 |         1 |
|  10 | ten                                  |         1 |
|  11 | el-ev-en                             |         3 |
|  12 | twelve                               |         1 |
|  13 | thir-teen                            |         2 |
|  14 | four-teen                            |         2 |
|  17 | se-ven-teen                          |         3 |
|  20 | twen-ty                              |         2 |
|  21 | twen-ty one                          |         3 |
|  42 | four-ty two                          |         3 |
|  73 | sev-en-ty three                      |         4 |
|  77 | sev-en-ty sev-en                     |         5 |
| 100 | one hund-red                         |         3 |
| 110 | one hund-red and ten                 |         5 |
| 111 | one hund-red and el-ev-en            |         7 |
| 555 | five hund-red and fif-ty five        |         7 |
| 700 | sev-en hund-red                      |         4 |
| 770 | sev-en hund-red and sev-en-ty        |         8 |
| 777 | sev-en hund-red and sev-en-ty sev-en |        10 |
| 999 | nine hund-red and nine-ty nine       |         7 |

```

# Answer
> 12 votes
# Python 2, ~~84~~ ~~83~~ ~~74~~ 67 bytes

```
lambda n:4*(n>99)+2-n%~9/9-0x55561aaaab/4**(n%100)%4+`n`.count('7')

```

*Thanks to @xnor for golfing off ~~9~~ 16 bytes!*

Try it online!

---

# Python 2, 79 bytes

```
lambda n:4*(n>99)+([-1]+10*[1]+[3,1]+7*[2]+8*([2]+9*[3]))[n%100]+`n`.count('7')

```

Straightforward, but longer.

Try it online!

# Answer
> 8 votes
# Perl 5 `-p`, ~~53~~ 51 bytes

```
$_=4*/.../+2*/[^0].$/+!/0$/+y/7//-/1[^1]$/-/00|12$/

```

Try it online!

**How**

```
-p commandline flag reads input into $_

$_=4*/.../     # Hundreds place has minimum of 4 sylables (__ HUN-DRED AND),
               # match fails on number <100, and would add 0 here
  +2*/[^0].$/  # Tens place has two syllables if not 0 (__-TY or __TEEN),
               # match fails on numbers <10, and would add 0
  +!/0$/       # Ones place has one syllable if not 0 (__)
               # -- Now adjust for special cases --
  +y/7//       # add a syllable for every 7 present
  -/1[^1]$/    # remove a syllable for 10-19, except 11
  -/00|12$/    # remove the syllable for AND if it's an even hundred
               # OR remove another syllable for 12

-p commandline flag outputs contents of $_

```

# Answer
> 7 votes
# Python 2, ~~112~~ 108 bytes

```
f=lambda n:n>99and f(n/100)+3+f(n%100)-(n%100<1)or n>19and f(n/10)-~f(n%10)or int("01111112111312222322"[n])

```

Try it online!

<sub>-4 bytes, thanks to Shaggy</sub>

# Answer
> 7 votes
# JavaScript (ES6), 89 bytes

```
n=>(s='01111112111312222322',n>99&&+s[n/100|0]+3-!(n%=100))+~~(s[n]||+s[n/10|0]-~s[n%10])

```

Try it online!

# Answer
> 6 votes
# JavaScript, ~~86~~ 84 bytes

A tweaked port of TFeld's Python solution.

```
f=n=>n>99?f(n/100)+3+f(n%=100)-!n:n>19?f(n/10)-~f(n%10):+"01111112111312222322"[n|0]

```

Try it online

2 bytes saved thanks to Arnauld

# Answer
> 6 votes
# Java 11, ~~105~~ 102 bytes

```
n->(""+"".repeat(8)).charAt(n%100)+(n+"").split("7",9).length-(n>99?2:6)
```

Contains loads of unprintable characters.

-3 bytes thanks *@OlivierGrégoire*.

Try it online.

**Explanation:**

```

n->               // Method with integer as both parameter and return-type
  (""
                  //  Push string with ASCII-value digits 46666666666867777777
 +"".repeat(8))
                  //  Appended with 8 times a string with ASCII-value digits 7888888888
   .charAt(n%100) //  Take the (input modulo-100)'th character of this string (as integer)
  +(n+"").split("7",9).length
                  //  Count the amount of 7s in the input + 1
  -(n>99?         //  And if the input is larger than 99:
     2            //   Subtract 2 (-1 for the 7s+1 count; -5 to map the ASCII-digits to:
                  //               4 → -1; 6 → 1; 7 → 2; 8 → 3;
                  //               and +4 for the inputs above 99)
    :             //  Else:
     6)           //   Subtract 6 (-1 for the 7s+1 count and -5 to map the ASCII-digits to:
                  //               4 → -1; 6 → 1; 7 → 2; 8 → 3)
```

# Answer
> 6 votes
# Wolfram Language ~~101~~ 115 Bytes

```
s=StringSplit;Length[Join@@(WordData[#,"Hyphenation"]&/@Join@@s/@
s[IntegerName@#,"-"])]+Boole[#>100&&#~Mod~100!=0]&

```

## Explanation

(substituting `StringSplit` for `s`)

```
Length[Join@@(WordData[#,"Hyphenation"]&/@Join@@
StringSplit/@ StringSplit[IntegerName@#,"-"])]+Boole[#>100&&#~Mod~100!=0]&

```

`IntegerName` renders the number in American English (i.e. without "and" included in numbers greater than 100.) E.g. `777-> "seven hundred seventy-seven`.

`StringSplit[IntegerName@#,"-"]` removes any hyphens in the rendering.

`StringSplit/@` splits the rendering into words.

`Join@@` leaves a simple list of words, without embedded list (in the case that a hyphen appeared).

`WordData[#,"Hyphenation"]` breaks up a single word into its syllables.

`Join@@` leaves a simple list of syllables in all of the words.

`Length` counts the syllables

`+Boole[#>100&&#~Mod~100!=0]` adds `1` to the syllable count for those numbers greater than 100 (because of the additional "and" employed in the British English rendering), excluding integral multiples of 100.

# Answer
> 5 votes
# 05AB1E, ~~34~~ 31 bytes

```
т%U7¢I€Ā`Iт@3*X_(X20@X12Q(X11QO

```

Try it online or verify all `[1,999]` test cases.

**Explanation:**

With all checks mentioned it will result in 1 for truthy and 0 for falsey.

```
т%         # Take modulo-100 of the (implicit) input
           #  i.e. 710 → 10
  U        # Pop and store it in variable `X`
7¢         # Count the amount of 7s in the (implicit) input
           #  i.e. 710 → 1
I€Ā        # Trutify each digit in the input (0 if 0; 1 otherwise)
   `       # And push all of the mapped values to the stack
           #  i.e. 710 → [1,1,0]
Iт@        # Check if the input is larger than or equal to 100
           #  i.e. 710 → 1 (truthy)
   3*      # Multiply that result by 3 (for 'hund-red and')
           #  i.e. 1 → 3
X_         # Check if variable `X` is 0
           #  i.e. 10 → 0 (falsey)
  (        # And negate that (to remove 'and' when #00)
           #  i.e. 0 → 0
X20@       # Check if variable `X` is larger than or equal to 20 (for '-ty')
           #  i.e. 10 → 0 (falsey)
X12Q       # Check if variable `X` is exactly 12
           #  i.e. 10 → 0 (falsey)
    (      # And negate that (to remove 'teen')
           #  i.e. 0 → 0
X11Q       # Check if variable `X` is exactly 11 (for 'el-ev-en' minus 'one one')
           #  i.e. 10 → 0 (falsey)
O          # Sum everything on the stack (and output implicitly)
           #  i.e. [1,1,1,0,3,0,0,0,0] → 6

```

# Answer
> 5 votes
# Jelly, ~~28~~ ~~25~~ 23 bytes

```
9ḊŻ;2+⁵Żċ%ȷ2$ạDṠḄƊ+Dċ7Ɗ

```

Try it online!

### How it works

```
9ḊŻ;2+⁵Żċ%ȷ2$ạDṠḄƊ+Dċ7Ɗ  Main link. Argument: n (integer in [1, ..., 999])

9                        Set the return value to 9.
 Ḋ                       Dequeue; yield [2, 3, 4, 5, 6, 7, 8, 9].
  Ż                      Zero; yield [0, 2, 3, 4, 5, 6, 7, 8, 9].
   ;2                    Concat 2, yield [0, 2, 3, 4, 5, 6, 7, 8, 9, 2].
     +⁵                  Add 10; yield [10, 12, 13, 14, 15, 16, 17, 18, 19, 12].
       Ż                 Zero; yield [0, 10, 12, 13, 14, 15, 16, 17, 18, 19, 12].
         %ȷ2$            Yield n % 1e2.
        ċ                Count the occurrences of the modulus in the array.
                 Ɗ       Combine the three links to the left into a monadic chain.
              D            Decimal; convert n to its array of digits in base 10.
               Ṡ             Take the sign of each decimal digit (0 or 1).
                Ḅ            Convert the array of signs from base 2 to integer.
             ạ           Compute the abs. difference of the results to both sides.
                      Ɗ  Combine the three links to the left into a monadic chain.
                   D       Decimal; convert n to its array of digits in base 10.
                    ċ7     Count the number of 7's.

```

# Answer
> 5 votes
# Charcoal, ~~39~~ 31 bytes

```
Ｉ⁻⁺↨Ｅθ¬¬Ｉι²№θ7Ｉ§⁺”)∨∧⌈a¡↶”×0⁸⁰Ｎ

```

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

```
Ｉ⁻⁺

```

Calculate adjustments to the number of syllables and output the result as a string.

```
↨Ｅθ¬¬Ｉι²

```

Start by changing each non-zero digit to 1 and then decoding as base 2. This gives the correct answer for most inputs.

```
№θ7

```

Add 1 for each `7`.

```
Ｉ§⁺”)∨∧⌈a¡↶”×0⁸⁰Ｎ

```

Take the literal string `10000000001021111111` and append 80 zeros, then cyclically index by the input, and subtract that digit.

# Answer
> 3 votes
# PHP, ~~190~~ ~~158~~ ~~145~~ ~~141~~ 137 bytes

```
<?for($j=$p=0;$p<strlen($i=$argv[1]);)$j+=str_split($i)[$p++]>0;echo$j+substr_count($i,7)+3*($i>99)-!($i%=100)+($i>19)-($i==12)+($i==11);

```

Try it online!

A port of Kevin Cruijssen's solution (unfortunately it doesn't have the same brevity in PHP :) )

-~~32~~ 45 thanks to Shaggy!

-3 thanks to Kevin Crujissen!

# Answer
> 2 votes
# 05AB1E, 24 bytes

Port of Dennis' jelly answer

```
8L>Ć¾šT+¾šsт%¢sSĀJCαs7¢+

```

Try it online! or as a Test suite

**Explanation**

```
8L>                       # push range [2 ... 9]
   Ć                      # enclose, append head
    ¾š                    # prepend 0
      T+                  # add 10 to each
        ¾š                # prepend 0
          sт%¢            # count occurrences of input % 100 in this list
              sS          # push input split into a list of digits
                Ā         # truthify, check each if greater than 0
                 JC       # convert from base-2 to base-10
                   α      # absolute difference
                    s7¢+  # add the amount of 7's in the input

```

# Answer
> 1 votes
# 05AB1E, 26 bytes

```
€ĀJCI7¢•Ž¢Γ}Þ±6u•¾80×«Iè(O

```

Port of *@Neil*'s Charcoal answer, so make sure to upvote him as well if you like this answer!

Try it online or verify all test cases.

Compressed integer `•Ž¢Γ}Þ±6u•` can alternatively be `•8JA•b2TÌǝ` for the same byte-count.

**Explanation:**

```
€Ā                   # Trutify every digit in the (implicit) input
                     # (0 remains 0; everything else becomes 1)
  J                  # Join it together to a single string
   C                 # Convert from binary to integer
I7¢                  # Count the amount of 7s in the input
•Ž¢Γ}Þ±6u•           # Push compressed integer 10000000001021111111
          ¾80×«      # Append 80 "0"s
               Iè    # Index the integer (with automatic wraparound) into it
                 (   # Negate the result
O                    # Sum all values on the stack (and output implicitly)

```

See this 05AB1E answer of mine (section *How to compress large integers?*) to understand why `•Ž¢Γ}Þ±6u•` is `10000000001021111111`.

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


title: Seats in a Finnish cinema

text:
# Question
Title: Seats in a Finnish cinema
You're given the map of a cinema theatre as a boolean matrix: 0 represents a free seat, 1 - occupied. Each Finn who walks in chooses the seat farthest away (Euclidean distance) from the nearest occupied one, or if several such exist - the first among them in row-major order. Output a matrix showing the order seats will eventually be occupied in; that is, replace the 0s with 2, 3, 4, etc

```
// in
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
// out
 2  8  3  9  1
10  5 11  6 12
 4 13 14 15  7
16 17  1  1 18

// in
0 0 0 0 0 0 0 0 0 0 0 0 0 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 1 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 1 0 0 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 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
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
// out
  5  43  17  44  45  46  18  47   8  48  49   6  50  19  51   2
 52  24  53  54   1  55  56  25  57  26  58  59  27  60  28  61
 20  62  63  29  64  65   1  66  30  67  68  21  69   9  70  71
 72  73   1  74  31  75  76  77  78   1  79  80  32  81  82  11
 12  83  84   1  85  86  87  13  88  89  90  14  91  92  33  93
 94  34  95  96  97  15  98  99  35 100  36 101 102   1 103  22
104 105  37 106  38 107  39 108 109  16 110  40 111 112  41 113
  4 114 115   7 116  23 117   3 118 119  42 120   1 121 122  10

// in
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 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 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// out
  2  38 39  26  40   6 41  42  12  43  44   7  45  46  27  47   3
 48  49 15  50  28  51 52  29  53  30  54  55  56  16  57  31  58
 32  59 60  33  61  62 17  63  64  65  18  66  67  68  34  69  35
 70  10 71  72  13  73 74  75   1  76  77  78  11  79  80  14  81
 82  83 36  84  85  86 21  87  88  89  22  90  91  37  92  93  94
 19  95 96  97  23  98 99 100  24 101 102 103  25 104 105 106  20
107 108  4 109 110 111  8 112 113 114   9 115 116 117   5 118 119

```

I/O format is flexible within the established code golfing norms for your language. You can assume the input is correct, of size at least 3x3, and doesn't consist entirely of the same boolean value. Write a function or a complete program. The shortest solution per language is considered the winner; no answer will be accepted. Standard loopholes are forbidden.

# Answer
# MATL, 37 bytes

```
!t~z:Q"@yX:gG&n:!J*w:+X:&-|w/X<&X>(]!

```

Try it online! Or verify all test cases. You may also want to see the cinema being filled up in ASCII art.

### Explanation

```
!t        % Implicit input: M×N matrix of zeros and ones. Transpose and duplicate.
          % The transpose is needed because MATL uses column-major (not row-major)
          % order. It will be undone at the end
~z        % Number of zeros, say Z
:Q        % Range, add 1 element-wise: gives the array [2, 3, ..., Z+1]. These are
          % the new values that will be written into the matrix
"         % For each k in that array
  @       %   Push k. Will be written in a position to be determined
  y       %   Duplicate from below: pushes a copy of the current matrix, that has
          %   values up to k-1 already written in
  X:      %   Linearize into an (R*C)×1 vector, in column-major order
  g       %   Convert to logical: this replaces non-zero values by 1
  G&n     %   Push input size as two separate numbers: M, N
  :!      %   Range, transpose: gives the column vector [1; 2; ...; N]
  J*      %   Multiply by imaginary unit, 1j, element-wise
  w:      %   Swap, range: gives the row vector [1, 2, ..., M]
  +       %   Add, with broadcast. Gives an N×M complex matrix defining a grid of
          %   coordinates: [1+1j, ..., M+1j; 2+1j, ... 2+1j; ...; N+1j, ..., N+Mj]
  X:      %   Linearize into an (M*N)×1 vector, in column-major order
  &-|     %   (M*N)×(M*N) matrix of absolute differences. This gives all distances
          %   between seats. Rows of this matrix represent currently used seats,
          %   and columns correspond to potential new positions
  w/      %   Swap, divide with broadcast. This divides the rows representing
          %   occupied seats by 1, and those with unocuppied seats by 0. So the
          %   latter rows are set to infinity, which effectively removes them for
          %   the subsequent minimization
  X<      %   Mimimum of each column: this gives the minimum distance to currently
          %   occupied seats for each potential new seat
  &X>     %   Argument maximum: gives the index of the first maximizing value
  (       %   Write value k at that position, using linear indexing
]         % End
!         % Transpose. Implicit display

```
> 12 votes

# Answer
# JavaScript (ES6), ~~156~~ 137 bytes

*Saved 18 bytes thanks to @l4m2*

That's quite a lot of `map()` ...

```
f=(a,n=1)=>a.map(B=(r,y)=>r.map((_,x)=>a.map(b=q=>q.map(v=>b=b<(d=X*X--+Y*Y)|!v?b:d,X=x)&Y--,Y=y)|v|b<=B||(R=r,C=x,B=b)))|B?f(a,R[C]=++n):a

```

Try it online!

### Commented

```
f = (a, n = 1) =>               // a = input array; n = seat counter
  a.map(B =                     // initialize B to a non-numeric value
    (r, y) =>                   // for each row r at position y in a[]:
    r.map((_, x) =>             //   for each target seat at position x in r[]:
      a.map(b =                 //     initialize b to a non-numeric value
        q =>                    //     for each row q in a[]:
        q.map(v =>              //       for each reference seat v in q[]:
          b = b < (             //         if b is less than d, defined as
            d = X * X-- + Y * Y //           the square of the Euclidean distance
          ) | !v ?              //           or the reference seat is empty
            b                   //             let b unchanged
          :                     //           else:
            d,                  //             update b to d
          X = x                 //         start with X = x
        ) & Y--,                //       end of q.map(); decrement Y
        Y = y                   //       start with Y = y
      ) |                       //     end of inner a.map()
      b <= B ||                 //     unless b is less than or equal to B,
      (R = r, C = x, B = b)     //     update B to b and save this position in (R, C)
    )                           //   end of r.map()
  ) | B ?                       // end of outer a.map(); if B was updated:
    f(a, R[C] = ++n)            //   update the best target seat and do a recursive call
  :                             // else:
    a                           //   stop recursion and return a[]

```
> 11 votes

# Answer
# Haskell, ~~216~~ ~~213~~ ~~185~~ 184 bytes

```
import Data.Array
m a=[snd$maximum a|a/=[]]
f k=k//m[(r,((a,b),maximum(elems k)+1::Int))|s<-[assocs k],((a,b),0)<-s,r<-[minimum[(x-a)^2+(y-b)^2|((x,y),i)<-s,i>0]]]
(until=<<((==)=<<))f

```

Takes the input as an array. Input and output are in reverse order. Credit for fixed point magic to Laikoni.

Try it online!
> 3 votes

# Answer
# Python 2, ~~200~~ 187 bytes

```
a=input()
z=len(a[0]);P=[divmod(i,z)for i in range(len(a)*z)];i=2
while 0in sum(a,[]):t,y,x=max((min((u-U)**2+(v-V)**2for V,U in P if a[V][U]),-v,-u)for v,u in P);a[-y][-x]=i;i+=1
print a

```

Try it online!

-13 bytes thx to a tip from Not that Charles by removing unneeded check for cells being 0.
> 3 votes

# Answer
# , ~~74~~ ~~70~~ 60 bytes

```
(+(1+>./@,)*i.@$(=]i.>./)*<./@(#|@-/])&,j./&i./@$)^:(1#.0=,)

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), 39 bytes

Thanks Cows quack for saving one byte, and ngn for saving another

```
1⌈2-≢∘⍸-⍴⍴∘⍋⍸∘~{⍵∪⍺[⊃⍒⌊/+.×⍨¨⍺∘.-⍵]}⍣≡⍸

```

Try it online!
> 3 votes

# Answer
# Jelly, 43 bytes

```
,¬J;Ð€"T€Ẏ©Ʋ€ạ²Sɗþ/Ṃ€MḢị®⁸⁸ẎṀ‘¤ṛ¦€Ḣ}¦µẎċ0Ɗ¡

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 44 bytes

```
{×⍵:⍵⋄≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣≡

```

Try it online!

Alternate solution at 44 bytes

```
{≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣(~0∊⊣)

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 121 bytes

```
Nest[p=Position;ReplacePart[#,#&@@Pick[a=#~p~0,m=Min/@DistanceMatrix[a,N@p[#,x_/;x>0]],Max@m]->Max@#+1]&,#,Total[1-#,2]]&

```

Try it online!
> 1 votes

# Answer
# Jelly, ~~35~~ ~~33~~ ~~30~~ 29 bytes

```
ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL

```

Try it online!

Replaced the `×ı+` with `æị` (complex combine), a new dyad based on `j.` from J, saving a byte.

Here is a more efficient version for TIO. Try it online!

## Explanation

```
ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL  Input: matrix M
Z                              Transpose
 J                             Enumerate indices - Get [1 .. # columns]
     J                         Enumerate indices - Get [1 .. # rows]
  æịþ                          Outer product using complex combine
                                 (multiply RHS by 1j and add to LHS)
      F                        Flatten
           F                   Flatten input
          ¥                    Dyadic chain
         x                       Times - Repeat each of LHS by each of RHS
       ạþ                        Outer product using absolute difference
            «/                 Reduce by minimum
              M                Indices of maximal values
               Ḣ               Head
                Ṭ              Untruth - Return a Boolean array with 1's at the indices
                 ×             Times
                     Ɗ         Monadic chain
                  F              Flatten input
                   Ṁ             Maximum
                    ‘            Increment
                      o@       Logical OR
                        F      Flatten input
                         ṁ     Mold - Reshape to match the input
                          µÐL  Repeat until result converges

```
> 1 votes

# Answer
## Clojure, 247 bytes

```
#(let[R(range(count %))C(range(count(% 0)))](loop[M % s 2](if-let[c(ffirst(sort-by last(for[x R y C :when(=((M x)y)0)][[x y](-(nth(sort(for[i R j C :when(>((M i)j)0)](+(*(- i x)(- i x))(*(- j y)(- j y)))))0))])))](recur(assoc-in M c s)(inc s))M)))

```

Input is a vec-of-vecs `M`, which is modified in a `loop` by `assoc-in`. When no free spot is found (`if-let`) then the result is returned.
> 1 votes

# Answer
# K (ngn/k), ~~81~~ ~~75~~ ~~73~~ ~~72~~ 70 bytes

```
{(~&/,/){a[*>A*&/+/''b*b:i[&~A:~a]-/:\:i:+!n:(#x;#*x)]:#?a:,/x;n#a}/x}

```

Try it online!
> 0 votes

---
Tags: code-golf, matrix
---


title: Map the cheaters!

text:
# Question
Title: Map the cheaters!
After all assignments are submitted, a dictionary is created that maps student number to the hash of their file.

This dictionary, or hashmap, or mapping (whatever your language calls it) will look as follows:

`{100: "aabb", 104: "43a", 52: "00ab", 430: "aabb", 332: "43a"}`

The key is the student number, and the value is the hash.

Our task is to pick out the cheaters! The cheaters are the ones which have identical hashes.

Given the input `{100: "aabb", 104: "43a", 52: "00ab", 430: "aabb", 332: "43a"}`, the function should return (or print) the following text:

```
100 has identical files to 430

104 has identical files to 332

```

Notice how the files where the hashes are unique are not mentioned.

**Also, the order is important here**:

`{100: "aabb", 202: "aabb", 303: "ab", 404: "aabb"}` should return (print) the following text:

`100 has identical files to 202,404`

It is **incorrect** to print any of the following:

`202 has identical files to 100,404`

`100 has identical files to 404, 202`

You should print it in terms of how it appears in the dictionary. In some languages, going through a dictionary is random, so in this special case, you are allowed to change the method of input such that you can go through it in an orderly fashion.

**More Examples:**

```
{} # prints nothing

{100: "ab", 303: "cd"} # prints nothing again

{100: "ab", 303: "cd", 404: "ab"}

100 has identical files to 404

{303: "abc", 304: "dd", 305: "abc", 405: "dd", 606: "abc"}

303 has identical files to 305,606

304 has identical files to 405

```

Shortest code wins!

# Answer
> 2 votes
# JavaScript (Babel Node), 113 bytes

Takes input as an array of arrays in `[key, value]` format. Go go gadget double flatMap!

```
o=>o.flatMap(([x,h],i)=>(a=o.flatMap(([y,H],j)=>j>i&H==h?(o[j]=[,j],[y]):[]))+a?x+' has identical files to '+a:a)

```

Try it online!

---

# JavaScript (Babel Node), 114 bytes

Takes input as a native JS object.

```
o=>Object.keys(o).flatMap((x,i,a)=>(a=a.filter(y=>i--<0&o[y]==o[x]&&(o[y]=y)))+a?x+' has identical files to '+a:a)

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~127~~ 126 bytes

```
def f(x):
 for l in{`[K for K,V in x if v==V]`[1:-1]for k,v in x}:
	if','in l:print l.replace(',',' has identical files to',1)

```

Try it online!

Takes a list of ordered pairs `(<studentNumber>,<hash>)` as input.

# Answer
> 1 votes
# , ~~145~~ ~~132~~ ~~129~~ ~~126~~ 124 bytes

```
function(m,`!`=names)for(e in !(t=table(m))[t>1])cat(el(n<-!m[m==e]),'has identical files to',paste(n[-1],collapse=','),'
')

```

Try it online!

It takes a named vector as input (names are the keys)

* -2 bytes thanks to Giuseppe

---

If `", "` separator (with a space after the comma) is allowed in case of multiple duplicates, we can use this code and save 10 bytes :

# , 114 bytes

```
function(m,`!`=names)for(e in !(t=table(m))[t>1])cat(el(n<-!m[m==e]),'has identical files to',toString(n[-1]),'
')

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 71 bytes

```
+m`((:.+)$(¶|.)+?)^(.+)\2$
,$4$1
:.*

G`,
%1`,
 has identical files to

```

Try it online! Takes input on separate lines but link includes test suite that splits the examples for you. Explanation:

```
+

```

Repeat this match until no more replacements can be made.

```
m`((:.+)$(¶|.)+?)^(.+)\2$
,$4$1

```

Look for pairs of matching hashes and append the key of the second match to that of the first match with a comma separator.

```
:.*

```

Delete all of the hashes.

```
G`,

```

Keep only the lines with commas.

```
%1`,
 has identical files to

```

Replace the first comma on each line with the desired text (including trailing space).

# Answer
> 0 votes
# Japt, 34 bytes

```
üÌl>1 ®mgÃ®Î+` •s ÅÁÈól fÅC ‘ `+ZÅ

```

Try it online!

Right now it's a bit inconsistent in the ordering of lines, but within a line it outputs correctly. If the lines of the output need to be in a specific order, it will take a few more bytes. Input is just an array of `[id, hash]` pairs

Explanation:

```
üÌ                                    :Group by hash
  l>1                                 :Remove the ones that are unique
      ®mgÃ                            :Get just the Ids
          ®                           :Generate a string for each hash:
           Î                          : The first Id with that hash
            +` •s ÅÁÈól fÅC ‘ `       : Plus " has identical files to " compressed
                               +ZÅ    : Plus the remaining Ids
                                      : Implicitly comma delimited

```

# Answer
> 0 votes
# 05AB1E, 34 bytes

```
Σθ}.γθ}vyg1›iy€нć“ÿ€°Ê¼‡œ€„ “?',ý,

```

Try it online or verify all test cases.

**Explanation:**

```
Σθ}                   # Sort the (implicit) input by the string
.γθ}                  # Then group it by the string
v                     # Loop `y` over each grouped inner list
 yg1›i                #  If the group contains more than 1 key-value pairs:
      y€н             #   Only leave the keys
      ć               #   Pop and push the head and rest of the list separately
                      #   (with the head being at the top of the stack now)
       “ÿ€°Ê¼‡œ€„ “   #   Compressed string "ÿ has identical files to "
                      #   where the "ÿ" is automatically replaced with the top of the stack
                   ?  #   Print it (without trailing newline)
       ',ý           '#   Join the remaining numbers by a comma
          ,           #   And output it as well (with trailing newline)

```

See this 05AB1E answer of mine (section *How to use the dictionary?*) to understand why `“ÿ€°Ê¼‡œ€„ “` is `"ÿ has identical files to "`.

# Answer
> 0 votes
# Perl 6, ~~115~~ ~~110~~ 103 bytes

*-2 bytes thanks to Jo King*

```
{unique map {.[0]~" has identical files to "~join ',',.skip},grep *>1,.map:{.grep(*{*}eq$^p{*})>>.key}}

```

Try it online!

Takes a list of Pairs since hashes are unordered. A list of two-element lists would save a few bytes but seems unidiomatic. Returns a list of lines.

**~~95~~ 88 bytes** if the order of lines in the result doesn't matter:

```
*.classify(*{*}){*}>>.key.grep(*>1).map:{.[0]~" has identical files to "~join ',',.skip}

```

Try it online!

# Answer
> 0 votes
# Ruby, ~~98~~ 96 bytes

```
->h{h.group_by{|k,v|v}.map{|k,v|x,*y=v.to_h.keys;p"#{x} has identical files to #{y*?,}"if y[0]}}

```

Try it online!

Takes input as Ruby Hash, returns by printing.

# Answer
> 0 votes
# Jelly, 39 bytes

```
Ṫ€ĠḊƇṢịẎµḢ;“]⁶ḅhṬyU⁹æṇL[Oþ⁹cƘƓ»,ṾK)j⁾¶¶

```

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 130 bytes

```
a=>a.GroupBy(x=>x.Value,x=>x.Key).Where(x=>x.Count()>1).Select(x=>x.First()+" has identical files to "+String.Join(",",x.Skip(1)))

```

Try it online!

The strange thing about this question is that the examples are given in a JSON format as key/value pairs which usually implies that they are unordered... In this case however, order is important. As such, I am using a list of tuples for input and a list of strings as output.

```
// a is a list of tuples
// (student #, hash)
a=>a
  // group by hash
  // grouped items are the student #'s
  .GroupBy(x=>x.Value,x=>x.Key)
  // remove single student groups
  .Where(x=>x.Count()>1)
  // format the output strings
  .Select(x=>x.First()+
    " has identical files to "+
    String.Join(",",x.Skip(1)))

```

# Answer
> 0 votes
# Perl 5, 100 +1(-n) bytes

```
for$x(/[a-z]+/g){($t,@a)=${h{$x}}++?():/\d+(?= $x)/g;@a&&say"$t has identical files to ",join",",@a}

```

Try it online!

---
Tags: code-golf, string, array
---


title: Optimizing swiping across a 1D keyboard

text:
# Question
Title: Optimizing swiping across a 1D keyboard
This is a with a custom scoring system, where **the lowest score wins.**

## Introduction

Many smartphones allow to enter text by swiping your finger across the 2D virtual keyboard. This technology is usually combined with a prediction algorithm that outputs a list of guessed words, sorted from most likely to least likely.

In this challenge:

* We are going to swipe across a **one-dimensional keyboard** restricted to a subset of the 26 letters.
* There will be **no prediction algorithm**: we want each word to be uniquely identified by its 'swipe sequence'.
* **We want the keyboard to be optimized** in such a way that the total number of moves for a given list of words is minimized.

## Swiping in one dimension

Below is a lexicographically sorted 1D keyboard with all letters:

`A``B``C``D``E``F``G``H``I``J``K``L``M``N``O``P``Q``R``S``T``U``V``W``X``Y``Z`

<sup>*NB: This may be displayed on several rows if you're browsing from mobile. Please think of it as a single row.*</sup>

To enter the word '**GOLF**' on such a keyboard, we will:

* start at `G`
* swipe to the right to `O`
* swipe to the left to `F`

Because `L` is located between `O` and `F`, we just go on swiping without stopping there.

So the swipe sequence of '**GOLF**' on this keyboard is `G``O``F`.

More generally:

* The first and last letters are always included.
* Other letters are included if and only if a direction change is required just after them.
* Repeated letters must be treated the same way as single letters. For instance, on the above keyboard:

+ '**LOOP**' would be encoded as `L``P` (with no stop on `O`)
    + '**GOOFY**' would be encoded as `G``O``F``Y` (the `O` is included because there's a direction change there -- not because it's doubled)

## Keyboard optimization

Let's consider the following list of words: \['**PROGRAMMING**', '**PUZZLES**', '**AND**', '**CODE**', '**GOLF**'\].

We need 16 distinct letters to type these words, so we just need a 16-letter keyboard. The following one is -- again -- lexicographically sorted:

`A``C``D``E``F``G``I``L``M``N``O``P``R``S``U``Z`

With this keyboard, the words will be encoded this way:

* **PROGRAMMING**: `P``R``G``R``A``M``I``N``G` (9 moves)
* **PUZZLES**: `P``Z``E``S` (4 moves)
* **AND**: `A``N``D` (3 moves)
* **CODE**: `C``O``D``E` (4 moves)
* **GOLF**: `G``O``F` (3 moves)

That's a total of **23 moves** for all words.

But we can do much better with this keyboard:

`C``G``O``D``S``E``L``Z``N``U``I``F``R``P``A``M`

Which gives:

* **PROGRAMMING**: `P``G``M``G` (4 moves)
* **PUZZLES**: `P``S` (2 moves)
* **AND**: `A``D` (2 moves)
* **CODE**: `C``E` (2 moves)
* **GOLF**: `G``F` (2 moves)

for a total of only **12 moves**.

## Keyboard scoring

For a given list of \\$n\\$ words, the score of a keyboard is given by:

$$\sum\_{k=1}^{n}{m\_k}^2$$

where \\$m\_k\\$ is the number of moves for the \\$k\\$-th word.

For instance, the two keyboards described in the previous paragraph would be scored \\$9^2+4^2+3^2+4^2+3^2=131\\$ and \\$4^2+2^2+2^2+2^2+2^2=32\\$ respectively.

The lower, the better.

## The challenge

* Given a list of words, your code must output a **valid** keyboard for this list. A keyboard is considered valid if each word generates a unique swipe sequence.
* You'll be given 11 independent lists of words. Your score will be equal to:

$$S + L$$ where \\$S\\$ is the sum of the scores of your keyboards for all lists and \\$L\\$ is the length of your code in bytes.

You can use this script to check your score. The `score()` function expects your code length as first parameter and an array of 11 keyboard strings as second parameter (the case doesn't matter).
* The submission with the lowest score wins. In case of a tie, the submission that was submitted first wins.

## Additional rules

* Your code must be **deterministic** (i.e. it must always return the same output for a given input).
* You must either A) provide a test link (e.g. on TIO) that does not time out, or B) include the generated keyboards within the body of your answer.
* You may take the words in either full uppercase or full lowercase. Mixed cases are forbidden.
* The input is guaranteed to have at least one solution.
* All words are made of at least 2 distinct letters.
* Your code must work for any valid input. It will be tested with an undisclosed list of words to make sure that it's not relying on hard-coded results.
* I reserve the right to increase the size of the test suite at any time to make sure that the submissions are not optimized for the initial test cases.

## Word lists

```
1) Sanity check #1 (only 4 valid solutions: HES, SEH, ESH or HSE)
SEE, SHE

2) Sanity check #2 (16 valid solutions, of which 4 are optimal: COLD, DOLC, DLOC or CLOD)
COLD, CLOD

3) Sanity check #3
ACCENTS, ACCESS

4) Warm-up
RATIO, NATION, NITRO, RIOT, IOTA, AIR, ART, RAT, TRIO, TRAIN

5) Pangram
THE, QUICK, BROWN, FOX, JUMPS, OVER, LAZY, DOG

6) Common prepositions
TO, OF, IN, FOR, ON, WITH, AT, BY, FROM, UP, ABOUT, INTO, OVER, AFTER

7) Common verbs
BE, HAVE, DO, SAY, GET, MAKE, GO, KNOW, TAKE, SEE, COME, THINK, LOOK, WANT, GIVE, USE, FIND, TELL, ASK, WORK, SEEM, FEEL, TRY, LEAVE, CALL

8) Common adjectives
GOOD, NEW, FIRST, LAST, LONG, GREAT, LITTLE, OWN, OTHER, OLD, RIGHT, BIG, HIGH, DIFFERENT, SMALL, LARGE, NEXT, EARLY, YOUNG, IMPORTANT, FEW, PUBLIC, BAD, SAME, ABLE

9) Common nouns
TIME, PERSON, YEAR, WAY, DAY, THING, MAN, WORLD, LIFE, HAND, PART, CHILD, EYE, WOMAN, PLACE, WORK, WEEK, CASE, POINT, GOVERNMENT, COMPANY, NUMBER, GROUP, PROBLEM, FACT

10) POTUS
ADAMS, ARTHUR, BUCHANAN, BUREN, BUSH, CARTER, CLEVELAND, CLINTON, COOLIDGE, EISENHOWER, FILLMORE, FORD, GARFIELD, GRANT, HARDING, HARRISON, HAYES, HOOVER, JACKSON, JEFFERSON, JOHNSON, KENNEDY, LINCOLN, MADISON, MCKINLEY, MONROE, NIXON, OBAMA, PIERCE, POLK, REAGAN, ROOSEVELT, TAFT, TAYLOR, TRUMAN, TRUMP, TYLER, WASHINGTON, WILSON

11) Transition metals
SCANDIUM, TITANIUM, VANADIUM, CHROMIUM, MANGANESE, IRON, COBALT, NICKEL, COPPER, ZINC, YTTRIUM, ZIRCONIUM, PLATINUM, GOLD, MERCURY, RUTHERFORDIUM, DUBNIUM, SEABORGIUM, BOHRIUM, HASSIUM, MEITNERIUM, UNUNBIUM, NIOBIUM, IRIDIUM, MOLYBDENUM, TECHNETIUM, RUTHENIUM, RHODIUM, PALLADIUM, SILVER, CADMIUM, HAFNIUM, TANTALUM, TUNGSTEN, RHENIUM, OSMIUM

```

# Answer
# Python 3 + Google OR-Tools, 1076 + 1971 = 3047

This always finds optimal solutions (but spends a lot of code to do so). It runs tests 1–9 in a few seconds, test 10 in six minutes, and test 11 in one minute.

### Code

```
from ortools.sat.python.cp_model import*
from itertools import*
C=combinations
R=range
L=len
T=lambda w:[*zip(w,w[1:],w[2:])]
W=[(*(g[0]for g in groupby(w)),)for w in input().split()]
K={*sum(W,())}
m=CpModel()
V=m.NewBoolVar
B={c:V(f"B{c}")for c in C(K,2)}
for a,b in[*B]:B[b,a]=B[a,b].Not()
for a,b,c in permutations(K,3):m.AddBoolOr([B[a,b],B[b,c],B[c,a]])
M={t:V(f"M{t}")for t in{*sum(map(T,W),[])}}
for a,b,c in M:m.AddBoolXOr([B[a,b],B[b,c],M[a,b,c].Not()])
N={(w,n):V(f"N{w,n}")for w in W for n in R(1,L(w))}
for w in W:
 for n in R(1,L(w)-1):s=sum(M[t]for t in T(w));m.Add(s>=n).OnlyEnforceIf(N[w,n]);m.Add(s<n).OnlyEnforceIf(N[w,n].Not())
for a,b in C(W,2):
 if(a[0],a[-1])==(b[0],b[-1]):m.AddForbiddenAssignments([M[t]for t in T(a)+T(b)],[[x in X for x in R(L(a)-2)]+[y in Y for y in R(L(b)-2)]for n in R(L(a))for X in C(R(L(a)-2),n)for Y in C(R(L(b)-2),n)if[a[x+1]for x in X]==[b[y+1]for y in Y]])
m.Minimize(sum((2*n+3)*N[w,n]for w,n in N))
s=CpSolver()
s.Solve(m)
o={k:0for k in K}
for c in C(K,2):o[c[s.Value(B[c])]]+=1
print(*sorted(K,key=lambda k:o[k]),sep="")

```

### Result

1. SEH, 13
2. DOLC, 20
3. TNSECA, 13
4. RATION, 80
5. TYKCIDBRFHJUEVOXWNGZALQMPS, 32
6. REWINTHUVOFABMPY, 66
7. FYCWORTMHAGINDKVESULB, 125
8. TSHRDABXLYOWUPMIENGCF, 213
9. PVKEFDLBMUSWOIHACNYTRG, 212
10. XHGTPMCKSUABYORDLJEIWNFV, 596
11. PYLFNAVEKBOCHTRGDSIZUM, 601

Check score
> 6 votes

---
Tags: code-challenge, optimization
---


# Question
Title: What will be on the top of this decorative calendar?
Someone gave my wife a decorative calendar consisting of four cubes. Here it is showing today's date (as of the posting of this challenge) on the front:

When I first saw it, I looked at it from the wrong angle (from directly above) and couldn't figure out why it gave this information:

```
[["February", "January"], [3], [7], ["Monday", "Tuesday"]]

```

Your job is to replicate my error for any date in 2019.

## Challenge

Write a program or function that takes any date from 2019, and outputs what appears on the ***top*** of all the cubes when that date is displayed facing out from the front of the calendar.

Here are all six sides for all the cubes. To display a `6` you just turn the `9` upside down. The `0` is vertically symmetrical, so `0` upside down is still `0`. There might be more than one correct answer for some dates (e.g. any 11th of any month will have more than one way to use the cubes, and the `0` thing) so you can output any correct answer.

## Rules

1. Standard loopholes forbidden.
2. Input/output format is flexible.
3. The output does have to be in order by cube, but not within a cube. The order must be month cube first, then the two number cubes, followed by the weekday cube. But when a cube has two elements on top, those two elements can be in either order.
4. You can replace `January` to `December` 0-11 or 1-12 if you like.
5. You can replace the days of the week with 0-6 or 1-7 if you like, and you can start the week on either `Sunday` or `Monday` (but you can't start the week on any other day - this is PPGC, not some sort of crazy-town.)
6. This is . Fewest bytes for each language wins.
7. Explanations encouraged.

## Test cases

```
(Tue) 2019-01-29   [[ "July", "August" ], [3], [7], [ "Thursday", "Wednesday" ]]
                   [[ "August", "July" ], [3], [7], [ "Wednesday", "Thursday" ]]

                   etc. since the order within each cube doesn't matter.

(Thu) 2019-07-11   [[ "May", "June" ], [3], [8], [ "Saturday", "Friday" ]]
                   [[ "May", "June" ], [8], [3], [ "Saturday", "Friday" ]]

                   since the two 1 cubes could be either way.

(Sun) 2019-10-27   [[ "January", "February" ], [3], [6], [ "Friday", "Saturday" ]]

(Wed) 2019-05-01   [[ "March", "April" ], [8], [3], [ "Monday", "Tuesday" ]]
                   [[ "March", "April" ], [6], [3], [ "Monday", "Tuesday" ]]
                   [[ "March", "April" ], [9], [3], [ "Monday", "Tuesday" ]]

                   since the 0 cube could have either the 8 side or the 6 side facing up, and the 6 could also be considered a 9.

(Sat) 2019-08-24   [[ "February", "January" ], [8], [5], [ "Sunday" ]]

```

# Answer
> 5 votes
# C (glibc), <sub>~~327~~ ~~319~~</sub> 286 bytes

```
#define C strftime(s
#define U(B,E)S[6]=E-1,C+B,99,"%A"+2*!E,S)
S[9],s[99];f(M,D){S[4]=112233107696>>3*M&7;C,9,"%B",S);S[4]^=1;
C+3,9,"%B",S);M=161102>>(D+M*23/9-1-2*(M>2))%7*3&7;U(6,M);U(9,(M^1));
printf("%s/%s %d%d %s/%s\n",
s,s+3,D>29?4:D%10<6?8:3,D>29?8:1070160091>>D%10*3&7,s+6,s+9);}

```

(Some line breaks added for clarity)

`f` takes a month (1–12) and a day (1–31). Prints to stdout. Try it online!

Test cases:

```
2019-01-29: July/August 37 Thursday/Wednesday
2019-07-11: May/June 83 Saturday/Friday
2019-10-27: January/February 36 Friday/Saturday
2019-05-01: March/April 83 Monday/Tuesday
2019-08-24: February/January 85 /Sunday

```

### Ungolfed

```
#include <stdio.h>
#include <time.h>
void f(int M, int D) {
    int month_cube[] = {6,3,0,5,2,7,4,1,4,0,5,1};
    int day_cube[] = {3,3,3,4,5,2,2,6,7,7};
    int week_cube[] = {6,1,5,2,7,4,0}; /* 1=Sun, 7=Sat, 0=none */
    int D1 = D/10, D2 = D%10;
    char s[4][99] = {{0}};
    struct tm t;

    t.tm_mon = month_cube[M-1];
    strftime(s[0], 99, "%B", &t);
    t.tm_mon = month_cube[M-1]^1;
    strftime(s[1], 99, "%B", &t);

    if (D1 >= 3) { /* D = 30, 31 */
        D1 = 4, D2 = 8;
    } else {
        if (D2 <= 5) {
            D1 = 8; /* 012[69]78: 012 -> 8 */
        } else {
            D1 = 3; /* 012345: 012 -> 3 */
        }
        D2 = day_cube[D2];
    }

    int W = (D + M*23/9 - 1 - 2*(M>2)) % 7; /* day of week */
    if (week_cube[W]) {
        t.tm_wday = week_cube[W] - 1;
        strftime(s[2], 99, "%A", &t);
    }
    if (week_cube[W]^1) {
        t.tm_wday = (week_cube[W]^1) - 1;
        strftime(s[3], 99, "%A", &t);
    }

    printf("%s/%s %d%d %s/%s\n", s[0], s[1], D1, D2, s[2], s[3]);
}

```

### Digit cubes

These are the possibilities for the digits:

```
Cube 1:
0 1 2 3 4 5
3 3 3 4 5 2
5

Cube 2:
0 1 2        6 7 8 9
8 8 8        2 6 7 7
6                2
9

```

The following mapping seems like the best choice for golfing:

```
   01 02 03 04 05 06 07 08 09
   83 83 84 85 82 32 36 37 37

10 11 12 13 14 15 16 17 18 19
83 83 83 84 85 82 32 36 37 37

20 21 22 23 24 25 26 27 28 29
83 83 83 84 85 82 32 36 37 37

30 31
48 48

```

### Cheats

`strftime` is meant to be called with a `struct tm` as input. Instead, I declare `int S[9]` and use `S[4]` as `tm_mon` and `S[6]` as `tm_wday`. This works if the C library uses the same list of struct members as the ISO standard.

`s[99]` is used to store various strings from `strftime`, but making it an `int` array saves a few bytes in indexing.

# Answer
> 3 votes
# JavaScript (ES6), 142 bytes

Takes input as `(year, month, day0, day1)` where \\$month\\$ is 1-indexed, \\$day0\\$ is the first digit of the date and \\$day1\\$ is the second digit.

Returns `(month0, month1, day0, day1, weekDay0, weekDay1)` where week days are 0-indexed with \\$0\\$ for Sunday. If the second week day is blank, it is set to \\$-1\\$.

```
(y,m,t,u)=>[M=-~((s='45226276204264')[m--+6]||4*m%2),M+1,t<3?u<6?8:3:s[t-3],u<3?3:s[u-3],D=s[(new Date(y,m,t*10+u).getDay()+6)%7+7],-~D%7||-1]

```

Try it online!

---
Tags: code-golf
---


title: Tips for golfing in Tcl

text:
# Question
Title: Tips for golfing in Tcl
What general tips do you have for golfing in Tcl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Tcl (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
> 7 votes
Use `lmap` instead `foreach`. This requires Tcl 8.6.

The syntax is the same, but `lmap` returns a list with the result of each loop.

# Answer
> 4 votes
Subcommands and options can (usually) be abbreviated. This can save quite a bit, but you *must* test as not everything can be shortened this way (`regsub`'s options can't, for example).

You can then use this with the magic of `namespace` to do some truly evil things. Consider this:

```
namespace exp *;namespace en cr -c ?

```

After that, `?` is now a magical command that lets you abbreviate any global Tcl command, and all without the nasty uncertainty of messing around with `unknown`.

# Answer
> 4 votes
On my answer https://codegolf.stackexchange.com/a/107557/29325 I can demonstrate:

1. Usually `set j 0;while \$j<$n;{...;incr j}` is shorter than the equivalent `for {set j 0} {$j<$n} {incr j} {...}`
2. When the looping variable begins at 1, we can do the increment as part of the `while` test condition, avoiding to write before `set i 1` unnecessarily: `while {[incr i]<=$n} {...}` instead of `set i 1;while \$i<=$n;{...;incr i}`

**ATTENTION**: One can only do 2. in the case of an outer loop! I could not apply it to my `j` variable as it needs to be reset to 1 in the outside of its own inner loop! And `incr j` would acquire the value that was set on the last step of the inner loop, instead of grabbing an **undefined** variable `j` to assume `0` and increment it to `1`!

# Answer
> 4 votes
Sometimes it is worth to use `time {script} n` where `n` is the number of iterations instead of a normal `while` or `for` loop. Although `time`'s purpose is not looping, the achieved effect is the same.

I made changes recently to my own answers following this direction.

**UPDATE:** I've just discovered an easy to fall pitfall: You can not replace a `for` or a `while` by a `time` block, if it contains a `break` or a `continue`.

# Answer
> 3 votes
Use the interactive shell. This allows you to abbreviate the command names as long as only 1 command starts with the remaining letters.

Example:

* `gets` -\> `ge`
* `lassign` -\> `las`
* `expr` -\> `exp`
* `puts` -\> `pu`

And interactive solutions are free :P

**Background**:

When `tclsh` runs with a terminal as input device, it sets the variable `tcl_interactive` to `1`. This causes `unknown` (default procedure that will be called if a command can not be found) to search for commands that starts with that name.

Downside: it will print the result of every line, use `;` instead of newlines.
Ohh, and it might invoke external commands like `w`, which is a good abbreviation of `while`.

# Answer
> 3 votes
# else is optional

As it is said on if manual page, `else` is implicit on `if` block constructs. So what is

`if ... {} else {}`

can become

`if ... {} {}`

as you can see on some of my answers.

# Answer
> 2 votes
I'm using Tcl 8.0.5, but I believe the following are applicable to all recent versions.

1. Use `rename` to rename `rename`:

```
rename rename &

```

The `&` can be any identifier; `&` just reminds me of "references" in C.
2. Use the renamed `rename` to rename `set`:

```
& set =

```

Again, the `=` can be any identifier; `=` is just intuitive to me.
3. Now, rename other commands that are worth renaming, *e.g.*

```
& regsub R
& string S
& while W

```

A command is worth renaming if, given its length *n*, and occurrences *k*, *k(n-1)-(n+4) \> 0*. Solving for *k*, the formula becomes `k > (n+4)/(n-1)`. Here's a reference table that makes it easy:

```
length of       minimum         example(s)
command         occurrences
------------------------------------------------
2               6               if (consider renaming to "?")
3               4               for, set (consider renaming to "=")
4               3               eval, expr, incr (consider renaming to "+"), info, join, proc, puts, scan
5               3               break, catch, lsort, split, subst, trace, unset, while
6               3               format, lindex, lrange, regexp, regsub, rename, return, string, switch
7               2               foreach, lappend, linsert, llength, lsearch, unknown
.               2               lreplace
.               2               continue
.               2

```
4. Next, compact frequently used subcommands like

```
= I index
= L length

```

so you can do things like

```
S $I $x 7
S $L $x

```
5. Some obvious miscellanea:

1. `lappend` can set the first element of a list if it doesn't yet exist (no need to initialize).
    2. You can set arrays without using `array`, *e.g.* `set doesNotExist(7) 43`.
    3. You can use strings (`"a b c"`) instead of `[list a b c]`.
    4. You can interpolate in strings like so: `foo${a}bar`.
    5. You can use `two\ words` rather than `"two words"`. (Remember in general that for contiguous strings without spaces, double quotes can be omitted!)
    6. You can almost always rewrite `for`s as `while`s to save a character or two, since a `while` can simultaneously check and increment while a `for` uses separate blocks.
6. For larger programs, here's a trick I thought of but haven't yet applied:

```
proc unknown {c args} {eval [info commands $c*] $args}

```

This emulates interactive command abbreviations! It costs 54 characters, but now you can use `j` for `join`, `sp` for `split`, `st` for `string`, `w` for `while`, and so on.

# Answer
> 1 votes
May be it should be integrated on another answer, but here it goes:

When a `proc` has only one parameter it could be written as

```
proc p a {DO THINGS}

```

instead of

```
proc p {a} {DO THINGS}

```

---

The same applies to a two parameters `proc` using a backslash; it can be written as

```
proc p a\ b {DO THINGS}

```

instead of

```
proc p {a b} {DO THINGS}

```

---

For an higher number of parameters the `{}` render shorter code.

# Answer
> 1 votes
Sometimes it is worth to replace the two `set` statements to concatenate strings by only one `lappend` statement. On a construction like, one can substitute

```
set s ""

loop {
    # ...
    set s $s\X
}

```

by

```
loop {
    # ...
    append s X
}

```

The `append` command has an `incr` like behaviour, which initializes a not yet defined variable.

Take care to not mistake `append` by `lappend`

# Answer
> 1 votes
If you are handling a list with an operation that syntactically is interleaving between each element, sometimes you can `join` elements to do a specific operation, instead of traversing it.

On https://codegolf.stackexchange.com/a/127042/29325 there is an example:

```
puts \n[expr [join [split [read stdin]] +]]

```

It `read stdin` gives `23 214 52` then split will give the list `{23 214 52}`. **After, `[join {23 214 52} +]` will return the string `23+214+52`.** Finally `expr 23+214+52` does the job of summing

# Answer
> 1 votes
If you have large codes, it's possible to avoid multiple usages of `expr` using `namespace pat tcl::mathop` at the beginning. It provides prefix-syntax operation as a regular Tcl fonction. For example:

```
namespace pat tcl::mathop
set sum [+ 1 2 3]
set prod [* {*}{1 2 3 4}]
puts $sum\ $prod

```

See official mathop doc page

# Answer
> 0 votes
When you have several variables that are been `set` on subsequent lines you can use one `lassign` instead of several `set` instructions to achieve the same effect.

One example is my own answer https://codegolf.stackexchange.com/a/105789/29325

To decide, one just needs to weight the number of variables (assuming 1 letter variables, as it is expected when golfing):

* \<5, `set` is golfier
* =5, `set` and `lassign` generate the same byte count
* \>5, `lassign` is golfier

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


title: Pumping quine radix

text:
# Question
Title: Pumping quine radix
Inspired (you don't need to know them for this challenge) by the Pumping Lemma for various languages, I propose the following challenge:

* choose some basis \\$B \geq 2\\$ and an integer \\$n \geq 0\\$
* write a program/function \\$P\\$
* partition* \\$P\\$ into some strings \\$s\_i \neq \epsilon\\$, st. \\$P = s\_n | \cdots | s\_i | \cdots | s\_0\\$

So far easy enough, here comes the tricky part: The program \\$P\\$ must for any given string with \\$e\_i \in \mathbb{N}^+\\$

$$(s\_n)^{e\_n} | \cdots | (s\_i)^{e\_i} | \cdots | (s\_0)^{e\_0}$$

output \\$\sum\_{i=0}^n e\_i \cdot B^i\\$ and something distinct from any positive number (eg. erroring, \\$0\\$, \\$-1\\$ etc.) for any other string.

* You must ensure that for a pumped string as described above the \\$e\_i\\$s are unique.

### Informal Explanation

Write a program and split it into a fixed number of chunks and pick a power-series (eg. \\$1,2,4,8,\dotsc\\$). The program needs to take a string as input and output a number in the following way:

1. First decide if the input string is made out of the same chunks (in order) as the program, though each chunk can be repeated any number of times. If this is not the case, return \\$0\\$, a negative number, error out etc.
2. Count the number of times each chunk is repeated and output (using the powerseries of \\$2\\$ as example): `number_of_last_chunk * 1 + number_of_second_last_chunk * 2 + number_of_third_last_chunk * 4 + ...`

Thanks Laikoni for helping me with the explanation!

## Example

Suppose I have the program \\$\texttt{ABCDEF}\\$ and I choose \\$n = 2\\$ with the partitioning \\$s\_2 = \texttt{ABC}\\$, \\$s\_1 = \texttt{D}\\$ and \\$s\_0 = \texttt{EF}\\$, choosing basis \\$B = 2\\$ we would have the following example outputs (the input is given to the original program):

$$ \begin{aligned} \text{Input} &\mapsto \text{Output} \\\ \texttt{ABCDE} &\mapsto 0 \\\ \texttt{ABCDEF} &\mapsto 7 \\\ \texttt{ABCDEFEF} &\mapsto 8 \\\ \texttt{ABCABCDEF} &\mapsto 11 \\\ \texttt{ABCDDEFEFEF} &\mapsto 11 \\\ \texttt{ABCABCDDEF} &\mapsto 13 \end{aligned} $$

This submission has score \\$3\\$.

## Walk-through

The example \\$\texttt{ABCDE}\\$ maps to \\$0\\$ because the \\$\texttt{F}\\$ is missing.

---

Now let's walk through the fifth example: The input is \\$\texttt{ABCDDEFEFEF}\\$ which we can write using the strings \\$s\_2,s\_1,s\_0\\$ as follows:

$$ (\texttt{ABC})^1 | (\texttt{D})^2 | (\texttt{EF})^3 $$

So this gives us \\$1\cdot 2^2 + 2 \cdot 2^1 + 3 \cdot 2^0 = 4+4+3 = 11\\$.

# Winning criterion

The score of your program/function will be \\$n+1\\$ where larger is better, ties will be the submission date earlier is better.

In case you're able to generalize your submission to an arbitrarily large \\$n\\$, you may explain how and score it as \\$\infty\\$.

---

**Notations:** \\$\epsilon\\$ denotes the empty string, \\$x | y\\$ the string concatenation of \\$x\\$ and \\$y\\$ & \\$x^n\\$ is the string \\$x\\$ repeated \\$n\\$ times.

# Answer
# Mathematica, \\$B=2\\$, score \\$\infty\\$

```
With[{s =
    StringJoin[StringRepeat["a", #] <> "b" & /@ Reverse[Range[#]]]},
  ToString[(s;
     StringReplace[#,
       StartOfString ~~ a : "(\"" .. ~~ b : ("a" .. ~~ "b") .. ~~
          c : ("\"; " <>
              StringTake[
               ToString[Extract[#0, {1, 2}, Hold],
                InputForm], {6, -2}] <> ") & ") .. ~~ EndOfString /;
         AllTrue[Differences[
            d = Length /@ Split[Characters[b]][[;; ;; 2]]], -2 < # <
             1 &] && Length[d] > 1 :>
        2^Max[d] StringLength[a] + Total[2^# #2 & @@@ Tally[d]] +
         StringLength[c]/389][[1]]) &, InputForm]] &

```

Pure function. Takes \\$k=n-1\\$ as input and returns the string representing \\$P\_k\\$ as output (for \\$k\geq2\\$). For the purposes of illustration, take this formatted version of \\$P\_3\\$:

```
("aaabaabab";
  StringReplace[#1,
    StartOfString ~~ a : ("(\"" ..) ~~ b : (("a" .. ~~ "b") ..) ~~
       c : ("\"; " <>
           StringTake[
            ToString[Extract[#0, {1, 2}, Hold], InputForm], {6, -2}] <>
            ") & " ..) ~~ EndOfString /;
      AllTrue[Differences[
         d = Length /@
           Split[Characters[b]][[1 ;; All ;; 2]]], -2 < #1 < 1 &] &&
       Length[d] > 1 :>
     2^Max[d] StringLength[a] +
      Total[Apply[2^#1 #2 &, Tally[d], {1}]] + StringLength[c]/389][[
   1]]) &

```

This function takes a string as input and either returns a positive integer or an invalid expression (`"..."[[1]]`) as output. Here, \\$s\_4=\texttt{("}\\$, \\$s\_3=\texttt{aaab}\\$, \\$s\_2=\texttt{aab}\\$, \\$s\_1=\texttt{ab}\\$, and \\$s\_0\\$ encompasses the remainder of the function.
> 3 votes

---
Tags: code-challenge, quine, base-conversion
---


title: Hexagonal adjacency

text:
# Question
Title: Hexagonal adjacency
The above image displays a hexagonal grid of hexagons. Each cell in the grid is assigned an index, starting from the center and spiraling counterclockwise around as shown. **Note that the grid will continue indefinitely - the above picture is simply the first section. The next hexagon would be adjacent to 60 and 37.**

Your task is to determine if two given cells on this grid are adjacent.

Write a program or function that, given two cell indices, prints/returns a truthy value if the two cells are adjacent, and a falsey value if not.

If not limited by practical reasons, your code should theoretically work for any size inputs.

Truthy test cases:

```
0, 1
7, 18
8, 22
24, 45
40, 64
64, 65

```

Falsey test cases:

```
6, 57
29, 90
21, 38
38, 60
40, 63
41, 39
40, 40

```

This is so the shortest answer in bytes wins. Explanations, even for non-esoteric languages, are encouraged.

# Answer
> 7 votes
# Elixir, ~~263~~ ~~257~~ ~~264~~ ~~223~~ ~~214~~ ~~218~~ 214 bytes

```
a=fn x,y->i=&(&1*(&1-1)*3+1)
[x,y]=Enum.sort [x,y]
if x<1,do: y in 1..6,else: (y-x==1||fn->a=y-trunc i.((r=(:math.sqrt(12*x-3)+3)/6)+1)
t=trunc r
a in [0,1,rem(b=x-i.(t)+1, t)<1&&b-t*6!=0&&2]||b<2&&a==-1 end.())end

```

Try it online!

## ungolfed version

```
def get_ring(x) do
    1/6*(:math.sqrt(12*x-3)+3)
end

def inv_get_ring(x), do: x*(x-1)*3+1

def ring_base(x), do: inv_get_ring(trunc(x))

def is_corner(x) do
    ring = trunc(get_ring(x))
    inv_ring = ring_base(ring)
    stuff = (x-inv_ring+1)
    rem(stuff, ring) == 0
end

def is_last(x),do: ring_base(get_ring(x)+1)-1 == x
def is_first(x),do: ring_base(get_ring(x)) == x

def hex_adj(x, y) do
    {x, y} = {min(x,y), max(x,y)}
    cond do
        x == 0 ->y in 1..6
        y-x==1 -> true
        true ->
            adj = trunc(inv_get_ring(get_ring(x)+1))
            number = if is_corner(x)&&!is_last(x), do: 2, else: 1
            if y-adj in 0..number do
                true
            else
                is_first(x) && y == adj-1
            end
    end
end

```
* `trunc(number)` Returns the integer part of number
* `rem(a,b)` Returns the remainder of a/b
* `cond do end` This is equivalent to else if or switch case clauses in many imperative languages

## Explanation

### get\_ring(index)

Calculates the "ring" of the index.

Example: 1 for 1-6, 2 for 7-18, etc.

This only applies if the result is `floor`ed. **Trailing digits represent how far that tile is around the ring.**

### inv\_get\_ring(ring)

Calculates the inverse of `get_ring(index)`.

### ring\_base(ring)

Calculates the index of the first tile in the ring.

### is\_corner(index)

Corners are tiles that have three adajcent tiles in the outer ring. The innermost ring consists entirely of corners.

Examples: 21,24,27,30,33,36

### is\_last(index)

Is true if this index is the highest in its ring.

### is\_first(index)

Is true if this is the base-tile of the ring.

# Answer
> 5 votes
# MATL, ~~47~~ ~~45~~ ~~44~~ ~~43~~ 41 bytes

```
s:"JH3/^6:^t5)w5:&)@qY"w@Y"]vYs0hG)d|Yo1=

```

**Try it online!** Or **verify all test cases**.

As a bonus, the code generates a hexagonal spiral that traces the positions of the cell centers, which can be seen graphically at **MATL Online** by modifying the last part of the code.

### Explanation

**General idea** The code first builds a sufficiently large hexagonal spiral with unit step. The spiral is defined as a vector of complex numbers representing positions of the cell centers. Indexing into that vector with the input numbers and computing the absolute difference gives the distance between the two indicated cells. Cells are adjacent if and only if the result is 1. However, due to floating point inaccuracies, rounding is necessary before comparing with 1.

**Building the spiral** The spiral will have a number of "layers" equal to the sum of the two inputs. This is (much) larger than necessary, and ensures that the input cells will be present in the spiral.

To build the spiral, the complex number *j* 2/3 (where *j* is the imaginary unit) is first computed. Raising this to exponents 1 through 6 gives a basic set of displacements, such that following those displacements in order would trace a hexagon. This hexagon would form the innermost layer of the spiral, except that it would be "closed". Actually, we want that hexagon to "grow" at the last step and then we trace a larger hexagon, with twice as many points (aligned in groups of two), to form the next layer of the spiral; see illustration here. The next layer will have thrice as many points as the first (in groups of three); see here.

To do this, the fifth displacement from the basic set (which points in the south-east direction) is chosen as the "growing" step. Layer *k* begins with that step, followed by the first five basic steps repeated *k* times, followed by the sixth step (east direction) repeated *k*−1 times. This hopefully becomes clearer by looking at the two figures linked above.

The resulting vector, including all layers, represents the complex displacements that would trace the spiral. Cumulative sum gives the actual coordinates of the cell centers.

Lastly, the initial cell, located at 0, is attached *to the end* of this vector. This is because MATL uses modular 1-based indexing, and index 0 refers to that *last* entry of an array.

**Testing for adjacency** The two cells given by the input numbers are selected, their coordinates are subtracted, and the absolute value is rounded and compared with 1.

**Commented code**

```
s         % Implicitly input array of two numbers. Push their sum, say S
:         % Range [1 2 ... S]
"         % For each k in [1 2 ... S]
  J       %   Push 1j
  H3/     %   Push 2, then 3, then divide: gives 2/3
  ^       %   Power
  6:      %   Push [1 2 ... 6]
  ^       %   Element-wise power. This is the array of 6 basic displacements
  t5)     %   Duplicate. Get 5th entry
  w5:&)   %   Swap. Push subarray with entries 1st to 5th, then push 6th
  @qY"    %   Repeat the 6th displacement k-1 times
  w@Y"    %   Swap. Repeat 1st to 5th displacements k times
]         % End
v         % Concatenate everything into a column vector
Ys        % Cumulative sum. This gives the cell center coordinates
0h        % Append a 0
G)        % Index by the input vector
d|        % Absolute difference
Yo        % Round to nearest integer
1=        % Does it equal 1? Implicitly display

```

# Answer
> 3 votes
# 05AB1E (legacy), ~~30~~ ~~29~~ 27 bytes

```
α2‹i1q}1Ý¹+v12y*3-tîÌy+}Ÿ²å

```

Try it online!

## Explanation of code:

```
α2‹i1q}                     : if the absolute diff of the two number is 1 or 0 return 1
                          ²å: return that the second number is in
                         Ÿ  : range of {
       1Ý                   :  create [0, 1]
         ¹+                 :  add the first number to the elements
           v            }   :  map that list
            12y*3-tîÌy+     :  calculate the corresponding value where it's an adjacency
                                }

```

## Explanation of math:

I "wasted" around 5 hours making this golf. In short I started making a 2d graph of the inputs, and draw `X` where they were adjacency to each other. Then I found a pattern. I searched for it on OEIS and bingo! I found that sequence and I used the formula given on the website.

# Answer
> 1 votes
# C (gcc), ~~175~~ 173 bytes

Thanks to Peter Taylor for catching a bug.

Thanks to ceilingcat for -2 bytes. That ~ operator continues to be my main blindspot.

```
c,r,C,L;y(a){a=a<L*2?L-a:a<L*3?-L:a<5*L?a-L*4:L;}z(a){L=ceil(sqrt(a/3.+.25)-.5);C=y(a-=3*L*~-L);L?L=y((L+a)%(L*6)):0;}f(a,b){z(a);c=C,r=L;z(b);a=a-b&&(abs(c-C)|abs(r-L))<2;}

```

Try it online!

This approach is focused on finding the row and the column of the two cells and compare them; any neighbours cannot have their corresponding coordinates differ by more than 1. Moving from the center outwards, we observe that each layer has 6 more cells than the previous. This means that the highest "index" in each layer L is on the form 6 * (L * (L - 1) * (L - 2) ...), or C = 6 * (L2 \+ L) / 2, where C is the "global" cell number. Shuffling things around, we get L2 \+ L - C / 3 = 0, which gives high-school math flashbacks. From that, we get the formula ceil (sqrt (1 / 4 + C / 3) + 0.5). Plugging a global cell index into it, we receive which layer the cell is in.

Since the first cell in each layer is naturally one higher than the highest of the previous layer, we find Lstart = (6 * (L - 1)2 \+ (L - 1)) / 2, which simplifies to 3 * (L2 \- L). From that we get the layer index Lindex = C - Lstart.

Next up, we see that each layer is comprised of six sections, each of length L. Starting at north-east and going counter-clockwise, we see that for the first two sections (1 \<= Lindex \<= 2 * L), we get the column from L - Lindex. The next section L * 2 \< Lindex \<= L * 3 have all cells sharing a single column -L. The two next sections are L * 3 \< Lindex \<= L * 5 with their columns according to Lindex \- L * 4. And lastly the sixth section all have its cells on column L. We can shift the upper bounds one step along to save some bytes in the code.

So then what about the rows? To reuse code, we turn the grid so that cell 44 is straight up. Then we run the same logic as for columns but call the results "rows" this time around. Of course, instead of actually turning a grid, we just walk 1 / 6 of a lap around it.

# Answer
> 1 votes
# Python 3, 150 bytes

```
def h(a,b):
 L=[];i=1
 while len(L)<a+b:r=sum((i*[1j**(k/3)]for k in range(4,16,2)),[]);r[0]+=1;L+=r;i+=1
 return.9<abs(sum(L[min(a,b):max(a,b)]))<1.1

```

My solution basically follows the same line of thought as Luis Mendo's above. If written more readable, the code is pretty self-explanatory:

```
def h(a,b):
    L=[]
    i=1
    while len(L)<a+b:
        l=sum((i*[1j**(k/3)]for k in range(4,16,2)),[])
        l[0]+=1
        L+=l
        i+=1
return .9<abs(sum(L[min(a,b):max(a,b)]))<1.1

```
1. function `h` does the following:
2. List L will contain the (complex) positions of each number.
3. `i` is the ring number.
4. In the while-loop, a new ring is added every iteration. Instead of figuring out how many rings we need, we just continue to build the list until it is long enough to contain a+b, then it is certainly long enough to contain either of them.
5. the 'ring-list' `l` is a concatenation of 6 lists of len(i) times the step-vector, where the step-vector is 1j\**(2/3) to some power. The range does not start at 0 but at 4, which causes a rotation of the whole grid. This allows me to do:
6. `l[0]+=1` in line 6, which is the step from one ring to the next.
7. `L+=l` concatenates the complete list and the ring-list.
8. List L contains only step vectors, which still must be summed (integrated) to get a position. A neat feature here is that we can just sum the slice *from the lowest number to the highest* to get their distance! Because of roundoff errors, the result won't be exactly 1, hence the .9\<...\<1.1. Interestingly, the zero case `h(0,0)` or h(0,1) is taken care of implicitly, because the sum of an empty list is zero. If I could be sure that `a<b`, ie the arguments would come in increasing order, I could shave off another 14 bytes by replacing `L[min(a,b):max(a,b)]` with `L[a:b]`, but alas!

PS: I didn't know this was such an old challenge, it showed up on top a few days ago, and kept nagging on me since:)

# Answer
> 0 votes
# Mathematica, ~~111~~ ~~105~~ 104 bytes

```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&

```

## Explanation:

`r=Floor[(1+Sqrt[(4#-1)/3])/2]&` defines a function `r` which takes input `#` and calculates the distance (in number of cells) to cell 0. It does this by exploiting the pattern in the last cells of each distance/ring: 0=3(0^2+0), 6=3(1^2+1), 18=3(2^2+2), 36=3(3^2+3),... and inverting the formula for that pattern. Note that for cell 0, it actually takes the floor of (1/2)+*i* \*(sqrt(3)/6), which it calculates component-wise to get 0+0 * *i* = 0.

With `r` defined, `r@#` is the ring for cell `#` (inside the definition of another function). `#+3r@#-3(r@#)^2&` does not appear in the code exactly, but it takes the number of a cell and subtracts the highest number of a cell in the next inner ring, so that it gives the answer to the question "which cell of the current ring is this?" For example, cell 9 is the 3rd cell of ring 2, so `r[9]` would output 2 and `#+3r@#-3(r@#)^2&[9]` would output 3.

What we can do with the function above is use it to find the polar angle, the counter-clockwise angle from the "cell 0, cell 17, cell 58" ray to the cell in question. The last cell of every ring is always at an angle Pi/6, and we go around a ring in increments of Pi/(3\*ring\_number). So, in theory, we need to calculate something like Pi/6+(which\_cell\_of\_the\_current\_ring)\*Pi/(3\*ring\_number). However, the rotation of the picture doesn't affect anything, so we can discard the Pi/6 part (to save 6 bytes). Combining this with the previous formula and simplifying, we get `Pi(#/(3r@#)+1-r@#)&`

Unfortunately, this is undefined for cell 0 since its ring number is 0, so we need to get around this. A natural solution would be something like `t=If[#==0,0,Pi(#/(3r@#)+1-r@#)]&`. But since we don't care about the angle for cell 0 and because `r@#` is repeated, we can actually save a byte here with `t=Limit[Pi(#/(3x)+1-x),x->r@#]&`

Now that we have the ring number and the angle, we can to find the position of a cell (center) so we can test for adjacency. Finding the actual position is annoying because the rings are hexagonal, but we can simply pretend the rings are perfect circles so that we treat ring number as the distance to the center of cell 0. This won't be a problem since the approximation is pretty close. Using the polar form of a complex number, we can represent this approximate position in the complex plane with a simple function: `p = r@#*Exp[I*t@#] &;`

The distance between two complex numbers on the complex plane is given by the absolute value of their difference, and then we can round the result to take care of any errors from the approximation, and check if this is equal to 1. The function that finally does this work doesn't have a name, but is `Round@Abs[p@#-p@#2]==1&`.

---

You can **try it online** in the Wolfram Cloud sandbox by pasting code like the following and clicking Gear-\>"Evaluate cell" or hitting Shift+Enter or the numpad Enter:

```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&[24,45]

```

Or for all test cases:

```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&//MapThread[#,Transpose[{{0,1},{7,18},{8,22},{24,45},{40,64},{64,65},{6,57},{29,90},{21,38},{38,60},{40,63},{41,39},{40,40}}]]&

```

---
Tags: code-golf, decision-problem, hexagonal-grid
---


title: Minimal code CPU stress-tester…

text:
# Question
Title: Minimal code CPU stress-tester…
## Introduction

There are lots of utilities out there capable of creating a high CPU load to stress-test your processor(s). On Microsoft Windows, you can even use the on-board `calculator.exe`, enter a large number like `999999999`, and press `n!` several times to make your CPU(s) work overtime.

But what’s in a solution if you didn’t create it yourself?

## The mission

Your mission – if you choose to accept it – is to create the smallest CPU stress-test tool on the planet.

### Must…

1. **must** produce 100% CPU load until aborted
2. **must** take a numeric input, representing the number seconds the stress-test should run
3. **must** allow user interaction (keypress, closing terminal window, or something like that) which should enable a user to abort the stress-test and/or quit the program
4. **must** target Microsoft Windows, Mac OSx, and/or Linux.
(Even a hamster could stress a Comodore64… therefore, you ***must*** target a current operating system.)

### Must not…

1. **must not** use 3rd-party programs or tools which replace expected functionality.
(Proposing shortcuts in the likes of `system('cpuStressThing.exe')` disqualifies your proposal.)

### May…

1. **may** use any approach/algorithm/functionality to produce expected 100% CPU load
2. **may** use any programming or scripting language
(as long as it allows practical verification of its functionality by running it)

## Winning Condition

Present the smallest sourcecode possible. The winner is the one presenting the most minimal (in size) sourcecode that complies to the above “must” and “must not” conditions. Now, make that baby burn…

---

***EDIT***

Since the question came up in the comment area… you only need to target 1 CPU core. I'm definitely not expecting you to produce a multi-core solution. After all, this should be fun – not work.

# Answer
> 28 votes
# Bash and standard utilities, 36 31 22 29 28 26 bytes

```
yes :|sh&sleep $1;kill $!

```

# Answer
> 20 votes
# Bash/iputils (Linux), 14 bytes

```
ping6 -fw$1 ::

```

Flood-pings the IPv6 null address, until the -w deadline timer expires

*caveat - only consumes 55-60% CPU on my test VM*

Edit: - I retract my caveat. While `top` reports the `ping6` process only consumes 55-60% CPU, I see the total CPU idle percentage (2 core VM) approach zero. This presumably is because a good deal of the processing is going on in the kernel as it handles the packets.

Note - must be run as root. As @Tobia comments, this seems like a reasonable requirement for something that will hog the CPU. And the OP approved it in the comments.

# Answer
> 9 votes
# Elf32 standalone binary - 86 bytes

I bet this is the **smallest correctly formed Elf format binary** that can be made to perform this function. This will execute without any additional support on any linux based platform, or potentially even **without an operating system**.

Binary download: http://ge.tt/3m6h2cK1/v/0?c

Hex dump:

```
0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 0300 0100 0000 5480 0408 3400 0000  ........T...4...
0000020: 0000 0000 0000 0000 3400 2000 0100 0000  ........4. .....
0000030: 0000 0000 0100 0000 0000 0000 0080 0408  ................
0000040: 0080 0408 5600 0000 5600 0000 0500 0000  ....V...V.......
0000050: 0010 0000 75fe                           ....u.

```

This is done by building an asm file with a minimal Elf header of its own, and skipping the use of `ld` altogether.

Assembly:

```
BITS 32

              org     0x08048000

ehdr:                                                 ; Elf32_Ehdr
              db      0x7F, "ELF", 1, 1, 1, 0         ;   e_ident
times 8       db      0
              dw      2                               ;   e_type
              dw      3                               ;   e_machine
              dd      1                               ;   e_version
              dd      _start                          ;   e_entry
              dd      phdr - $$                       ;   e_phoff
              dd      0                               ;   e_shoff
              dd      0                               ;   e_flags
              dw      ehdrsize                        ;   e_ehsize
              dw      phdrsize                        ;   e_phentsize
              dw      1                               ;   e_phnum
              dw      0                               ;   e_shentsize
              dw      0                               ;   e_shnum
              dw      0                               ;   e_shstrndx

ehdrsize      equ     $ - ehdr

phdr:                                                 ; Elf32_Phdr
              dd      1                               ;   p_type
              dd      0                               ;   p_offset
              dd      $$                              ;   p_vaddr
              dd      $$                              ;   p_paddr
              dd      filesize                        ;   p_filesz
              dd      filesize                        ;   p_memsz
              dd      5                               ;   p_flags
              dd      0x1000                          ;   p_align

phdrsize      equ     $ - phdr

section .text
global  _start
_start:       jnz     _start

filesize      equ     $ - $$

```

Built with `nasm -f bin tiny_cpu_stresser_elf32.asm -o tiny_cpu_stresser_elf32`

# Answer
> 7 votes
# bash builtins only 20 bytes

```
ulimit -t $1;exec $0

```

# Answer
> 6 votes
## C, 52

```
t;main(s){for(scanf("%d",&s),t=time();time()-t<s;);}

```

Press Ctrl+C to exit.

# Answer
> 5 votes
## Perl, 32

```
for($i=<>,$t=time;time-$t<$i;){}

```

Now the embarrassing part: I foolishly put `$t=time` in front of `$i=<>` and was furiously trying to figure out why it exits a few seconds early.

Again, Ctrl+C to exit.

# Answer
> 5 votes
## Unix C, 47

```
main(int a,char**b){alarm(atoi(b[1]));for(;;);}

```

Pass the time on the command line. Interrupt key (Ctrl-C) aborts.

# Answer
> 4 votes
# PHP ~~43~~ 40 bytes:

I hope this is an acceptable answer:

~~set\_time\_limit($\_REQUEST\['t'\]);while(!0);~~

```
<?for(set_time_limit($_REQUEST['t']);;);

```

I could do like this: `<?for(set_time_limit($_POST['t']);;);` but it would lose flexibility and 3 bytes.

---

And i could cheat and do like this: `<?for(set_time_limit($_REQUEST[t]);;);`. It shaves off 2 bytes, but it's not a "standard" solution. Lets keep the game fair.

---

As @fireeyedboy and @primo suggested, you can also use this solution (34 bytes):

```
<?for(set_time_limit($argv[1]);;);

```

This allows it's use from the console, calling it like this:

```
php <filename> <time in seconds>

```

As i told, I'm not targeting the console solution, but they have to get the credit for this one.

Another answer could be this "monster", which is just both answers combined:

```
<?for(set_time_limit($argv[1]|$_REQUEST['t']);;);

```

---

It's impossible to get key presses in php, without being on console, which I'm not targeting!

To stop it, you MUST abort the process (stopping the page from loading might stop the code)!

As a plus, it works in Android too! If you install a php server (free on Google Play).

To make it work, simply do like this:

You create a .php webpage and append `?t=<time in seconds>` to the end of the url or submit a post (using a form or even ajax).

# Answer
> 4 votes
# Smalltalk (Smalltalk/X), 34

input: n; interrupt with CTRL-c or CMD-.

```
[[]loop]valueWithTimeout:n seconds

```

can golf better, if measured in days ;-) (just kidding):

```
[[]loop]valueWithTimeout:n days

```

or from a command line:

# Answer
> 4 votes
This is not a serious attempt at it, but...

# Bash, 12 bytes

```
:(){ :|:&};:

```

As found on Wikipedia.

**WARNING: harmful code, don't run it on your computer!**

---

Technically:
\- It produces 100% CPU load until system crashes;
\- Allows user interaction to stop it (if you manage to kill all the forks, you can actually stop it...);
\- You could give it a numeric input that represents the number of seconds it should run, but it won't use it.

# Answer
> 4 votes
## Perl - 14 bytes

```
alarm<>;{redo}

```

Sets a `SIGALRM` to be sent in `input` seconds, which terminates the script. In the meantime, it spins in a busy-wait.

Sample usage:

```
$ echo 4 | perl stress.pl
Terminating on signal SIGALRM(14)

```

---

## Perl - 12 (+1) bytes

If command line options are counted as one byte each, this could be reduced to **13 bytes** using a `-n`:

```
alarm;{redo}

```

Sample usage:

```
$ echo 4 | perl -n stress.pl
Terminating on signal SIGALRM(14)

```

# Answer
> 4 votes
# BrainFuck/Extended BrainFuck: 3

```
+[]

```

It will use 100% cpu on one core until aborted. All Brainfuck programs are valid EBF programs.

# Zozotez LISP: 7 ~~15~~ ~~19~~

When using the little driver.

```
(:'r s) ; redfine read in the read-eval-print-loop

```

As a standalone expression without a driver: 15

```
((:'L(\()(L))))     ; setq a loop function and execute it

```

Usage: `echo '((\(L)(L))(\()(L)))' | jitbf zozotez.bf`

# Answer
> 3 votes
# Python, ~~58~~ ~~55~~ 51

~~Wow... longer than the C one. There's got to be a better way.~~ Still a tad long, but at least it beats the C solution!

```
import time;t=time.time;u=t()+input()
while t()<u:1

```

# Answer
> 3 votes
## x86\_64 assembly on Linux - 146 (source), 42 (assembled code)

The NASM minified source (146 bytes):

```
xor rdi,rdi
mov rcx,[rsp+16]
mov rcx,[rcx]
l:
sub cl,'0'
jl k
imul rdi,10
movsx rdx,cl
add rdi,rdx
ror rcx,8
jmp l
k:
mov rax,37
syscall
s:
jmp s

```

Accepts a parameter on the command line specifying the number of seconds to run in the range (0, 9999999\]; can be interrupted with the usual Ctrl-C.

You can assemble it with

```
nasm -f elf64 -o stress.o stress.asm && ld -o stress stress.o

```

In theory it would be necessary to add a `global _start` followed by a `_start:` label at the beginning, but `ld` manages to fix it by itself with little fuss.

The corresponding machine code (42 bytes):

```
00000000  48 31 ff 48 8b 4c 24 10  48 8b 09 80 e9 30 7c 11  |H1.H.L$.H....0|.|
00000010  48 6b ff 0a 48 0f be d1  48 01 d7 48 c1 c9 08 eb  |Hk..H...H..H....|
00000020  ea b8 25 00 00 00 0f 05  eb fe                    |..%.......|
0000002a

```

(generated with `nasm` adding the `BITS 64` directive)

A somewhat more readable version:

```
global _start

_start:
    xor rdi,rdi
    mov rcx,[rsp+16]
    mov rcx,[rcx]
argparse:
    sub cl,'0'
    jl alarm
    imul rdi,10
    movsx rdx,cl
    add rdi,rdx
    ror rcx,8
    jmp argparse
alarm:
    mov rax,37
    syscall
loop:
    jmp loop

```

# Answer
> 3 votes
# Batch, 2 characters

`%0`

In essence, the program constantly starts itself over and over. Your results may vary, due to processor task allocation priority, but it works for me.

# Answer
> 2 votes
# Java - ~~154 148~~ 186

Weird error ate my `Thread.sleep()` part

```
public class Z{public static void main(String[]a) throws Exception{new Thread(){public void run(){for(;;);}.start();Thread.sleep(Byte.valueOf(a[0])*1000);System.exit(0);}}

```

and a more readable version:

```
public class Z {
    public static void main(String[] a) throws Exception {
        new Thread() {
            public void run() {
                for (;;)
                    ;
            }
        }.start();
        Thread.sleep(Byte.valueOf(a[0]) * 1000);
        System.exit(0);
    }
}

```

Spawns a `new Thread` with a nice endless loop (`for(;;);`) then on main thread a `thread.sleep()` and a `System.exit(0)` after timeout to exit; ctrl-c exits, too on cmdline wasnt able to shorthand that `exit()`. crashing wont work;

# Answer
> 2 votes
# Go, ~~215~~ ~~212~~ 193 bytes (full)

```
package main
import(."runtime"
f"flag"
."strconv"
."time")
func main(){f.Parse()
c:=NumCPU()*2
t,_:=Atoi(f.Arg(0))
GOMAXPROCS(c)
for;c>0;c--{go(func(){for{Now()}})()}
<-After(Duration(t)*1e9)}

```

Bonus, stresses all CPU's.

The `Now()` in the loop is there to kick in the scheduler, `Now` was the shortest function name I could find in my namespace

If I run `go fmt` the size increases to ~~286~~ ~~277~~ 254 bytes

# Answer
> 2 votes
# C# - 178 characters

```
using A=System.DateTime;class P{static void Main(string[]a){var b=A.Now.AddSeconds(int.Parse(a[0]));System.Threading.Tasks.Parallel.For(0,1<<30,(i,l)=>{if(A.Now>b)l.Stop();});}}

```

And more readable:

```
using A = System.DateTime;
{
    class P
    {
        static void Main(string[] a)
        {
            var b = A.Now.AddSeconds(int.Parse(a[0]));
            System.Threading.Tasks.Parallel.For(0, 1 << 30, (i, l) =>
            {
                if (A.Now > b)l.Stop();
            });
        }
    }
}

```

Thats 178 chars in C# and uses all cores.

The only weakness that it is always ending because of the 1\<\<30 integer limit.

# Answer
> 2 votes
# Powershell, ~~18~~ ~~54~~ 50 bytes

To produce 100% load for all CPU cores.

```
for($s=date;($s|% AddS* "$args")-ge(date)){sajb{}}

```
* The script takes a time in seconds as argument.
* `| AddS*` is the shortcut for `.AddSeconds()` method.
* `sajb` is the alias for `Start-Job` cmdlet.

# Answer
> 1 votes
C#, 118

```
using a=System.DateTime;class b{static void Main(string[]c){var d=a.Now.AddSeconds(int.Parse(c[0]));while(d>a.Now){}}}

```

Uncompressed

```
using a = System.DateTime;
class b
{
    static void Main(string[] c)
    {
        var d = a.Now.AddSeconds(int.Parse(c[0]));
        while (d > a.Now) { }
    }
}

```

This requires a number as an argument which is the number of seconds to run. It will use 100% of one core for that much time or until crtl+c. I'm pretty sure this is as small as C# will go with its verbosity.

# Answer
> 1 votes
## Linux sh and standard utilities, 14

Recent gnu coreutils includes a `timeout` utility which is helpful:

```
 timeout $1 yes

```

# Answer
> 1 votes
# Matlab - 19

`tic;while toc<5;end`

Replace `5` with desired execution time.

# Answer
> 1 votes
# Bash: 19 chars

```
function f(){ f;};f

```

# Answer
> 1 votes
# Assembly: 16 bytes

```
_start:jg _start

```

Edit: Having not noticed the requirement to take a numeric input, i'm going to claim it does take one on the commandline, but ignores it =)

# Answer
> 1 votes
# EcmaScript 6:

```
z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(i=9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)

```

This will use 100% of the CPU on a single-core machine, and with Firefox, it has the added bonus that Firefox keeps using up more and more memory; the whole interface locks up and the only way to stop it is to kill Firefox in the task manager.

# Answer
> 1 votes
# DOS Batch - 5 bytes

```
%0|%0

```

# DOS Batch - 8 bytes

```
%0|%0&%0

```

Second is a translation of the infamous sh forkbomb.

Ctrl+C breaks the program (unless you've tweaked the settings a little).

# Answer
> 1 votes
# Java - 88 characters

```
class S{public static void main(String[]a){for(long i=0;i<Long.valueOf(a[0]);){i=i+1;}}}

```

This allows for 2⁶³-1 loops.

### More Readable Version

```
class S {
    public static void main(String[] a) {
      for (long i = 0; i < Long.valueOf(a[0]);) { i = i + 1; }
}

```

# C# - 87 characters

```
class S{public static void Main(string[]a){for(long i=0;i<long.Parse(a[0]);){i=i+1;}}}

```

### More Readable Version

```
class S {
public static void Main(string[] a) {
    for(long i = 0;i < long.Parse(a[0]);i++) { i = i + 1; }
}
}

```

(This is on a 4 core system)

# Answer
> 1 votes
# perl, 23 bytes

I can't figure out how to paste a literal control-T here, so I've typed $^T instead, but either works (the literal is 1 char shorter at 23 bytes):

```
$e=$^T+<>;1 until$e<time

```

$^T is just the time the interpreter started, so you can basically read that as time() since it is the first thing we calculate.

# Answer
> 1 votes
# Python, 30

I found this old puzzle interesting, I hope it's OK to post an answer to an old question. I just couldn't let the C answers beat Python. ;)

`sum(range(int(input())*2**26))`

This needs tuned for different CPUs, but I don't think that violates the OP... `sum(range(2**27))` pegs one of *my* 2.8GHz i7 cores for about a second. :)

---
Tags: code-golf
---