title: Friar simulator

text:
# Question
Title: Friar simulator
he brethren from the order of St Golfus the Concise have a tradition of reciting a short prayer whenever they see someone make the sign of the cross. Due to the high level of sin measured among tourists recently, they have installed CCTV in the monastery, and they've hired you to help them keep old tradition alive in the age of AI.

Your task is to analyse output from the friars' finger-tracking software and tell how many prayers are due. The input is a matrix containing integers between 0 and 4. 1,2,3,4 represent the positions of fingers at consecutive moments in time. 0 represents non-fingers.

The One True WayTM to cross oneself is:

```
.1.
3.4
.2.

```

("." matches any digit). However, due to uncertainty about the rotation of the camera and the presence of pious Eastern Orthodox brethren in the crowd (whose One True WayTM is in the opposite sideways direction), you should count all rotations and reflections too:

```
.4. .2. .3. .1. .3. .2. .4.
1.2 4.3 2.1 4.3 1.2 3.4 2.1
.3. .1. .4. .2. .4. .1. .3.

```

One digit may be part of multiple crosses. Help the friars determine the number of times their AI should `.pray()` by counting how many of the above 3x3 submatrices are present. Write a program or a function. Take input in any reasonable convenient form.

Testament cases:

```
// in
[[0,4,2,0],
 [1,3,2,4],
 [2,3,1,0]]

// out
2

// in
[[4,3,3,2,4,4,1,3,2,2],
 [0,3,0,2,1,1,2,3,2,3],
 [0,3,1,3,2,4,3,3,1,1],
 [4,3,2,3,2,4,1,4,2,3],
 [0,4,2,3,4,0,2,3,2,4],
 [2,1,0,0,2,0,0,1,2,4],
 [4,0,3,1,3,2,0,3,2,3],
 [1,4,3,3,1,4,0,1,4,4],
 [0,2,4,3,4,3,1,3,0,4],
 [3,0,1,0,4,0,3,3,3,3]]

// out
3

// in
[[3,2,3,1,0,3,4,2,1,1,1,1,4,0,1,3,1,1,2,1,1,3,0,1,0,1,1,0,0,1,0,3,4,0,1,1,2,3,1,2,4,1,0,2,3,0,2,4,3,2],
 [2,4,1,1,0,3,0,2,4,2,3,2,1,3,0,2,3,2,4,4,4,3,2,1,1,3,2,1,2,3,2,4,0,3,1,4,4,1,1,0,1,1,0,2,2,3,1,2,0,2],
 [3,4,0,0,4,4,0,3,4,4,1,3,2,1,3,2,3,2,2,0,4,0,1,2,3,0,4,3,2,2,2,0,3,3,4,4,2,2,1,4,4,1,3,1,1,2,0,1,1,0],
 [1,4,2,2,2,1,3,4,1,1,2,1,4,0,3,2,2,4,1,3,3,0,4,1,1,0,0,1,2,2,1,3,4,0,4,1,0,1,1,0,2,1,3,1,4,4,0,4,3,2],
 [4,4,2,0,4,4,1,1,2,2,3,3,2,3,0,3,2,1,0,3,3,4,2,2,2,1,1,4,3,2,1,1,4,3,4,2,4,0,1,0,2,4,2,2,0,3,3,0,3,2],
 [4,3,3,1,3,1,1,3,3,1,0,1,4,3,4,3,4,1,2,2,1,1,2,1,4,2,1,1,1,1,1,3,3,3,1,1,4,4,0,0,3,3,1,4,4,3,2,3,3,0],
 [1,4,1,4,0,0,1,3,1,2,2,1,1,2,3,3,2,0,3,4,3,2,1,2,2,3,3,1,4,2,1,1,4,1,3,2,0,0,0,1,2,4,1,1,3,0,4,2,3,1],
 [2,2,3,0,0,4,2,1,2,3,1,2,4,1,0,1,0,2,4,1,3,4,4,0,0,4,0,4,4,2,0,0,2,2,3,3,4,1,0,3,2,1,0,1,1,0,3,0,3,2],
 [1,2,4,3,4,3,1,2,2,3,0,1,2,4,4,4,3,1,2,3,4,3,3,2,0,0,2,0,3,4,4,2,3,2,0,2,4,3,0,0,0,4,4,0,4,4,0,3,3,3],
 [4,4,1,2,0,2,2,0,0,3,2,3,2,3,4,1,0,2,3,0,3,2,1,1,4,3,0,2,3,1,0,4,1,2,4,1,1,4,4,4,2,2,2,3,0,1,0,3,0,1],
 [4,0,3,0,2,2,0,3,2,2,2,4,0,4,0,1,0,1,4,3,3,2,3,1,2,2,4,4,0,3,2,3,1,4,1,0,3,2,3,2,2,0,1,2,4,0,3,0,4,4],
 [0,4,0,1,0,2,3,2,1,3,1,1,2,0,3,2,1,4,0,1,4,4,1,3,4,4,1,0,4,1,0,3,4,0,3,2,4,3,3,3,3,1,2,2,3,3,3,1,3,4],
 [3,4,1,2,1,1,1,0,4,0,1,1,0,4,1,3,1,1,2,0,2,1,4,1,4,4,3,2,0,3,0,3,0,1,1,2,1,3,0,4,4,2,2,2,1,3,4,1,1,1],
 [3,0,1,4,2,0,0,3,1,1,1,4,4,0,2,2,0,4,0,3,1,0,2,2,4,4,4,0,4,4,4,4,4,4,3,0,4,4,4,1,2,4,4,3,0,0,4,0,4,2],
 [2,0,1,2,1,1,3,0,3,1,0,4,3,1,2,1,1,3,0,1,2,4,2,1,2,3,4,2,4,4,2,2,3,4,0,0,1,0,0,4,1,3,3,4,1,2,1,3,3,2],
 [4,0,2,0,3,1,2,1,1,1,1,2,3,0,3,1,0,4,3,0,0,0,2,0,1,4,0,2,1,3,4,2,2,4,2,3,1,2,0,2,0,2,4,0,1,2,3,4,1,3],
 [3,0,2,4,2,0,3,4,3,2,3,4,2,0,4,1,0,4,3,3,1,0,2,2,2,1,3,3,1,1,0,3,3,0,3,2,1,1,0,1,2,2,0,4,4,2,0,1,3,1],
 [0,4,4,4,0,3,0,3,0,2,2,0,1,2,3,3,4,3,0,4,1,2,3,3,0,2,2,3,0,0,0,2,4,2,3,4,2,3,4,0,2,0,1,1,3,4,2,2,4,4],
 [2,1,2,3,4,3,1,2,0,0,0,0,0,0,3,4,3,3,1,2,2,1,3,4,1,2,4,0,1,4,1,0,0,0,2,1,1,1,3,0,0,3,1,1,4,2,1,3,4,1],
 [1,0,3,0,2,1,4,2,3,3,1,1,3,4,4,0,1,2,1,3,0,3,1,1,3,0,2,4,4,4,2,3,1,4,3,4,0,1,4,1,1,1,4,0,0,2,3,4,0,4]]

// out
8

```

"Blessed be the shortest of shortests, for it winneth the kingdom of upvotes." -Book of St Golfus 13:37

"Thou shalt not use loopholes, for they are the wicked works of Lucifer." -Letter to the Meta 13:666

Slight visualization of people making the cross

```
var html = $('pre').html();
html = html.split('0').join('<span class="zero">0</span>')
.split('1').join('<span class="one">1</span>')
.split('2').join('<span class="two">2</span>')
.split('3').join('<span class="three">3</span>')
.split('4').join('<span class="four">4</span>')
$('pre').html(html);
var count =['zero','one','two','three','four'];
var counter = 0;
var $all = $('span');
window.setInterval(function() {
  var clazz = count[counter];
  counter++;
  if(counter == count.length) {
     counter = 0;
  }
  $all.css({'color':'white'});
  $('span.'+clazz).css({'color':''});

},1000)
```

```
.zero {
    color:blue;
}
.one {
    color:green;
}
.two {
    color:gray;
}
.three {
  color:orange;
}
.four {
  color: red;
}
span {
  transition:1s ease-out;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
  // in
[[0,4,2,0],
 [1,3,2,4],
 [2,3,1,0]]

// out
2

// in
[[4,3,3,2,4,4,1,3,2,2],
 [0,3,0,2,1,1,2,3,2,3],
 [0,3,1,3,2,4,3,3,1,1],
 [4,3,2,3,2,4,1,4,2,3],
 [0,4,2,3,4,0,2,3,2,4],
 [2,1,0,0,2,0,0,1,2,4],
 [4,0,3,1,3,2,0,3,2,3],
 [1,4,3,3,1,4,0,1,4,4],
 [0,2,4,3,4,3,1,3,0,4],
 [3,0,1,0,4,0,3,3,3,3]]

// out
3

// in
[[3,2,3,1,0,3,4,2,1,1,1,1,4,0,1,3,1,1,2,1,1,3,0,1,0,1,1,0,0,1,0,3,4,0,1,1,2,3,1,2,4,1,0,2,3,0,2,4,3,2],
 [2,4,1,1,0,3,0,2,4,2,3,2,1,3,0,2,3,2,4,4,4,3,2,1,1,3,2,1,2,3,2,4,0,3,1,4,4,1,1,0,1,1,0,2,2,3,1,2,0,2],
 [3,4,0,0,4,4,0,3,4,4,1,3,2,1,3,2,3,2,2,0,4,0,1,2,3,0,4,3,2,2,2,0,3,3,4,4,2,2,1,4,4,1,3,1,1,2,0,1,1,0],
 [1,4,2,2,2,1,3,4,1,1,2,1,4,0,3,2,2,4,1,3,3,0,4,1,1,0,0,1,2,2,1,3,4,0,4,1,0,1,1,0,2,1,3,1,4,4,0,4,3,2],
 [4,4,2,0,4,4,1,1,2,2,3,3,2,3,0,3,2,1,0,3,3,4,2,2,2,1,1,4,3,2,1,1,4,3,4,2,4,0,1,0,2,4,2,2,0,3,3,0,3,2],
 [4,3,3,1,3,1,1,3,3,1,0,1,4,3,4,3,4,1,2,2,1,1,2,1,4,2,1,1,1,1,1,3,3,3,1,1,4,4,0,0,3,3,1,4,4,3,2,3,3,0],
 [1,4,1,4,0,0,1,3,1,2,2,1,1,2,3,3,2,0,3,4,3,2,1,2,2,3,3,1,4,2,1,1,4,1,3,2,0,0,0,1,2,4,1,1,3,0,4,2,3,1],
 [2,2,3,0,0,4,2,1,2,3,1,2,4,1,0,1,0,2,4,1,3,4,4,0,0,4,0,4,4,2,0,0,2,2,3,3,4,1,0,3,2,1,0,1,1,0,3,0,3,2],
 [1,2,4,3,4,3,1,2,2,3,0,1,2,4,4,4,3,1,2,3,4,3,3,2,0,0,2,0,3,4,4,2,3,2,0,2,4,3,0,0,0,4,4,0,4,4,0,3,3,3],
 [4,4,1,2,0,2,2,0,0,3,2,3,2,3,4,1,0,2,3,0,3,2,1,1,4,3,0,2,3,1,0,4,1,2,4,1,1,4,4,4,2,2,2,3,0,1,0,3,0,1],
 [4,0,3,0,2,2,0,3,2,2,2,4,0,4,0,1,0,1,4,3,3,2,3,1,2,2,4,4,0,3,2,3,1,4,1,0,3,2,3,2,2,0,1,2,4,0,3,0,4,4],
 [0,4,0,1,0,2,3,2,1,3,1,1,2,0,3,2,1,4,0,1,4,4,1,3,4,4,1,0,4,1,0,3,4,0,3,2,4,3,3,3,3,1,2,2,3,3,3,1,3,4],
 [3,4,1,2,1,1,1,0,4,0,1,1,0,4,1,3,1,1,2,0,2,1,4,1,4,4,3,2,0,3,0,3,0,1,1,2,1,3,0,4,4,2,2,2,1,3,4,1,1,1],
 [3,0,1,4,2,0,0,3,1,1,1,4,4,0,2,2,0,4,0,3,1,0,2,2,4,4,4,0,4,4,4,4,4,4,3,0,4,4,4,1,2,4,4,3,0,0,4,0,4,2],
 [2,0,1,2,1,1,3,0,3,1,0,4,3,1,2,1,1,3,0,1,2,4,2,1,2,3,4,2,4,4,2,2,3,4,0,0,1,0,0,4,1,3,3,4,1,2,1,3,3,2],
 [4,0,2,0,3,1,2,1,1,1,1,2,3,0,3,1,0,4,3,0,0,0,2,0,1,4,0,2,1,3,4,2,2,4,2,3,1,2,0,2,0,2,4,0,1,2,3,4,1,3],
 [3,0,2,4,2,0,3,4,3,2,3,4,2,0,4,1,0,4,3,3,1,0,2,2,2,1,3,3,1,1,0,3,3,0,3,2,1,1,0,1,2,2,0,4,4,2,0,1,3,1],
 [0,4,4,4,0,3,0,3,0,2,2,0,1,2,3,3,4,3,0,4,1,2,3,3,0,2,2,3,0,0,0,2,4,2,3,4,2,3,4,0,2,0,1,1,3,4,2,2,4,4],
 [2,1,2,3,4,3,1,2,0,0,0,0,0,0,3,4,3,3,1,2,2,1,3,4,1,2,4,0,1,4,1,0,0,0,2,1,1,1,3,0,0,3,1,1,4,2,1,3,4,1],
 [1,0,3,0,2,1,4,2,3,3,1,1,3,4,4,0,1,2,1,3,0,3,1,1,3,0,2,4,4,4,2,3,1,4,3,4,0,1,4,1,1,1,4,0,0,2,3,4,0,4]]

</pre>
```

---

Thanks @Tschallacka for the visualization.

# Answer
> 19 votes
## Grime, 20 bytes

```
n`.\1./\3.\4/.\2.voO

```

Try it online!

A very literal implementation of the spec:

* `n`` make Grime count the number of subrectangles of the input that yield a match.
* `.\1./\3.\4/.\2.` defines the 3x3 square:

```
.1.
3.4
.2.

```

Where `.` can be any character.
* `oO` is an orientation modifier which allows this rectangle to appear in any rotation or reflection. The `v` is used to lower `o`s precedence so that we don't need parentheses around the square.

# Answer
> 16 votes
## Snails, ~~17~~ 16 bytes

```
Ao
\1.=\2o=\3b\4

```

Try it online!

### Explanation

`A` makes Snails count the number of possible matching paths in the entire input. `o` sets the starting direction to any orthogonal direction (instead of just eastward). The pattern itself is on the second line:

```
\1    Match a 1.
.     Match an arbitrary character (the one in the centre).
=\2   Check that the next character ahead is a 2, but don't move there.
o     Turn to any orthogonal direction. In practice, this will only be one
      of the two directions from the centre we haven't checked yet.
=\3   Check that the next character ahead is a 3.
b     Turn around 180 degrees.
\4    Match a 4 in that direction.

```

# Answer
> 7 votes
# Perl, 70 bytes

Includes +2 for `0p`

Give input matrix as a block of digits without spaces on STDIN:

```
perl -0pe '$_=map{/.$/m+y/1-4/3421/;/(?=1.{@{-}}(3.4|4.3).{@{-}}2)/sg}($_)x4'
0420
1324
2310
^D

```

Rotates the cross by rotating the digits

# Answer
> 7 votes
## Haskell, ~~108~~ ~~102~~ 93 bytes

```
f((_:t:x):w@((l:q@(_:r:_)):(_:b:z):_))=sum$f((t:x):q:[b:z]):f w:[1|(l*r-1)*(t*b-1)==11]
f _=0

```

Try it online!

No regex. Pattern match

```
.t.
l.r
.b.

```

in the top left corner of the matrix , take a `1` if `(l*r-1)*(t*b-1)==11` and recursively go to the right (drop `.l.`) and down (drop first row). If the pattern cannot be matched (at the right or bottom border) take a `0`. Sum all results.

Edit: -9 bytes thanks to @xnor.

# Answer
> 6 votes
# Retina, ~~92~~ ~~83~~ 82 bytes

```
L$v`(?<=(.)*).(.)..*¶(?<6-1>.)*(.).(.).*¶(?<-6>.)*.(.)
$5$2$3$4
/../_O`.
1234|3412

```

Try it online! Explanation:

```
L$v`(?<=(.)*).(.)..*¶(?<6-1>.)*(.).(.).*¶(?<-6>.)*.(.)
$5$2$3$4

```

Look for all overlapping 3x3 squares. A lookbehind captures the indent so that it can be balanced on the second line, itself transferring the indent from group 1 to group 6, so it can be balanced again on the third line. The input is assumed to be rectangular so we don't have to check that the groups balance. The bottom/top middle cells and the left/right middle cells are then captured.

```
/../_O`.

```

Sort each pair of cells into order.

```
1234|3412

```

Count the remaining valid patterns.

# Answer
> 5 votes
# Jelly, 26 bytes

```
Z3Ƥṡ€3ẎµFḊm2ṙ-s2Ṣ€ṢFµ€ċ4R¤

```

Try it online!

# Explanation

```
Z3Ƥṡ€3ẎµFḊm2ṙ-s2Ṣ€ṢFµ€ċ4R¤  Main Link
 3Ƥ                         For each 3 rows
Z                           Zip the rows
   ṡ€3                      Get all arrangements of 3 consecutive columns from these rows. At this step, we have all 3x3 contiguous submatrices
      Ẏ                     Unwrap by one layer; previously grouped by rows, now ungrouped
       µ           µ€       For each 3x3 submatrix
        F                   Flatten it
         Ḋ                  Get rid of the first element
          m2                Take every second element (this only keeps the edges)
            ṙ-              Rotate right 1 element
              s2            Group into pairs; now the top and bottom are grouped and the left and right are grouped
                Ṣ€          Sort each pair
                  Ṣ         Sort the pairs
                   F        Flatten
                      ċ4R¤  Count the number of occurrences of range(4); i.e. [1,2,3,4]

```

-3 bytes thanks to Jonathan Allan (2) and Mr. Xcoder (3) (merged)

# Answer
> 5 votes
# Java 8, ~~135~~ ~~133~~ 131 bytes

```
m->{int r=0,i=0,j;for(;++i<m.length-1;)for(j=1;j<m[i].length-1;)if(~(m[i-1][j]*m[i+1][j])*~(m[i][j-1]*m[i][++j])==39)r++;return r;}

```

-2 bytes thanks to *@tehtmi* for a shorter formula: `(l*r-1)*(t*b-1)==11` to `~(l*r)*~(t*b)==39`

**Explanation:**

Try it online.

```
m->{                     // Method with integer-matrix parameter and integer return-type
  int r=0,               //  Result-integer, starting at 0
      i=0,j;             //  Index integers
  for(;++i<m.length-1;)  //  Loop over the rows, skipping the first and last
    for(j=1;j<m[i].length-1;)
                         //   Inner loop over the columns, skipping the first and last
      if(~(m[i-1][j]*m[i+1][j])*~(m[i][j-1]*m[i][++j])==39)
                         //    If (-(bottom*top)-1) * (-(left*right)-1) is exactly 39:
        r++;             //     Increase the result-counter by 1
  return r;}             //  Return the result-counter

```

# Answer
> 4 votes
# Husk, 23 bytes

```
#ö§&¦ḣ4SδΛ≈↔Ċ2tΣṁoX3TX3

```

Try it online!

## Explanation

```
#ö§&¦ḣ4SδΛ≈↔Ċ2tΣṁoX3TX3  Implicit input, a list of lists of integers.
                     X3  Length-3 slices.
                ṁ        Map over them and concatenate:
                    T     Transpose,
                 oX3      then get length-3 slices.
                         Now we have a list of 3x3-arrays of the (transposed) input.
#ö                       Return number of 3x3-arrays that satisfy this:
                          Take m = [[0,3,0],[2,4,1],[1,4,0]] as an example.
               Σ          Concatenate: [0,3,0,2,4,1,1,4,0]
              t           Tail: [3,0,2,4,1,1,4,0]
            Ċ2            Take every second element: c = [3,2,1,4]
  §&                      c satisfies both of the following:
    ¦                     1) It contains every element of
     ḣ4                      the range [1,2,3,4].
       Sδ                 2) If you zip c
           ↔                 with its reverse,
         Λ                   then each corresponding pair
          ≈                  has absolute difference at most 1.
                         Implicitly print the result.

```

# Answer
> 3 votes
# Python 3, ~~120~~ 118 bytes

```
lambda x:sum({x[i+1][j]*x[i+1][j+2],x[i][j+1]*x[i+2][j+1]}=={2,12}for i in range(len(x)-2)for j in range(len(x[0])-2))

```

Try it online!

Uses the fact that the product of opposite pairs of numbers in the cross must be 2 and 12 respectively, and compares with a set to cover all the different orientations. Takes input as a 2D array of integers.

# Answer
> 3 votes
# Dyalog APL, ~~30~~ ~~29~~ ~~28~~ ~~27~~ 26 bytes (SBCS)

```
+/∘,{12 2⍷×∘⌽⍨⊢/4 2⍴⍵}⌺3 3

```

Try it online!

# Answer
> 2 votes
# Jelly, 36 bytes

```
“ƒɦƈạ%ȤFE’b4s4
ṡ3µZṡ3F€µ€ẎḊm2$$€’f¢L

```

Try it online!

# 37 bytes

For some reason I can't move the `Ḋm2$$` to the top link.

```
ṙ1s2I€FPA,P⁼1,24
ṡ3µZṡ3F€µ€ẎḊm2$$€Ç€S

```

Try it online!

# Answer
> 2 votes
# Clean, ~~255~~ ... 162 bytes

It isn't beneficial that often to use pattern filters in comprehensions, but in this case, it is.

```
import StdEnv,StdLib
? =reverse
@ =transpose
t=tails
$m=sum[1\\f<-[id,@,?,?o@,@o?,@o?o@,?o@o?o@,?o@o?],[a,b,c:_]<-t(f m),[_,1:_]<-t a&[3,_,4:_]<-t b&[_,2:_]<-t c]

```

Try it online!

Defines the function `$`, taking `[[Int]]` and returning `Int`.

It first generates all symmetries of the matrix `m` (transforming via `f`), takes the `tails` of which have three or more rows, and synchronously checks how many of the first three sets of columns from the `tails` of each row match the pattern of the cross.

This is equivalent to counting the number of ordered `tails`-of-`tails` matching the pattern `[[_,1,_:_],[3,_,4:_],[_,2,_:_]:_]` \- which is in turn logically the same as checking if, for each cell in the matrix, that cell is the upper-left corner of any rotation of the cross.

# Answer
> 2 votes
# Japt `-x`, ~~39~~ ~~38~~ 33 bytes

```
ã3 Ëmã3 y x@[XXy]®g1 ë2 ×Ãn e[2C]

```

Try it online!

-1 byte thanks to @Shaggy.

-5 bytes thanks to @ETHproductions by refactoring the array.

### Unpacked & How it works

```
Uã3 mD{Dmã3 y xX{[XXy]mZ{Zg1 ë2 r*1} n e[2C]

       Input: 2D Array of numbers
Uã3    Generate an array of length 3 segments of U
mD{    Map... (D = 2D array of numbers having 3 rows)
Dmã3     Map over each row of D to generate an array of length 3 segments
y        Transpose; make an array of 3x3 subsections
xX{      Map and sum... (x = 3x3 2D array of numbers)
[XXy]      Array of X and X transposed
mZ{        Map...
Zg1 ë2 r*1   Take row 1, take 0th and 2nd elements, reduce with *
}
n          Sort the array
e[2C]      Equals [2,12] element-wise?
           Implicit cast from boolean to number

       Result: 1D array of counts
-x     Sum of the result array

```

There should *still* be a better way to test for the cross...

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


title: Only Even Bytes

text:
# Question
Title: Only Even Bytes
## The scenario

Lately you have been noticing some strange behavior with your favorite text editor. At first it seemed that it was ignoring random characters in your code when writing to disk. After a while you noticed a pattern; characters with odd ASCII values were being ignored. Under further inspection you discovered that you can only write to files properly if every eighth bit is zero. Now you need to know if your valuable files have been affected by this strange bug.

## The task

You must write a complete program that determines if a file contains any odd bytes (demonstrating it is uncorrupted). But because of your text editor **you cannot write any odd bytes in your source code.** You may assume any pre-existing encoding for input, however you must still check every individual byte, not just characters.

### Input

Your program will take the contents of or the path to a file from either stdin or command line.

### Output

Your program will output to stdout either a truthy value if the given file contains an odd byte or a falsy if every eighth bit is zero.

## Criteria

This is code golf, shortest program that completes the task wins. To be a valid submission every eighth bit in the files source code must be a zero. I would recommend including a copy of your source code's binaries in your submission.

Standard loopholes apply.

## Test Cases

(In ASCII encoding) Input:

```
"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

Output:
falsy

Input:
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

Output:
truthy

Input:
LOREMIPSVMDOLORSITAMETCONSECTETVRADIPISCINGELITSEDDOEIVSMODTEMPORINCIDIDVNTVTLABOREETDOLOREMAGNAALIQVA
VTENIMADMINIMVENIAMQVISNOSTRVDEXERCITATIONVLLAMCOLABORISNISIVTALIQVIPEXEACOMMODOCONSEQVAT
DVISAVTEIRVREDOLORINREPREHENDERITINVOLVPTATEVELITESSECILLVMDOLOREEVFVGIATNVLLAPARIATVR
EXCEPTEVRSINTOCCAECATCVPIDATATNONPROIDENTSVNTINCVLPAQVIOFFICIADESERVNTMOLLITANIMIDESTLABORVM

Output:
truthy

```

## Tips

* Choose language wisely this challenge might not be possible in every language
* The Unix command `xxd -b <file name>` will print the binaries of a file to the console (along with some extra formatting stuff)
* You may use other encodings other than ASCII such as UTF-8 as long as all other rules are followed

# Answer
# GS2, 4 bytes

```
dΦ("

```

Try it online!

### Hexdump

```
0000000: 64 e8 28 22                                      d.("

```

### How it works

```
      (implicit) Read all input and push it on the stack.
 Φ    Map the previous token over all characters in the string:
d       Even; push 1 for even characters, 0 for odd ones.
  (   Take the minimum of the resulting list of Booleans.
   "  Negate the minimum.

```
> 26 votes

# Answer
## Befunge, 36 bytes

I know this is an old question, but I wanted to give it a try because I thought it would be an interesting challenge in Befunge.

```
>~:0`|
>20`:>$.@
|` " "<
*8*82<^p24*

```

Try it online!

It outputs `1` if the input is corrupted (i.e. contains an odd byte), and `0` if it's OK.

**Explanation**

The problem is how to determine odd bytes without having access to the `/` (divide) or `%` (modulo) commands. The solution was to multiply the value by 128 (the sequence `28*8**`), then write that result into the playfield. On a strictly standard interpreter, playfield cells are signed 8 bit values, so an odd number multiplied by 128 becomes truncated to -1 while an even number becomes 0.

The other trick was in reading the -1 or 0 back from the playfield without having access to the `g` (get) command. The workaround for this was to write the value into the middle of an existing string sequence (`" "`), then execute that sequence to push the enclosed value onto the stack. At that point, determining the oddness of the byte is a simple less-than-zero test.

One final aspect worth discussing is the output. In the false case, we reach the `>$.` sequence with just one value on the stack, so `$` clears the stack making the `.` output a zero. In the true case, we follow the path `20`:>$.`. Since two is greater than zero, the comparison pushes a one onto the stack, and the `:` makes a duplicate copy so the `$` won't drop it before it gets output.
> 21 votes

# Answer
## CJam (11 bytes)

```
"r2":(~f&2b

```

Online demo

Stripping away the tricks to avoid odd bytes, this reduces to

```
q1f&2b

```

which reads the input, maps a bitwise AND with `1`, and then performs a base conversion, giving zero iff all of the ANDs were zero.
> 12 votes

# Answer
# Printable .COM file, 100 bytes

```
^FZjfDXVL\,LPXD$$4"PXD,lHPXDjJXDRDX@PXDjtXDH,nPXDj@XD4`@PXD,ZHPXD4,@PXD4:4"PXDH,\PXD4"PXD,hPXDRDX@P\

```

Hexdump:

```
00000000  5e 46 5a 6a 66 44 58 56  4c 5c 2c 4c 50 58 44 24  |^FZjfDXVL\,LPXD$|
00000010  24 34 22 50 58 44 2c 6c  48 50 58 44 6a 4a 58 44  |$4"PXD,lHPXDjJXD|
00000020  52 44 58 40 50 58 44 6a  74 58 44 48 2c 6e 50 58  |RDX@PXDjtXDH,nPX|
00000030  44 6a 40 58 44 34 60 40  50 58 44 2c 5a 48 50 58  |Dj@XD4`@PXD,ZHPX|
00000040  44 34 2c 40 50 58 44 34  3a 34 22 50 58 44 48 2c  |D4,@PXD4:4"PXDH,|
00000050  5c 50 58 44 34 22 50 58  44 2c 68 50 58 44 52 44  |\PXD4"PXD,hPXDRD|
00000060  58 40 50 5c                                       |X@P\|
00000064

```

Using a *very loose* definition of source as something that can be reasonably typed by a human, and inspired by EICAR Standard Antivirus Test File (more info at *"Let's have fun with EICAR test file"* at Bugtraq).

Using only printable non-odd ASCII bytes (side note: opcodes affecting words tend to be odd, the W bit is the lsb of some opcodes), it constructs a fragment of code at SP (which we conveniently set just past our generating code), and execution ends up falling through to the generated code.

It uses the fact that the stack initially contains a near pointer to the start of the PSP, and that the start of the PSP contains the `INT 20h` instruction (more info on this at https://stackoverflow.com/questions/12591673/).

Real source:

```
; we want to generate the following fragment of code

;  5E                pop si             ; zero SI (pop near pointer to start of PSP)
;  46                inc si             ; set SI to 1
; loop:
;  B406              mov ah,0x6         ; \
;  99                cwd                ; >
;  4A                dec dx             ; > D-2106--DLFF
;  CD21              int 0x21           ; > DIRECT CONSOLE INPUT
;  7405              jz end             ; > jump if no more input
;  40                inc ax             ; > lsb 0/1 odd/even
;  21C6              and si,ax          ; > zero SI on first odd byte
;  EBF3              jmp short loop     ; /
; end:
;  96                xchg ax,si         ; return code
;  B44C              mov ah,0x4c        ; D-214C
;  CD21              int 0x21           ; TERMINATE WITH RETURN CODE

 pop si             ; this two opcodes don't need to be encoded
 inc si

 pop dx             ; DX = 20CD (int 0x20 at start of PSP)
 push byte +0x66
 inc sp
 pop ax
 push si
 dec sp
 pop sp             ; SP = 0x0166
 sub al,0x4c        ; B4
 push ax
 pop ax
 inc sp
 and al,0x24
 xor al,0x22        ; 06
 push ax
 pop ax
 inc sp
 sub al,0x6c
 dec ax             ; 99
 push ax
 pop ax
 inc sp
 push byte +0x4a    ; 4A
 pop ax
 inc sp
 push dx            ; [20]CD
 inc sp
 pop ax
 inc ax             ; 21
 push ax
 pop ax
 inc sp
 push byte +0x74    ; 74
 pop ax
 inc sp
 dec ax
 sub al,0x6e        ; 05
 push ax
 pop ax
 inc sp
 push byte +0x40    ; 40
 pop ax
 inc sp
 xor al,0x60
 inc ax             ; 21
 push ax
 pop ax
 inc sp
 sub al,0x5a
 dec ax             ; C6
 push ax
 pop ax
 inc sp
 xor al,0x2c
 inc ax             ; EB
 push ax
 pop ax
 inc sp
 xor al,0x3a
 xor al,0x22        ; F3
 push ax
 pop ax
 inc sp
 dec ax
 sub al,0x5c        ; 96
 push ax
 pop ax
 inc sp
 xor al,0x22        ; B4
 push ax
 pop ax
 inc sp
 sub al,0x68        ; 4C
 push ax
 pop ax
 inc sp
 push dx            ; [20]CD
 inc sp
 pop ax
 inc ax
 push ax            ; 21
 pop sp             ; now get the stack out of the way

```
> 10 votes

# Answer
# MATL, 7 bytes

```
l$Z$2\z

```

The source code uses UTF-8 encoding. So the source bytes are (in decimal)

```
108    36    90    36    50    92   122

```

The input is a file name, taken as a string enclosed in single quotes. The output is the number of odd bytes in the file, which is truthy iff nonzero.

### Explanation

```
l    % Push a 1. We use `l` instead of `1` to have an even value
$    % Input specificication. This indicates that the next function takes 1 input
Z$   % Input file name implicitly, read its raw bytes and push them as an array of chars
2\   % Modulo 2
z    % Number of nonzero values. This gives the number of odd bytes. Implicitly display

```
> 9 votes

# Answer
# CJam, ~~18~~ ~~17~~ 15 bytes

```
"<rj":(((*~:|X&

```

Assumes that the locale is set to Latin-1. Try it online!

### How it works

The straightforward solution goes as follows.

```
q       e# Read all input from STDIN and push it as a string on the stack.
 :i     e# Cast each character to its code point.
   :|   e# Take the bitwise OR of all code points.
     X  e# Push 1.
      & e# Take the bitwise AND of the logical OR and 1.

```

Unfortunately, the characters `q` and `i` cannot appear in the source code. To work around this issue, we are going to create part of the above source code dynamically, then evaluate the string.

```
"<rj"         e# Push that string on the stack.
     :(       e# Decrement all characters, pushing ";qi".
       (      e# Shift out the first character, pushing "qi" and ';'.
        (     e# Decrement ';' to push ':'.
         *    e# Join "qi" with separator ':', pushing "q:i".
          ~   e# Evaluate the string "q:i", which behaves as explained before.

```
> 8 votes

# Answer
# Pyth, ~~20~~ 13 bytes

```
vj0>LhZ.BRj.z

```

Or in binary:

```
00000000: 01110110 01101010 00110000 00111110 01001100 01101000  vj0>Lh
00000006: 01011010 00101110 01000010 01010010 01101010 00101110  Z.BRj.
0000000c: 01111010                                               z

```

Try it online

### How it works

```
           .z   all lines of input
          j     join on newline
       .BR      convert each character to binary
   >LhZ         take the last (0 + 1) characters of each binary string
 j0             join on 0
v               evaluate as an integer

```

The resulting integer is truthy (nonzero) iff any of the bytes were odd.
> 7 votes

# Answer
# Jelly, 13 bytes

```
24‘ịØBvF|\ṪBṪ

```

Expects the input as a quoted command-line argument. Try it online!

### Hexdump

```
0000000: 32 34 fc d8 12 42 76 46 7c 5c ce 42 ce           24...BvF|\.B.

```
> 4 votes

# Answer
# Retina, 106 bytes

Removes every allowed character, then matches any remaining characters. Truthy values will be the number of characters found. Falsey values will be `0`.

```
`"| |\$|&|\(|\*|,|\.|0|2|4|6|8|:|<|>|@|B|D|F|H|J|L|N|P|R|T|V|X|Z|\\|\^|`|b|d|f|h|j|l|n|p|r|t|v|x|z|\||~

.

```

**Try it online**

Since `.` doesn't match newlines by default, I don't have to remove them.
> 4 votes

# Answer
## Perl 5 \+ `-p0`, 136 bytes

Similar to other answers, this removes all even bytes and leaves any odd bytes (which is truthy).

```
tr<�
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\\^`bdfhjlnprtvxz|~€‚„†ˆŠŒŽ’”–˜šœž ¢¤¦¨ª¬®°²´¶¸º¼¾ÀÂÄÆÈÊÌÎÐÒÔÖØÚÜÞàâäæèêìîðòôöøúüþ><>d

```

Try it online!
> 1 votes

# Answer
# Japt, 10 bytes

```
ø0ôH² ®dZÄ

```

Try it online!

Japt's codepage is ISO-8859-1. The code gives `false` when itself is entered as a string, therefore a valid submission.

### Unpacked & How it works

```
Uø0ôHp2  mZ{ZdZ+1

Uø      Does input string contain any element in the following array...?
0ôHp2     Range of 0 to 32**2, inclusive
mZ{       Map...
ZdZ+1       Convert the number Z to a char having charcode 2*Z+1

```

Not having `String.c` (get charcode, or map over charcodes) was a pain, but fortunately there is `Number.d` (convert number to char).

Turns out that Japt wins over CJam, Pyth *and* Jelly :)

---

Without the restriction, there are a couple of ways to do it in **6 bytes** (going par with CJam and Jelly again):

```
®c uÃn

Unpacked: UmZ{Zc u} n

UmZ{   Map on each char...
Zc u     Convert to charcode modulo 2
}
n      Convert the resulting string to number

```

`"000..000"` is converted to the number 0 (falsy) regardless of how long it is. On the other hand, anything that contains 1 is converted to a nonzero `double`, or `Infinity` if it's too big (both truthy).

```
¬d_c u

Unpacked: q dZ{Zc u

q    Convert to array of chars
dZ{  Is something true when mapped with...
Zc u   Convert each char to charcode modulo 2

```

More straightforward approach that directly yields `true` or `false`.

Or, **5 bytes** solution is even possible with the help of `-d` flag:

```
¬®c u

Unpacked: q mZ{Zc u

q     Convert to array of chars
mZ{   Map...
Zc u    Convert to charcode modulo 2

      Result is array of zeros and ones
-d    Apply .some() on the resulting array

```
> 0 votes

---
Tags: code-golf, restricted-source, binary, decision-problem
---


title: Smallest possible version of abs

text:
# Question
Title: Smallest possible version of abs
The abs() function in most languages does one thing: give the positive version of the input. Most of the times this is done using something similar to

```
int
abs (int i)
{
    return i < 0 ? -i : i;
}

```

I was wondering if there is any way to do this with less bytes. Note that this doesn't have to be more efficient, just smaller

Edit: i forgot to add that you can't use the abs() function in your language

# Answer
> 4 votes
## Retina, 2 bytes

```
-

```

Try it online!

Just remove the minus sign...

# Answer
> 2 votes
# TI-Basic, 3 bytes

```
√(AnsAns

```

Square root of input * input. Alternatively, `√(Ans²` is also 3 bytes.

# Answer
> 2 votes
# , 8 bytes

```
(x^2)^.5

```

Try it online!

thanks to @Giuseppe

---

Former, 1 byte longer version :

# , 9 bytes

```
x*sign(x)

```

Try it online!

# Answer
> 1 votes
# Whitespace, ~~48~~ 47 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate][S S S T   S T T   S T N
_Push_45_-][T   S S T   _Subtract][N
T   S N
_If_0_jump_to_Label_LOOP][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start LOOP:
  Character c = STDIN as character
  if(c == '-')
    Go to next iteration of LOOP
  Print c
  Go to next iteration of LOOP

```

---

**Old 48 bytes answer:**

```
[S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate][N
T   T   S N
_If_negative_jump_to_Label_NEG][N
S N
N
_Jump_to_Label_PRINT][N
S S S N
_Create_Label_NEG][S S T    T   N
_Push_-1][T S S N
_Multiply][N
S S N
_Create_Label_PRINT][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer i = STDIN as integer
if(i is negative)
  i = i * -1
  Jump to function PRINT
else
  Jump to function PRINT

function PRINT:
  Print i as integer to STDOUT

```

# Answer
> 0 votes
# 05AB1E, 2 bytes

```
nt

```

Try it online.

**Explanation:**

```
n     # Square
      #  i.e. 5 → 25
      #  i.e. -5 → 25
 t    # Square-root
      #  25 → 5

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 3 bytesSBCS

There are a few interesting approaches to this. All are anonymous tacit prefix functions. H.PWiz added two more.

`⊢××` The argument multiplied by its sign. Try it online!

`⊢⌈-` Max of the argument and its negation. Try it online!

`⊢∧×` The LCM of the argument and its sign. Try it online!

`⊢∨-` The GCD of the argument and its negation. Try it online!

`⊢÷×` The argument divided by its sign. Try it online! Handles complex numbers but needs `⎕DIV` (**Div**ision method) set to 1.

# Answer
> 0 votes
# sed, 5 bytes

```
s/-//

```

Strip the negative sign

# Answer
> 0 votes
# Java 8, 13 bytes

```
n->n<0?n*-1:n

```

Try it online.

Boring, but can't be done shorter without `Math.` or using `-n` directly (a.f.a.i.k.).

# Answer
> 0 votes
# , 2 bytes

Anonymous tacit prefix function.

`%*` The argument (implicit) divided by its sign. Try it online! Handles complex numbers as well.

# Answer
> 0 votes
# Python 2, 18 bytes

```
lambda x:max(-x,x)

```

Try it online!

**Previous (20 bytes)**

```
lambda x:(x,-x)[x<0]

```

Try it online!

# Answer
> 0 votes
# Japt, 2 bytes

Multiply input by its sign.

```
*g

```

Try it

Another square/root solution.

```
²q

```

Try it

Slightly less trivial 4 byte solution: convert to string, remove non-digit characters and convert back to integer. Or, if input can be taken as a string, this one can simply be `r-`.

```
sr\D

```

Try it

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


title: Use that goodn't meme

text:
# Question
Title: Use that goodn't meme
There is currently a meme on the internet that consist of taking a sentence, reverse the meaning and adding `n't` at the end. For example, `I am small` becomes `I am talln't`

## Challenge

For the sake of the challenge, we'll simplify this : Your task will be to detect whenever there is a negation in a sentence, and replace it with the 'positive' one with `n't` added at the end. There will be some tricky parts that will be explained in the rules.

## Rules

* You have to take a *String* as *input*, and return a *String* as *output*.
* Input will be a sentence **in lowercase**, with only `.` and `,` as punctuation marks.
* You have to replace any `no <any_word>` or `not <any_word>` with `<any_word>n't`.
* `no`/`not` have to be a word and **not** a substring : you don't have to change anything in `none of those`
* If the word already finish with a `n`, you have to replace `n't` with `'t` : `no plan` become `plan't` and **not** `plann't`
* When `no` or `not` isn't followed by any word, a punctuation mark or another `no`/`not`, you have to replace it with **`yesn't`**.
* compound words count as one word. so even if `no-op` contain the substring `no`, it doesn't contain the **word** no. So the result will be `no-op` and **not** `-opn't`.
* You do not have to worry about grammar errors. For example, `there is no way` will result to `there is wayn't`.
* No standard loopholes allowed.
* This is , so the shortest code wins.

There are some examples, even if this challenge looks clearn't for now.

## Examples

> **Input :** i love codegolfing, but i do not like short programs. does this sentence makes sense ... of course no.
> **Output :** i love codegolfing, but i do liken't short programs. does this sentence makes sense ... of course yesn't.
>
> **Input** : you are not invited. get out.
> **Output** : you are invitedn't. get out.
>
> **Input** : i am not ok, i have no plan and i have no gunn
> **Output** : i am okn't, i have plan't and i have gunn't
>
> **Input** : oh no no no i refuse.
> **Output** : oh yesn't yesn't in't refuse.
>
> **Input** : oh no no no, i refuse.
> **Output** : oh yesn't yesn't yesn't, i refuse.
>
> **Input** : i cannot believe this, you can't codegolf.
> **Output** : i cannot believe this, you can't codegolf.
>
> **Input** : oh no ... he did it again.
> **Output** : oh yesn't ... he did it again.
>
> **Input** : nn't is not a word, kevin. so this is not nn't.
> **Output** : nn't is an't word, kevin. so this is nn'tn't.
>
> **Input** : is it not clearn't for everyone
> **Output** : is this clearn'tn't for everyone
>
> **Input** : this is non't sense ...
> **Output** : this is non't sense ...

# Answer
# Retina, ~~86~~ ~~70~~ 65 bytes

```
T`-'`L
\bnot?\s+(?!not?\b)(\w+?)n?\b
$1n't
\bnot?\b
yesn't
T`L`-'

```

-16 bytes thanks to *@Neil*.
-5 bytes thanks to *@ovs*.

Try it online.

**Explanation:**

```
T`-'`L             # Replace all "-" with "A" and all "'" with "B" to store them

\bnot?             # Then replace the word "no" or "not",
 \s+               #  followed by 1 or more whitespaces,
 (?!not?\b)(\w+?)  #  followed by a word/letter that is not "not" or "no"
 n?\b              #  minus a single trailing "n" if there are any
$1                 # with: the word/letter
 n't               #  appended with "n't"

\bnot?\b           # Then replace any remaining loose "no" or "not"
yesn't             # with "yesn't"

T`L`-'             # And finally replace all "A" with "-" and all "B" with "'" again

```
> 5 votes

# Answer
# Python 2, ~~208~~ ~~123~~ ~~113~~ 146 bytes

```
lambda s:re.sub(r"\bnot?\b(?!['-])(\s(?!not?(\b)(?!['-]))([\w'-]+))?",lambda m:(m.group(3)or"yes")+"n't"[(m.group(3)or'')[-1:]=='n':],s)
import re

```

Try it online!

Lost a bunch of bytes because of words ending in `n't` or `n`. Either or is shorter, but handling both was longer.
> 4 votes

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

```
s=>s.replace(/\bnot?\b( (?!not?\b)(['\w-]*(\w)))?/g,(a,b,s,t)=>(s||'yes')+(t=='n'?'':'n')+"'t")

```

Try it online!

Thank Rick Hitchcock for 2 bytes
> 2 votes

# Answer
# Stax, ~~75~~ ~~73~~ 50 bytes

```
ä§▀t9lJ₧5M#|+4╖¼├n▌ ·=┌«∙£╣▀K╖¥y▐▲·(■◄╙→á╣ó•ô╓╢Θ₧○

```

Run and debug it
> 2 votes

# Answer
# Japt, 72 bytes

```
F=_r"%bnot?%s+(?!not?%b)(%w+?)n?%b|%bnot?%b(?!['-])",@Y=Y||"yes"Y+"n't"}

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~163~~ 136 bytes

```
s->s.replaceAll("(^|[ ,.])not?(?= *([,.]|$|not?(?=$|[ ,.])))","$1yesn't").replaceAll("(^|[ ,.])not? ([\\w'-]+?)n?(?=$|[ ,.])","$1$2n't")

```

-27 bytes by creating a port of *@recursive*'s Stax' answer.

Try it online.
> 0 votes

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


title: LaTeX truth tables

text:
# Question
Title: LaTeX truth tables
Write a program or a function that accepts the list of outputs from a logic function and outputs the LaTeX code for its truth table.

The inputs should be labeled as lowercase letters `a-z`, and the output should be labelled as `F`. The length of list of inputs will always be shorter than `2^25`, which means that number of inputs will always be less than 25, so you can use letters from lowercase alphabet for input names.

## Input

A number `n` of inputs and list of length `2^n` of binary numbers which represents the outputs of a logical function.

## Output

LaTeX code that produces the truth table for that function. Input and output values should be centered in rows. There must be a line between table header and its values and between inputs and output, so the code should be similar to that below.

```
\begin{tabular}{c * <NUMBER OF INPUTS>|c}
<INPUTS>&F\\
\hline
<INPUT VECTOR i>&<OUTPUT>\\
\end{tabular}

```

## Example

Input:

```
2
[0, 0, 0, 1]

```

Output:

```
\begin{tabular}{cc|c}
a & b & F \\
\hline
0 & 0 & 0 \\
0 & 1 & 0 \\
1 & 0 & 0 \\
1 & 1 & 1 \\
\end{tabular}

```

Which when displayed in LaTeX shows the following truth table

## General rules

# Answer
# Charcoal, 70 bytes

```
≔tabularζ\ζ{*θc|c}⸿⪫✂β⁰Ｉθ¹&⁰&F\\⸿\hline⸿Ｅη⁺⪫⁺⮌ＥＩθＩ﹪÷κＸ²λ²⟦ι⟧&¦\\⁰\endζ

```

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

```
≔tabularζ

```

Save this string in a variable to avoid duplication.

```
\ζ{*θc|c}⸿

```

Print the initial `\tabular{*2c|c}` line (2 or whatever value the first input `q` has).

```
⪫✂β⁰Ｉθ¹&⁰&F\\⸿\hline⸿

```

Get the first `q` letters from the predefined variable `b` and insert `&`s between them, then append the `&F\\` and also print `\hline` on the next line.

```
Ｅη⁺⪫⁺⮌ＥＩθＩ﹪÷κＸ²λ²⟦ι⟧&¦\\

```

Loop over the characters in the second input. For each one, its index is converted to binary with length `q`, the character is concatenated, the result is joined with `&`s and `\\` is appended. The resulting strings are implicitly printed on separate lines.

```
⁰\endζ

```

Print the `\endtabular`. (The  is just a separator as the deverbosifier forgots to insert a `¦`.)
> 10 votes

# Answer
# Python 2, 153 bytes

```
lambda n,l:r'\tabular{*%dc|c}%s&F\\\hline%s\endtabular'%(n,q(map(chr,range(97,97+n))),r'\\'.join(q(bin(2**n+i)[3:]+x)for i,x in enumerate(l)))
q='&'.join

```

Try it online!

Outputs like

```
\tabular{*2c|c}a&b&F\\\hline0&0&0\\0&1&0\\1&0&0\\1&1&1\endtabular

```

`\tabular` and `\endtabular` are used as shorter `\begin{tabular}` and `\end{tabular}`, as per this LaTeX golf tip. The `*2c` is a shorthand to define 2 columns.
> 6 votes

# Answer
## Haskell, ~~164~~ 155 bytes

```
s%f=((:"&")=<<s)++f:"\\\\"
n#r=unlines$("\\tabular{"++('c'<$[1..n])++"|c}"):take n['a'..]%'F':"\\hline":zipWith(%)(mapM id$"01"<$[1..n])r++["\\endtabular"]

```

Try it online!

```
unlines                               -- take a list of strings and join it with NL.
                                      -- the strings are:
   "\\tabular{"++('c'<$[1..n])++"|c}" -- tabular definition with n times 'c'
   take n['a'..]%'F'                  -- table header
   "\\hline"                          -- hline
   zipWith(%)(mapM id$"01"<$[1..n])r  -- table content
   ["\\endtabular"]                   -- end of tabular definition

Table header and content are built via function '%'

s%f=                                  -- take a string 's' and a char 'f'
    ((:"&")=<<s)                      -- append a "&" to each char in 's'
    ++f:"\\\\"                        -- and append 'f' and two backslashes

Table header:

take n['a'..] % 'F'                   -- s: the first n letters from the alphabet
                                      -- f: char 'F'
Table content:

zipWith(%)                            -- apply '%' pairwise to
    mapM id$"01"<$[1..n]              -- all combinations of '0' and '1' of length n
    r                                 -- and the string 'r'

```

Edit: using `\tabular` instead of `\begin{tabular}` (stolen from @xnor's answer).
> 5 votes

# Answer
# Python 2, ~~192~~ ~~168~~ 166 bytes

```
lambda n,l:r'\begin{tabular}{*%dc|c}%s\end{tabular}'%(n,r'\\'.join(map('&'.join,[map(chr,range(97,97+n))+[r'F\\\hline']]+[bin(2**n+i)[3:]+l[n]for i in range(2**n)])))

```

Try it online!

Pretty printed version:

# Python 2, ~~234~~ ~~229~~ ~~218~~ ~~209~~ ~~205~~ 203 bytes

```
n,l=input()
print'\\begin{tabular}{'+'c'*n+'|c}\n'+' & '.join(chr(i+97)for i in range(n)+[-27]),'\\\\\n\hline'
i=0
for r in l:print' & '.join(bin(i)[2:].rjust(n,'0')+`r`),r'\\';i+=1
print'\\end{tabular}'

```

Try it online!
> 3 votes

# Answer
# Proton, 142 bytes

```
n=>x=>"\\tabular*#{n}c|c#{j(map(chr,97..97+n))}&F\\\\\hline"+'\\\\'.join(j(bin(i)[2to].zfill(n)+x[i])for i:0..len(x))+"\\endtabular"j="&".join

```

Try it online!

Output is in golfed LaTeX form; thanks to xnor for that trick!

~~This should be able to be golfed to shorter than xnor's Python answer because Proton should in theory never lose to Python lol (in practice I'm bad xD). I may steal some tricks from xnor ;P~~

Managed to now be shorter by making some things into variables, which I just noticed xnor also did :P

And there we go, -6 bytes by using some Proton golfing tricks.
> 2 votes

# Answer
# , ~~196 187~~ 171 bytes

```
function(m,n){cat("\\tabular{*",n,"c|c}")
write(c(letters[1:n],"F\\\\\\hline",rbind(t(rev(expand.grid(rep(list(0:1),n)))),paste0(m,"\\\\")),"\\endtabular"),1,n+1,sep="&")}

```

Try it online!

Output similar to the Charcoal answer. `expand.grid` from this answer.

For the record, using `xtable` from the eponym package is not ~~much~~ shorter since one has to specify a lot of options to match the spec, in addition to including the package:

### , 187 bytes

```
function(m,n){u=rbind(apply(expand.grid(rep(list(0:1),n)),1,rev),m)
rownames(u)=c(letters[1:n],"F")
print(xtable(t(u),dig=0,align=c(rep("c",n+1),"|c}")),hl=0,include.r=F)}
library(xtable)

```

Try it online!
> 1 votes

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


title: Is this a Weyr matrix?

text:
# Question
Title: Is this a Weyr matrix?
There's a type of *n*×*n* matrix *W* called the basic Weyr canonical form. Such a matrix is described by its blocks and has the following properties, using the following reference diagram:

* the main diagonal blocks *Wii* are *ni×ni* matrices of the form λ***Ini*** where ***Ini*** is the *ni×ni* identity matrix.
* *n1 ≥ n2 ≥ ... ≥ nr*
* the first superdiagonal blocks *Wk-1,k* for *k ∈ 2..r* are *nk-1×nk* matrices that are *full column rank in row-reduced echelon form*, or more simply put, ***Ink*** sitting on top of *nk-1 \- nk* rows of zeros.
* all other blocks are **0** matrices.

For example:

* The main diagonal blocks (yellow) are such that the ni are 4, 2, 2, and 1.
* The first superdiagonal blocks are in green.
* The grey zone consists of all the other blocks, which are all **0**.

For this challenge we will assume λ=1.

## Input

A square matrix with 0s and 1s in any convenient format.

## Output

Output one of two distinct values for whether the input matrix is Weyr or not Weyr.

## Rules

This is . Fewest bytes in each language wins. Standard rules/loopholes apply.

## Test cases

Presented as arrays of rows.

Weyr:

```
[[1]]
[[1,1],[0,1]]
[[1,0,1,0,0],[0,1,0,1,0],[0,0,1,0,1],[0,0,0,1,0],[0,0,0,0,1]]
[[1,0,0,1,0,0,0,0,0],[0,1,0,0,1,0,0,0,0],[0,0,1,0,0,1,0,0,0],[0,0,0,1,0,0,1,0,0],[0,0,0,0,1,0,0,1,0],[0,0,0,0,0,1,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,1]]
[[1,0,0,0,1,0,0,0,0],[0,1,0,0,0,1,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,1,0,1,0,0],[0,0,0,0,0,1,0,1,0],[0,0,0,0,0,0,1,0,1],[0,0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1]]

```

Non-Weyr:

```
[[0]]
[[1,0],[1,1]]
[[1,0,0,1,0,0],[0,1,0,0,0,0],[0,0,1,0,0,1],[0,0,0,1,0,0],[0,0,0,0,1,0],[0,0,0,0,0,1]]
[[1,0,1,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]]
[[1,0,0,1,0,0,0,0,0],[0,1,0,0,1,0,0,0,0],[0,0,1,0,0,1,0,0,0],[0,0,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0,0],[0,0,0,0,0,1,0,1,0],[0,0,0,0,0,0,1,0,1],[0,0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,0,1]]

```

# Answer
> 3 votes
# K (ngn/k), ~~91~~ ~~88~~ ~~84~~ ~~80~~ 81 bytes

```
{x~e|(-n)#'(0*x),'(!n)=\:,/(-1_b)+1_0{x#!y}':|-n-':|b:|\@[-1++/|\|+x|e:=n:#x;]\0}

```

Try it online!

# Answer
> 1 votes
# Python 2, 270 bytes

```
lambda m,w=0:{w}&{0,len(m)}and I(m)or any(I([l[:i]for l in m[:i]])*I([l[i:j+i]for l in m[:j]])*(sum(sum(m[:i]+[l[:i]for l in m],[]))==2*i+j)and f([l[i:]for l in m[i:]],j)for i in range(w,len(m))for j in range(1,i+1))
I=lambda m:all(sum(l)==l[i]>0for i,l in enumerate(m))

```

Try it online!

Explanation:

Recursively checks blocks for identity and their superdiagonal blocks.

`I` checks if a matrix is an identity matrix

```
I=lambda m:all(sum(l)==l[i]>0for i,l in enumerate(m))

```

For each block of the input matrix, the function checks that it is an identity, and that there is another identity matrix block, to it's right. The next iteration then looks at a block of that size.

```
{w}&{0,len(m)}and I(m)                # if the while matrix is an identity matrix,
                                      # return true (but only the first time or last block)
or
any(
 I([l[:i]for l in m[:i]])                         # the current block is identity
 *I([l[i:j+i]for l in m[:j]])                     # and, the smaller block to the right is identity
 *(sum(sum(m[:i]+[l[:i]for l in m],[]))==2*i+j)   # and everything below and to the right (not the
                                                  # smaller block), are 0
 and f([l[i:]for l in m[i:]],j)                   # and the remaining matrix is alse Weyr(recursively)
 for i in range(w,len(m))             # for each block size i
 for j in range(1,i+1)                # for each smaller right block of size j
)

```

---
Tags: code-golf, decision-problem, matrix
---


title: Tips for golfing in Common Lisp

text:
# Question
Title: Tips for golfing in Common Lisp
What general tips do you have for golfing in Common Lisp? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Common Lisp (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
> 2 votes
Use `'` (quote) as synonym for `""` for single words.

Quote stops evaluation of symbol, allowing you to e.g. print it. Note that the casing is dependant on `*print-case*` variable (most of the time it's in the upcase).

```
(print"yes")
(print'yes) ; saved a byte!

```

# Answer
> 1 votes
# Use the best looping construct for the job

Use looping constructs that are as short as possible - `loop for` is rarely the way to go:

* `(dotimes(i <number>))` to loop a certain number of times
* `(mapcan lambda list)` to map a list
* `(mapcar lambda list)` to map and flatten a list
* `(do((var1 initialvalue1 nextvalue1)(var2 initialvalue2 nextvalue2)...)((endcondition)returnvalue))` for more complex loops
* `(map'string body list)` to map string -\> string
* `(map nil body list)` to iterate over a list

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


title: Find All Distinct Gozinta Chains

text:
# Question
Title: Find All Distinct Gozinta Chains
# Gozinta Chains

(Inspired by Project Euler #606)

A gozinta chain for n is a sequence `{1,a,b,...,n}` where each element properly divides the next. For example, there are eight distinct gozinta chains for 12:

```
{1,12}, {1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}.

```

## The Challenge

Write a program or function that accepts a positive integer (`n > 1`) and outputs or returns all the distinct gozinta chains for the given number.

1. Order in the chains matters (ascending), order of the chains does not.
2. On the off-chance it exists, you cannot use a builtin that solves the challenge.
3. This is .

Edit: Removing `1` as a potential input.

# Answer
> 10 votes
# Python 3, 68 65 bytes

**Edit:** -3 bytes thanks to @notjagan

```
f=lambda x:[y+[x]for k in range(1,x)if x%k<1for y in f(k)]or[[x]]

```

Try it online!

# Explanation

Each **gozinta chain** consists of the number `x` at the end of the chain, with at least one divisor to the left of it. For each divisor `k` of `x` the chains `[1,...,k,x]` are distinct. We can therefore for each divisor `k` find all of its distinct **gozinta chains** and append `x` to the end of them, to get all distinct **gozinta chains** with `k` directly to the left of `x`. This is done recursively until `x = 1` where `[[1]]` is returned, as all **gozinta chains** start with 1, meaning the recursion have bottomed out.

The code becomes so short due to Python list comprehension allowing double iteration. This means that the values found in `f(k)` can be added to the same list for all of the different divisors `k`.

# Answer
> 7 votes
## Husk, 13 bytes

```
ufo=ḣ⁰…ġ¦ΣṖḣ⁰

```

A somewhat different approach to that of H.PWiz, though still by brute force. Try it online!

## Explanation

The basic idea is to concatenate all subsequences of `[1,...,n]` and split the result into sublists where each element divides the next. Of these, we keep those that start with `1`, end with `n` and contain no duplicates. This is done with the "rangify" built-in . Then it remains to discard duplicates.

```
ufo=ḣ⁰…ġ¦ΣṖḣ⁰  Input is n=12.
           ḣ⁰  Range from 1: [1,2,..,12]
          Ṗ    Powerset: [[],[1],[2],[1,2],[3],..,[1,2,..,12]]
         Σ     Concatenate: [1,2,1,2,3,..,1,2,..,12]
       ġ¦      Split into slices where each number divides next: [[1,2],[1,2],[3],..,[12]]
 fo            Filter by
      …        rangified
   =ḣ⁰         equals [1,...,n].
u              Remove duplicates.

```

# Answer
> 5 votes
# Jelly, ~~9~~ 8 bytes

```
ÆḌß€Ẏ;€ȯ

```

Try it online!

Uses a similar technique to my Japt answer, and therefore runs very quickly on larger test cases.

### How it works

```
ÆḌß€Ẏ;€ȯ    Main link. Argument: n (integer)
ÆḌ          Yield the proper divisors of n.
       ȯ    If there are no divisors, return n. Only happens when n is 1.
  ß€        Otherwise, run each divisor through this link again. Yields
            a list of lists of Gozinta chains.
    Ẏ       Tighten; bring each chain into the main list.
     ;€     Append n to each chain.

```

# Answer
> 4 votes
## Mathematica, 77 bytes

```
FindPath[Graph@Cases[Divisors@#~Subsets~{2},{m_,n_}/;m∣n:>m->n],1,#,#,All]&

```

Forms a `Graph` where the vertices are the `Divisors` of the input `#`, and the edges represent proper divisibility, then finds `All` paths from the vertex `1` to the vertex `#`.

# Answer
> 3 votes
# Jelly, 12 bytes

```
ŒPµḍ2\×ISµÐṀ

```

A monadic link accepting an integer and returning a list of lists of integers.

**Try it online!**

### How?

We want all the sorted lists of unique integers between one and N such that the first is a one, the last is N, and all pairs divide. The code achieves this filter by checking the pair-wise division criteria is satisfied over the power-set of the range in question, but only picking those with maximal sums of incremental difference (the ones which both start with one and end with N will have a sum of incremental differences of N-1, others will have less).

```
ŒPµḍ2\×ISµÐṀ - Link: number N
ŒP           - power-set (implicit range of input) = [[1],[2],...,[N],[1,2],[1,3],...,[1,N],[1,2,3],...]
          ÐṀ - filter keep those for which the result of the link to the left is maximal:
  µ      µ   - (a monadic chain)
    2\       -   pairwise overlapping reduce with:
   ḍ         -     divides? (1 if so, 0 otherwise)
       I     -   increments  e.g. for [1,2,4,12] -> [2-1,4-2,12-4] = [1,2,8]
      ×      -   multiply (vectorises) (no effect if all divide,
             -                          otherwise at least one gets set to 0)
        S    -   sum         e.g. for [1,2,4,12] -> 1+2+8 = 11 (=12-1)

```

# Answer
> 3 votes
# Japt, 17 bytes

```
â¬£ßX m+S+URÃ·ª'1

```

Test it online!

Weirdly, generating the output as a string was way easier than generating it as an array of arrays...

### Explanation

```
 â¬ £  ßX m+S+URÃ ·  ª '1
Uâq mX{ßX m+S+UR} qR ||'1   Ungolfed
                            Implicit: U = input number, R = newline, S = space
Uâ                          Find all divisors of U,
  q                           leaving out U itself.
    mX{         }           Map each divisor X to
       ßX                     The divisor chains of X (literally "run the program on X")
          m    R              with each chain mapped to
           +S+U                 the chain, plus a space, plus U.
                  qR        Join on newlines.
                     ||     If the result is empty (only happens when there are no factors, i.e. U == 1)
                       '1     return the string "1".
                            Otherwise, return the generated string.
                            Implicit: output result of last expression

```

# Answer
> 3 votes
## JavaScript (Firefox 30-57), 73 bytes

```
f=n=>n>1?[for(i of Array(n).keys())if(n%i<1)for(j of f(i))[...j,n]]:[[1]]

```

Conveniently `n%0<1` is false.

# Answer
> 3 votes
# Mathematica, 60 bytes

```
Cases[Subsets@Divisors@#,x:{1,___,#}/;Divisible@@Reverse@{x}]&

```

Uses the undocumented multi-arg form of `Divisible`, where `Divisible[n1,n2,...]` returns `True` if `n2∣n1`, `n3∣n2`, and so on, and `False` otherwise. We take all `Subsets` of the list of `Divisors` of the input `#`, then return the `Cases` of the form `{1,___,#}` such that `Divisible` gives `True` for the `Reverse`d sequence of divisors.

# Answer
> 3 votes
# Haskell, 107 100 95 bytes

```
f n=until(all(<2).map head)(>>=h)[[n]]
h l@(x:_)|x<2=[l]|1<2=map(:l)$filter((<1).mod x)[1..x-1]

```

Maybe there is a better termination condition (tried something like

```
f n=i[[n]]
i x|g x==x=x|1<2=i$g x
g=(>>=h)

```

but it's longer). The check for `1` seems prudent as scrubbing repeat `1`s or duplicates (`nub` not in `Prelude`) is more bytes.

Try it online.

# Answer
> 3 votes
# Haskell (Lambdabot), ~~92~~ 85 bytes

```
x#y|x==y=[[x]]|1>0=(guard(mod x y<1)>>(y:).map(y*)<$>div x y#2)++x#(y+1)
map(1:).(#2)

```

Needs Lambdabot Haskell since `guard` requires `Control.Monad` to be imported. Main function is an anonymous function, which I'm told is allowed and it shaves off a couple of bytes.

*Thanks to Laikoni for saving seven bytes.*

**Explanation:**

Monads are very handy.

```
x # y

```

This is our recursive function that does all the actual work. `x` is the number we're accumulating over (the product of the divisors that remain in the value), and `y` is the next number we should try dividing into it.

```
 | x == y = [[x]]

```

If `x` equals `y` then we're done recursing. Just use `x` as the end of the current gozinta chain and return it.

```
 | 1 > 0 =

```

Haskell golf-ism for "True". That is, this is the default case.

```
(guard (mod x y < 1) >>

```

We're operating inside the list monad now. Within the list monad, we have the ability to make multiple choices at the same time. This is very helpful when finding "all possible" of something by exhaustion. The `guard` statement says "only consider the following choice if a condition is true". In this case, only consider the following choice if `y` divides `x`.

```
(y:) . map (y *) <$> div x y#2)

```

If `y` does divide `x`, we have the choice of adding `y` to the gozinta chain. In this case, recursively call `(#)`, starting over at `y = 2` with `x` equal to `x / y`, since we want to "factor out" that `y` we just added to the chain. Then, whatever the result from this recursive call, multiple its values by the `y` we just factored out and add `y` to the gozinta chain officially.

```
++

```

Consider the following choice as well. This simply adds the two lists together, but monadically we can think of it as saying "choose between doing this thing OR this other thing".

```
x # (y + 1)

```

The other option is to simply continue recursing and not use the value `y`. If `y` does not divide `x` then this is the only option. If `y` does divide `x` then this option will be taken as well as the other option, and the results will be combined.

```
map (1 :) . (# 2)

```

This is the main gozinta function. It begins the recursion by calling `(#)` with its argument. A `1` is prepended to every gozinta chain, because the `(#)` function never puts ones into the chains.

# Answer
> 3 votes
## Haskell, 51 bytes

```
f 1=[[1]]
f n=[g++[n]|k<-[1..n-1],n`mod`k<1,g<-f k]

```

Recursively find gozinta chains of proper divisors and append `n`.

Try it online!

# Answer
> 2 votes
# Jelly, 17 bytes

```
ḊṖŒP1ppWF€ḍ2\Ạ$Ðf

```

Try it online!

# Answer
> 2 votes
# Mathematica, 104 bytes

```
(S=Select)[Rest@S[Subsets@Divisors[t=#],FreeQ[#∣#2&@@@Partition[#,2,1],1>2]&],First@#==1&&Last@#==t&]&

```

# Answer
> 2 votes
## Mathematica ~~86~~ 77 Bytes

```
Select[Subsets@Divisors@#~Cases~{1,___,#},And@@BlockMap[#∣#2&@@#&,#,2,1]&]&

```

Brute force by the definition.

Wishing there was a shorter way to do pairwise sequential element comparison of a list.

Thanks to @Jenny\_mathy and @JungHwanMin for suggestions saving 9 bytes

# Answer
> 2 votes
# Mathematica, 72 bytes

```
Cases[Subsets@Divisors@#,{1,___,#}?(And@@BlockMap[#∣#2&@@#&,#,2,1]&)]&

```

### Explanation

```
Divisors@#

```

Find all divisors of the input.

```
Subsets@ ...

```

Generate all subsets of that list.

```
Cases[ ... ]

```

Pick all cases that match the pattern...

```
{1,___,#}

```

Beginning with 1 and ending with `<input>`...

```
?( ... )

```

and satisfies the condition...

```
And@@BlockMap[#∣#2&@@#&,#,2,1]&

```

The left element divides the right element for all 2-partitions of the list, offset 1.

# Answer
> 2 votes
# TI-BASIC, 76 bytes

```
Input N
1→L1(1
Repeat Ans=2
While Ans<N
2Ans→L1(1+dim(L1
End
If Ans=N:Disp L1
dim(L1)-1→dim(L1
L1(Ans)+L1(Ans-(Ans>1→L1(Ans
End

```

# Explanation

```
Input N                       Prompt user for N.
1→L1(1                        Initialize L1 to {1}, and also set Ans to 1.

Repeat Ans=2                  Loop until Ans is 2.
                              At this point in the loop, Ans holds the
                              last element of L1.

While Ans<N                   While the last element is less than N,
2Ans→L1(1+dim(L1              extend the list with twice that value.
End

If Ans=N:Disp L1              If the last element is N, display the list.

dim(L1)-1→dim(L1              Remove the last element, and place the new
                              list size in Ans.

L1(Ans)+L1(Ans-(Ans>1→L1(Ans  Add the second-to-last element to the last
                              element, thereby advancing to the next
                              multiple of the second-to-last element.
                              Avoid erroring when only one element remains
                              by adding the last element to itself.

End                           When the 1 is added to itself, stop looping.

```

I could save another 5 bytes if it's allowed to exit with an error instead of gracefully, by removing the Ans\>1 check and the loop condition. But I'm not confident that's allowed.

# Answer
> 1 votes
# Husk, ~~17~~ 16 bytes

-1 byte, thanks to Zgarb

```
foEẊ¦m`Je1⁰Ṗthḣ⁰

```

Try it online!

# Answer
> 0 votes
# PHP ~~147~~ 141

Edited to remove a redundant test

```
function g($i){$r=[[1]];for($j=2;$j<=$i;$j++)foreach($r as$c)if($j%end($c)<1&&$c[]=$j)$r[]=$c;foreach($r as$c)end($c)<$i?0:$R[]=$c;return$R;}

```

## Explained:

```
function g($i) {

```

15 chars of boilerplate :(

```
    $r = [[1]];

```

Init the result set to `[[1]]` as every chain starts with 1. This also leads to support for 1 as an input.

```
    for ($j = 2; $j <= $i; $j++) {
        foreach ($r as $c) {
            if ($j % end($c) < 1) {
                $c[] = $j;
                $r[] = $c;
            }
        }
    }

```

For every number from 2 to `$i`, we're going to extend each chain in our set by the current number *if* it *gozinta*, then, add the extended chain to our result set.

```
    foreach ($r as $c) {
        end($c) < $i ? 0 : $R[] = $c;
    }

```

Filter out our intermediate chains that didn't make it to `$i`

```
    return $R;
}

```

10 chars of boilerplate :(

# Answer
> -1 votes
# Mathematica

```
f[1] = {{1}};
f[n_] := f[n] = Append[n] /@ Apply[Join, Map[f, Most@Divisors@n]]

```

Answer is cached for additional calls.

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


# Question
Title: Array-of-array string conversion to and from matrix
Matrix challenges are popular. There's an issue of how to provide test cases. A common method is the *row-wise array-of-arrays* representation, such as:

```
[[1,2],[3,4],[5,6]] -> a 3 by 2 matrix

```

This is good with vertical space, but there's always the task of converting the test cases into something your language can use, and vice versa for producing test cases to this format.

So this is a challenge and also a repository of conversion functions that people can use when trying or composing matrix challenges.

## Defining the format

A **row string of length *m*** is a comma-separated list of *m ≥ 1* numbers, enclosed in square brackets.

A **row-wise *n×m* array-of-arrays string** is a comma-separated list of *n ≥ 1* **row strings of length *m*** enclosed in square brackets with the following whitespace rules:

* has no whitespace before the first `[` or after the last `]`, except for an optional trailing newline.
* otherwise may contain spaces

## The challenge

Produce two\* programs/functions in your language:

1. one which takes a **rowwise *n×m* array-of-arrays string** as an input, and outputs the matrix (as implemented in the language.)
2. another one which takes an *n×m* matrix (as implemented in the language) as an input and outputs the **rowwise *n×m* array-of-arrays string**.

\*It is allowed for one program/function to perform both tasks and you can have helper code used by both conversion functions.

## Rules

* To be clear: the language must support matrices (or something equivalent like 2D arrays - the name is not important) because the output/input of the two tasks needs to be an actual matrix in the language.
* This is .
* Fewest total number of bytes (from all functions and any helper code) in each language wins.
* If one program or function does both conversions, only count those bytes once.
* Standard rules apply/loopholes forbidden.

## Test strings

```
[[1]]
[ [ 1, 2 ], [ 3, 4 ] ]
[[1.2,3.4,5.6],[3,2,1], [10, 11, 12.1]]

```

Not really possible to provide test *matrices*.

### A non-golfed, possibly not bug-free worked example

I hope this doesn't violate the "don't answer your own question" guideline.

The R function I use to convert from string to matrix

The R function I use to convert from matrix to string

*Here's the Sandbox and a related question.*

# Answer
# Japt, 30 bytes

```
F=_OxZ}G=_Oo'[+Zm_'[+Z+']} +']

```

Try it online!

Function `F` converts a string into a matrix, and function `G` converts a matrix into a string.
> 0 votes

---
Tags: code-golf, string, matrix, conversion
---


# Question
Title: Head, Shoulders, Knees and Toes, Knees and Toes
### Introduction:

I think we all know it, and it has probably been translated in loads of different languages: the "Head, Shoulders, Knees and Toes" children song:

> Head, shoulders, knees and toes, knees and toes
> Head, shoulders, knees and toes, knees and toes
> And eyes and ears and mouth and nose
> Head, shoulders, knees and toes, knees and toes
> wikipedia

---

### Challenge:

**Input:** A positive integer.

**Output:** Output one of the following words based on the input as n-th index:

```
head
shoulders
knees
toes
eyes
ears
mouth
nose

```

Here the body parts are appended with the indexes:

```
Head (0), shoulders (1), knees (2) and toes (3), knees (4) and toes  (5)
Head (6), shoulders (7), knees (8) and toes (9), knees (10) and toes (11)
And eyes (12) and ears (13) and mouth (14) and nose (15)
Head (16), shoulders (17), knees (18) and toes (19), knees (20) and toes (21)

Head (22), shoulders (23), knees (24) and toes (25), knees (26) and toes  (27)
Head (28), shoulders (29), knees (30) and toes (31), knees (32) and toes (33)
And eyes (34) and ears (35) and mouth (36) and nose (37)
Head (38), shoulders (39), knees (40) and toes (41), knees (42) and toes (43)

etc.

```

### Challenge rules:

* You are of course allowed to use 1-indexed input instead of 0-indexed. But please specify which one you've used in your answer.
* The output is case insensitive, so if you want to output it in caps that's fine.
* You should support input up to at least 1,000.

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Test cases (0-indexed):

```
Input:  Output:
0       head
1       shoulders
7       shoulders
13      ears
20      knees
35      ears
37      nose
98      knees
543     nose
1000    knees

```

# Answer
# 05AB1E, ~~36~~ ~~35~~ 34 bytes

```
“‡ä¾ØsÏ©s¸±s“#2ä¤«Ð“—íÖÇ©¢ÄÃ“#s)˜è

```

Try it online! or as a Test suite

**Explanation**

```
“‡ä¾ØsÏ©s¸±s“                        # dictionary string 'head shoulders knees toes'
             #                       # split on spaces
              2ä                     # split in 2 parts
                ¤                    # get the last part ['knees', 'toes']
                 «                   # concatenate and flatten
                                     # STACK: [['head', 'shoulders'], ['knees', 'toes'], 'knees', 'toes']
                  Ð                  # triplicate
                   “—íÖÇ©¢ÄÃ“        # dictionary string 'eyes ears mouth nose'
                             #s      # split on spaces and swap top 2 elements of stack
                               )˜    # wrap stack in a list and flatten
                                 è   # index into list with input

```

In short, we build the list `['head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes', 'eyes', 'ears', 'mouth', 'nose', 'head', 'shoulders', 'knees', 'toes', 'knees', 'toes']` and index into it with input (0-indexed).
> 12 votes

# Answer
## JavaScript (ES6), ~~91~~ ~~88~~ 87 bytes

```
n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

```

### How it works

We have 4 distinct pairs of words that always appear together: 'head' is always followed by 'shoulders', 'knees' is always followed by 'toes', etc.

Therefore, we can use the following index:

```
00: [ 'knees', 'toes' ]
01: [ 'head', 'shoulders' ]
10: [ 'eyes', 'ears' ]
11: [ 'mouth', 'nose' ]

```

And compress the whole sequence (in reverse order) into the following binary mask:

```
00 00 01 11 10 00 00 01 00 00 01

```

We use `[ 'knees', 'toes' ]` as the first pair to get as many leading zeros as possible.

We pad this sequence with an extra `0` so that the extracted value is premultiplied by 2, which leads to:

```
0b00000111100000010000010 = 245890

```

Hence the final formula for the correct word:

```
(245890 >> (n % 22 & ~1)) & 6 | n % 2

```

### Test cases

```
let f =

n=>'knees,toes,head,shoulders,eyes,ears,mouth,nose'.split`,`[(245890>>(n%22&~1))&6|n%2]

console.log(f(0));    // head
console.log(f(1));    // shoulders
console.log(f(7));    // shoulders
console.log(f(13));   // ears
console.log(f(20));   // knees
console.log(f(35));   // ears
console.log(f(37));   // nose
console.log(f(98));   // knees
console.log(f(543));  // nose
console.log(f(1000)); // knees
```
> 32 votes

# Answer
# Python 2, ~~158~~ ~~148~~ ~~137~~ ~~128~~ ~~114~~ ~~109~~ 104 bytes

Lookup table seems better. Also shortened the big string and reordered the items. -5 bytes thanks to Rod for using string as a list.

```
c=int('602323'*2+'4517602323'[input()%22])
print"smkteehnhonoyaeooueeerasutesssdelhs"[c::8]+"ders"*(c<1)

```

initial solution:

```
n=input()%22
n-=10*(n>15)
if n>=12:n-=8
else:n%=6;n-=2*(n>3)
print"hskteemnehnoyaooaoeeerusduessste ls   h  d       e       r       s"[n::8].strip()

```
> 10 votes

# Answer
## Perl, 74 bytes

**73 bytes code + 1 for `-p`.**

```
$_=(@a=(head,shoulders,(knees,toes)x2),@a,eyes,ears,mouth,nose,@a)[$_%22]

```

Uses 0-based indexing. Doesn't output a separator, but that could be amended with `-l` in the flags.

Try it online.
> 6 votes

# Answer
# Java 7, ~~155~~ ~~137~~ ~~131~~ ~~123~~ ~~111~~ 110 bytes

```
String c(int i){return"knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",")[(245890>>(i%22&~1))&6|i%2];}

```

-12 bytes thanks to *@Neil*.
-1 byte by shamelessly creating a port of *@Arnauld*'s amazing answer.

Java is 0-indexed, so that's what I've used.

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(int i){
    return "knees,toes,head,shoulders,eyes,ears,mouth,nose".split(",")
      [(245890>>(i%22&~1))&6|i%2];
  }

  public static void main(String[] a){
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(7));
    System.out.println(c(13));
    System.out.println(c(20));
    System.out.println(c(35));
    System.out.println(c(37));
    System.out.println(c(98));
    System.out.println(c(543));
    System.out.println(c(1000));
  }
}

```

**Output:**

```
head
shoulders
shoulders
ears
knees
nose
ears
knees
nose
knees

```
> 4 votes

# Answer
# Python 2, ~~97~~ 90 Bytes

There may be some math that makes it so I don't have to make the word list, but this works for now!

```
lambda n,k='head shoulders '+'knees toes '*2:(k*2+'eyes ears mouth nose '+k).split()[n%22]

```

<sup>*Thanks to Flp.Tkc for saving 7 bytes :)*</sup>
> 4 votes

# Answer
# C, ~~153 bytes~~ 141 bytes

```
*b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"};i;char*g(a){a%=22;i=(a+4)%10;return b[a<4?a:(a&12)>8?a-8:i<2?i:a%2+2];}

```

Thanks to @cleblanc for 4 bytes. Declaring b globally throws a ton of warnings about casting to int, but didn't break for me.

Ungolfed:

```
*b[]={"head","shoulders","knees","toes","eyes","ears","mouth","nose"};
i;
char* g(a) {
    a%=22;
    i=(a+4)%10;
    return b[a < 4        ? a
            :(a & 12) > 8 ? a-8
            :i < 2        ? i
            :               a % 2 + 2];
}

```

It's not the smallest answer, but I liked the technique, and had fun finding a few patterns.

Changelog:

* Moved `b` to global to avoid `char` (4 bytes)
* `a > 11 && a < 16` =\> `(a & 12) > 8` (2 bytes)
* `i=(a-6)%10` =\> `i=(a+4)%10` so that `i < 2 && i >= 0` =\> `i < 2` (6 bytes)
> 3 votes

# Answer
# JavaScript (ES6) ~~91~~ 89 Bytes

```
f=
n=>((d='head:shoulders:'+(b='knees:toes:')+b)+d+'eyes:ears:mouth:nose:'+d).split`:`[n%22]

console.log(f.toString().length)
console.log(f(0) === 'head')
console.log(f(1) === 'shoulders')
console.log(f(7) === 'shoulders')
console.log(f(13) === 'ears')
console.log(f(20) === 'knees')
console.log(f(35) === 'ears')
console.log(f(37) === 'nose')
console.log(f(98) === 'knees')
console.log(f(543) === 'nose')
console.log(f(1000) === 'knees')
```
> 2 votes

# Answer
# PHP, 91 ~~102~~ ~~118~~ ~~128~~ ~~129~~ Bytes

```
<?=[head,shoulders,knees,toes,eyes,ears,mouth,nose]['0123230123234567012323'[$argv[1]%22]];

```

0-Indexed

Down to 91 following removal of str\_split, didn't realise PHP string were accessible as a char array (a PHP 5+ thing?)

~~Down to 102 thanks to insertusername suggestion for removing string quotes and allowing the notices~~
> 2 votes

# Answer
## R, 95 bytes

```
c(o<-c("head","shoulders",y<-c("knees","toes"),y),o,"eyes","ears","mouth","nose",o)[scan()%%22]

```

Creates a character vector to function as a lookup table. Takes input from stdin (`1-indexed`) and `%%22` to find the corresponding body part.

Bonus: `%%` is vectorized which means that this will work with a vector inputs as well.

Test cases on R-fiddle (Note that this is a named function because `scan` doesn't work on R-fiddle)
> 2 votes

# Answer
# jq, 80 characters

(77 characters code + 3 characters command line option)

```
((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22]

```

Sample run:

```
bash-4.3$ jq -r '((("head shoulders "+"knees toes "*2)*2+"eyes ears mouth nose ")*2/" ")[.%22]' <<< 1000
knees

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)
> 2 votes

# Answer
# WinDbg, ~~207~~ ~~157~~ 151 bytes

```
ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41

```

*-50 bytes by encoding the offset/length of the body parts as ascii chars.*

*-6 bytes by using a local var when looking up the offset/length.*

Input is done with a value set in the pseudo-register `$t0`.

How it works:

```
* Initialization, writes this string at address 0x2000000. The nonsense after the body parts
* are the offsets and lengths of the body parts in the first part of the string, each of
* which is incremented by 0x41 to make it a printable ascii character.
ea 2000000
        "headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";

* Display the output:
r$t4=(@$t0%16)*2+2000027
da1FFFFBF+by(@$t4) Lby(@$t4+1)-41

* Display output explanation:
r $t4 = (@$t0%16)*2+2000027   * Set $t4 = input, @$t0, mod 22, doubled +0x2000027
by(@$t4)                      * byte_at(@$t4)-0x41 is the {Offset} into the string
                              * for the start of output. The -0x41 is already subtracted
                              * from 0x2000000 to make 0x1FFFFBF.
Lby(@$t4+1)-41                * byte_at(@$t4+1)-0x41 is the {Length} of the output.
da 1FFFFBF+{Offset} L{Length} * Display {Length} chars from {Offset} of the above string.

```

Sample output:

```
0:000> r$t0=0
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000000  "head"

0:000> r$t0=1
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000004  "shoulders"

0:000> r$t0=7
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000004  "shoulders"

0:000> r$t0=0n13
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200001a  "ears"

0:000> r$t0=0n20
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

0:000> r$t0=0n35
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200001a  "ears"

0:000> r$t0=0n37
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000023  "nose"

0:000> r$t0=0n98
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

0:000> r$t0=0n543
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
02000023  "nose"

0:000> r$t0=0n1000
0:000> ea2000000"headshoulderskneestoeseyesearsmouthnoseAEEJNFSENFSEAEEJNFSENFSEWE[E_FdEAEEJNFSENF";r$t4=(@$t0%16)*2+2000027;da1FFFFBF+by(@$t4) Lby(@$t4+1)-41
0200000d  "knees"

```
> 2 votes

# Answer
# Jelly, 55 bytes

```
“¥ḷne“¥ṇṭḲ»ẋ2ṭ“¢1$“@⁼5⁼»µẋ2;“¥ḳVo“¥ḳ'k“£Qo“£³ạ»;⁸FḊḲ
ị¢

```

Try it online! (1-based index)

Come on! Really?

As a bonus, this is the compressed string I was supposed to use instead of the top line:

```
“¡¦ṡb[wfe=⁺żɦ4Gƈġhḳ"ẇ⁴ż>oH¹8ṡʠʠḟṀUṿḶ>¬Þ:ĖẇrṗṁɼlDṫỤ¬ȷ⁶Dḥci*⁻³GḲOÞạṖṃ\»

```

Both encode this string:

```
head shoulders knees toes knees toes head shoulders knees toes knees toes eyes ears mouth nose head shoulders knees toes knees toes

```

Guess I should go exercise now :P
> 1 votes

# Answer
## Powershell, 91 Bytes, Zero-Indexed

```
$a='head shoulders '+'knees toes '*2;($a*2+'eyes ears mouth nose '+$a).Split()[$args[0]%22]

```

Very straightforward approach, generate the array of the first 22 items using some string multiplication where possible, by compiling them with spaces and splitting at the end. (splitting is 2 bytes shorter than the equivalent setup as an array) then just find the point in that array using the modulus of the input, not exactly interesting or language-specific.

Test Case:

```
PS C:\++\golf> 0..1000|%{.\hskt $_}
head
shoulders
knees
toes
knees
toes
head
shoulders
knees
toes
knees
toes
eyes
ears
mouth
nose
head
shoulders
knees
toes
knees
toes
head
shoulders
knees
toes
....

```

etc.
> 1 votes

# Answer
# Befunge, ~~129~~ 119 bytes

0-indexed

```
&29+2*%:2/v>00p>%#7_v
+%2\-"/"g2<|<:-1g007<"head*shoulders*knees*toes*eyes*ears*mouth*nose"p00
02202246022>$$:>7#:%#,_@

```

Try it online!

**Explanation**

As Arnauld pointed out, the words come in pairs, so we have an index of just 11 values and then add the word number % 2 to get the appropriate word in the pair. The words are pushed onto the stack as a single string separated by asterisks to save space. We test for word breaks by taking the char value modulo 7, since only the asterisk is a multiple of 7.

```
&29+2*%               n = getint() % 22             // % 22 to ensure it's in range
:2/2g                 i = index_array[n/2]          // we use n/2 because words are paired
-"/"                  i -= '/'                      // convert from ASCII to 1-based value
\2%+                  i += n%2                      // get the correct word in the pair
00p                   index = i                     // save for later

"head*shoulders*knees*toes*eyes*ears*mouth*nose"    // push all the words onto the stack

700g1-:|              while (index-1 != 0) {        // the 7 is used in the drop loop
  00p                   index = index-1
  >%#7_                 do while (pop() % 7)        // drop up to the next '*' (%7==0)
                      }

$$                    pop();pop()                   // get rid of index and extra 7

: 7 % _               while ((c = pop()) % 7)       // output up to the next '*' (%7==0)
 > : ,                  putchar(c)

```
> 1 votes

# Answer
# ruby, 81 bytes

Lambda function using zero indexing.

```
->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]}

```

**explanation**

We generate the following array, of which we use the first 16 elements, covering the correct lines 2,3,4 of the song:

```
%w{head shoulders knees toes knees toes
   eyes ears mouth nose
   head shoulders knees toes knees toes

   eyes ears mouth nose}                  #last 4 elements not used

```

We take n modulo 22 to reduce it to a single verse, then we subtract 6. Now the index 6 (for example) has been changed to 0 and points to the right word. Indicies 0..5 which point to the first line of the song are now negative. We use `&15` (identical to `%16` but avoids the need for brackets) to map the 1st line of the song to the 4th line. Thus index `0` -\> `-6` -\> `10`

**in test program**

```
f=->n{("head shoulders#{" knees toes "*2}eyes ears mouth nose".split*2)[n%22-6&15]}

#call as below to test index 0..43
44.times{|i|p f[i]}

```
> 1 votes

# Answer
# SQL 2005 747 Bytes

Golfed:

```
GO
CREATE PROCEDURE H @n INT AS BEGIN IF NOT EXISTS(SELECT*FROM R)BEGIN INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')END SELECT W FROM R WHERE I=@n%22 END

```

Ungolfed:

```
GO
CREATE PROCEDURE H
@n INT
AS
BEGIN IF NOT EXISTS(SELECT*FROM R)
BEGIN
INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('eyes')INSERT INTO R VALUES('ears')INSERT INTO R VALUES('mouth')INSERT INTO R VALUES('nose')INSERT INTO R VALUES('head')INSERT INTO R VALUES('shoulders')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')INSERT INTO R VALUES('knees')INSERT INTO R VALUES('toes')
END
SELECT W FROM R WHERE I=@n%22 END

```

Needs a table like this, where the first column is auto-incremented:

This is a one-indexed answer. The table is populated the first time stored procedure is created - it wouldn't let me do all the `INSERT` in one statement, disappointingly, this feature is only available in `>=SQL 2008`. After this, it uses the `%22` trick from the other answers. Once the table has been populated, it only uses the last part:

```
SELECT W FROM R WHERE I=@n%22

Input:  Output:
R 1       head
R 2       shoulders
R 8       shoulders
R 14      ears
R 21      knees
R 36      ears
R 38      nose
R 99      knees
R 54      nose
R 1001    knees

```
> 1 votes

# Answer
## bash (with ed), 83 chars

1-indexed

```
ed<<<"a
head
shoulders
knees
toes
eyes
ears
mouth
nose
.
3,4t4
1,6y
6x
$(($1%22))"

```

Sample call:

```
 $ bash test.sh 1001
 knees

```
> 1 votes

# Answer
# dc, 135 bytes

```
6[head]6[:add6-r;ar:adA+r;ar:a]dshx7[shoulders]7lhx8[knees]8lhxA 2;aAlhx9[toes]9lhxB 3;aBlhx[eyes]C:a[ears]D:a[mouth]E:a[nose]F:a22%;ap

```

Try it online!

Arrays in `dc` have to be built an element at a time, which takes up the brunt of this exercise. Since 'eyes', 'ears', 'mouth', and 'nose' only appear once in our array, we just pop them in. But for the others, we save a few bytes by putting them on the stack like `x[head]x`, where *x* is the middle of its three values, then we run the macro `[:add6-r;ar:adA+r;ar:a]dshx` to put it in the array, pull it back, put it in at the same value less six, pull it back, and then put it in one last time at the original value plus ten. We use the middle value because `dc` allows us to use hex digits even in decimal mode, and subtracting `A` is one less byte than adding `16` \- this also only works because all of the middle values are under fifteen. We have to do knees and toes twice, and making our macro smart enough to sort that out is more expensive than just running the macro twice; but we do save bytes here by loading a previously stored copy of the string instead of writing it out again (`B 3;aB` vs. `B[toes]B` \- I think this saves 3 bytes total).

Once we have the array built, all we need to do is `22%` and then `;ap` to pull it from the array and print.
> 1 votes

# Answer
## C#6, 138 bytes

```
string F(int i)=>(i+10)%22<4?"eyes,ears,mouth,nose".Split(',')[(i+10)%22%4]:"head,shoulders,knees,toes,knees,toes".Split(',')[(i+6)%22%6];

```

repl.it demo

Ungolfed + comments:

```
string F(int i)=>
    // Is it eyes/ears/mouth/nose?
    (i+10)%22<4
        // If yes, then set index to 4-word line and take modular 4
        // String array constructed by splitting comma-delimited words
        ? "eyes,ears,mouth,nose".Split(',')
            [(i+10)%22%4]
        // Else set index to last 6-word line and take modular 6
        : "head,shoulders,knees,toes,knees,toes".Split(',')
            [(i+6)%22%6];

```
> 0 votes

# Answer
# Excel, 146 bytes

```
=MID("Head     ShouldersKnees    Toes     Eyes     Ears     Mouth    Nose",CHOOSE(MOD(MOD(MOD(B1+16,22),16),10)+1,1,10,19,28,19,28,37,46,55,64),9)

```

Uses @Neil's `MOD(MOD(MOD(B1+16,22),16),10)` to save `15` bytes.
> 0 votes

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