title: Fill the Golfeek gutter

text:
# Question
Title: Fill the Golfeek gutter
*Golfeek* is the working name of an esolang I'm occasionally working on. One distinctive feature of this language is that each statement is encoded as a sequence of bits rather than a sequence of bytes.

Instead of just showing a long binary sequence, the 'gutter' of the source editor contains a representation of each statement in a more digest and (slightly) more readable format:

## Format

* The binary sequence is always read from left to right.
* It is first split into nibbles (groups of 4 bits) shown as uppercase hexadecimal between brackets. A space is inserted after each byte, provided that it's followed by another byte or a last lone nibble.

*Example:*

```
[1,1,1,1,0,0,0,0,1,0,1,0] --> "[F0 A]"
 \_____/ \_____/ \_____/

```
* If there are more than 14 nibbles, only the first 6 bytes are shown, followed by a space, followed by `..`, followed by the closing bracket.
* If the number of bits is not a multiple of 4, the remaining bit(s) is/are appended as '0' or '1' right after the closing bracket.

*Example:*

```
[0,1,1,1,1,0,0,1,0,1] --> "[79]01"
 \_____/ \_____/ \_/

```

## Your task

Given a sequence of bits, return its representation in *Golfeek* format.

## Rules

* The sequence of bits may be taken in any reasonable and non-ambiguous format. Please note that the sequence may contain leading zeros, which your format must be able to deal with.
* You can assume that there will always be at least 4 bits in the input sequence, and therefore at least one nibble between the brackets.
* The output must be a string (or a list of characters) that conforms exactly to the format described above, with uppercase hexadecimal and correct spacing. A trailing linefeed is optional.
* This is .

## Test cases

### Input

```
0101
00001
110101
10100111
101001111100
000000000000000
011110101101001110010011000111
11011110101011011011111011101111
11110101000110000001111011001110011100100110111000100000100
111101010001100000011110110011100111001001101110001000001001
1111010100011000000111101100111001110010011011100010000010010

```

### Output

```
[5]
[0]1
[D]01
[A7]
[A7 C]
[00 0]000
[7A D3 93 1]11
[DE AD BE EF]
[F5 18 1E CE 72 6E 20]100
[F5 18 1E CE 72 6E ..]
[F5 18 1E CE 72 6E ..]0

```

# Answer
# 05AB1E, ~~36~~ ~~34~~ ~~33~~ 31 bytes

```
Ć4ô¤¨s¨Ch2ôJDg8@i6∍„..ª}ðý"[ÿ]ÿ

```

Try it online!
> 5 votes

# Answer
# Retina 0.8.2, ~~112~~ 111 bytes

```
.{4}
$&
(.+)
[$1]
T`d`L`.*]
B
AB
+`BA
ABB
A+(B*)
$.1
T`d`L`1\d(?=.*])
B(.)
$1
T` `_`\w..
(\[.{18})...+]
$1..]

```

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to @Grimmy. Explanation:

```
.{4}
$&

```

Group the nibbles.

```
(.+)
[$1]

```

Bracket the nibbles.

```
T`d`L`.*]

```

Change the bits used by the nibbles from `01` to `AB` to distinguish them from the spare bits.

```
B
AB
+`BA
ABB

```

Convert from binary to unary.

```
A+(B*)
$.1

```

Convert from unary to decimal.

```
T`d`L`1\d(?=.*])
B(.)
$1

```

Convert `10-15` from decimal to hexadecimal.

```
T` `_`\w..

```

Group pairs of nibbles into bytes.

```
(\[.{18})...+]
$1..]

```

Truncate the output if there are more than 14 nibbles.
> 4 votes

# Answer
# Jelly, 35 bytes

```
s4µLÐṀ©s14Ḅ‘ịØHUḢaȧ⁾..$ƊUs2KØ[j;ḟ®F

```

A full program which, given a list format of 1s and 0s, prints the result.

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

# Answer
# JavaScript (Node.js), ~~129~~ ~~124~~ 113 bytes

-5 thanks @tsh 11 more thanks @Arnauld

```
s=>'['+s.replace(/..../g,(x,i)=>(i<56?"9ABCDEF."[x=!s[59]|i<48?"0b"+x-9:7]||x+9:"")+(s[i+7]?i&4&&x-7?' ':'':']'))

```

Try it online!
> 3 votes

# Answer
# Red, 208 bytes

```
func[s][r: :rejoin b: parse s[collect[any[keep[4 skip]]copy t to end]]forall
b[b/1: pick form debase/base r["0000"b/1]2 4]b: collect[foreach[x y]b[keep
r[x any[y""]]]]if b/8[clear at b 8 b/7:".."]r["["b"]"t]]

```

Try it online!
> 2 votes

# Answer
# Charcoal, 50 bytes

```
[≔⪪Ｓ⁴θＦ›⁴Ｌ§θ±¹≔⊟θω≔⪫⪪↥⭆θ⍘↨²ι¹⁶¦² θ⎇‹²⁰Ｌθ⁺…θ¹⁸..θ]ω

```

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

```
[

```

Output the opening `[`.

```
≔⪪Ｓ⁴θ

```

Split the input into nibbles.

```
Ｆ›⁴Ｌ§θ±¹≔⊟θω

```

Save the last slice if it's not a whole nibble.

```
≔⪫⪪↥⭆θ⍘↨²ι¹⁶¦² θ

```

Convert each nibble into uppercase base 16, joining with alternate spaces.

```
⎇‹²⁰Ｌθ⁺…θ¹⁸..θ

```

If the resulting string is greater than 20 characters then truncate it to 18 and add `..` otherwise output the string.

```
]

```

Output the closing `]`.

```
ω

```

Output any left-over bits.
> 2 votes

# Answer
# Perl 5 (`-p`), ~~91~~, 89 bytes

-2 bytes thanks to Xcali++

```
s/.{4}/sprintf"%X",oct"0b$&"/eg;$\=$';s/$\$//;s-.{12}\K...+-..-;s-..(?=.)-$& -g;$_="[$_]"

```

Try it online!
> 2 votes

# Answer
# Japt, 50 bytes

```
ò4
jJUÌÊ¦4
®n2G uÃò mq
"[]"i1WjT7 ¸h18WÊ?"..":P)+V

```

Try it

```
ò4            (Input as a string) partitioned on each 4 bits.

jJ             V = get n elements from last index and remove them
  UÌÊ¦4        n = is last element length != 4 ?

®n2G uÃò mq           Convert each nibble to base 16,
     uÃ        to uppercase,
       ò mq    and join each pair.

"[]"i1         Inserts between squares :
      WjT7      first 7 elements(removing them),
           ¸    joined with space.
h18             Then replace characters at index 18 with :
   WÊ?".."       '..' if not empty
          :P     else empty string.
)+V           Finally appends remaining bits and outputs implicitly.

```
> 1 votes

# Answer
# C (gcc), ~~194~~ ~~181~~ ~~191~~ 190 bytes

Thanks to ceilingcat (-14 bytes) for the suggestions. Fixed an edge case (+10 bytes).

The function takes the input string and builds up byte-sized representations a nibble at a time, outputting the results until the sixth byte, and changing the `[` to a space after the first byte output (if there is one). The buffer is reset after each output.

After the sixth byte, nothing is output until the entire string is processed, but if the length exceeds 59 bytes (7 bytes + 3 bits), the stored representation changes to `..`, which is then output at the end. Excess bits that don't fit in a nibble are printed from the end of the input string. There is an edge case that I had to specifically check for, which is an input between 49 and 51 bytes (6 bytes + 3 bits), as an extra space would normally get printed before the ending bracket.

```
c,t;f(char*s){char u[4]="[";for(t=c=0;*s;c++>58?u[1]=u[2]=46:0)t+=t+*s++-48,c%4>2?u[c%8/4+1]=t+48+7*(t>9),t=0:0,c%8>6&c<48?printf(u),*(int*)u=32:0;printf("%s]%s",u+(c%8<1|c-48U<4),s---c%4);}

```

Try it online!
> 1 votes

# Answer
# Burlesque, 48 bytes

```
4co{L[4.<}ptl_FLjb2b62co)++sa7.>{6.+".."[+}if+]Q

```

Try it online!

```
4co       #Split into nibbles
{L[4.<}pt #Partition into those whose lengths >4 and those <4
l_FL      #Take the remainder as a flat list
jb2b6     #Convert the main block into base 16 (via binary)
2co)++    #Join as pairs
sa7.>     #Length greater than 7
{
 6.+      #Take first 6 discarding remainder
 ".."[+   #Append ".."
}if       #If length > 6
+]        #Append remainder bits
Q         #Prettify

```
> 1 votes

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


title: Spin the Calculator

text:
# Question
Title: Spin the Calculator
## Introduction:

Let's take a look at a standard Calculator in Windows:
For this challenge, we'll only look at the following buttons, and ignore everything else:

```
7 8 9 /
4 5 6 *
1 2 3 -
0 0 . +

```

## Challenge:

**Input:**
You will receive two inputs:

* One is something to indicate the rotation in increments of 90 degrees
* The other is a list of coordinates representing the buttons pressed on the rotated calculator.

Based on the first input, we rotate the layout mentioned above clockwise in increments of 90 degrees. So if the input is `0 degrees`, it remains as is; but if the input is `270 degrees`, it will be rotated three times clockwise (or once counterclockwise). Here are the four possible lay-outs:

```
Default / 0 degrees:
7 8 9 /
4 5 6 *
1 2 3 -
0 0 . +

90 degrees clockwise:
0 1 4 7
0 2 5 8
. 3 6 9
+ - * /

180 degrees:
+ . 0 0
- 3 2 1
* 6 5 4
/ 9 8 7

270 degrees clockwise / 90 degrees counterclockwise:
/ * - +
9 6 3 .
8 5 2 0
7 4 1 0

```

The second input is a list of coordinates in any reasonable format . For example (0-index 2D integer-array):

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

```

**Output:**
We output both the sum, as well as the result (and an equal sign `=`).

**Example:**
So if the input is `270 degrees` and `[[1,2],[2,3],[0,3],[1,0],[1,1]]`, the output will become:

```
517*6=3102

```

## Challenge rules:

* The inputs can be in any reasonable format. The first input can be `0-3`, `1-4`, `A-D`, `0,90,180,270`, etc. The second input can be a 0-indexed 2D array, 1-indexed 2D array, a String, list of Point-objects, etc. Your call. It's even possible to swap the x and y coordinates compared to the example inputs given. **Please state which input formats you've used in your answer!**
* You are allowed to add spaces (i.e. `517 * 6 = 3102`) if you want to.
* You are allowed to add trailing zeros after the comma, to a max of three (i.e. `3102.0`/`3102.00`/`3102.000` instead of `3102` or `0.430` instead of `0.43`).
* You are not allowed to add parenthesis in the output, so `(((0.6+4)-0)/2)/4=0.575` is not a valid output.
* You are allowed to use other operand-symbols for your language. So `×` or `·` instead of `*`; or `÷` instead of `/`; etc.
* Since a calculator automatically calculates when inputting an operand, **you should ignore operator precedence!** So `10+5*3` will result in `45` (`(10+5)*3=45`), not `25` (`10+(5*3)=25`)
(i.e. `10``+``5``*` (it now displays 15 in the display) → `3``=` (it now displays the answer `45`)). Keep this in mind when using `eval` and similar functions on the resulting sum.
* There won't be any test cases for division by 0.
* There won't be any test cases with more than three decimal digits as result, so no need for rounding the result.
* There won't be any test cases where multiple operands follow each other, or where two dots follow each other.
* There won't be any test cases for negative numbers. The minus-sign (`-`) will only be used as operand, not as negative.
* There won't be any test cases for `.##` without a leading number before the comma (i.e. `2+.7` will not be a valid test case, but `2+0.7` could be).

## 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:

```
Input:   270 degrees & [[1,2],[2,3],[0,3],[1,0],[1,1]]
Output:  517*6=3102

Input:   90 degrees & [[3,1],[0,0],[0,1],[3,3],[2,0],[0,3],[0,0],[0,2],[3,0],[2,1]]
Output:  800/4+0.75=200.75

Input:   0 degrees & [[0,0],[1,0],[2,0],[3,0],[1,2],[2,1],[2,2]]
Output:  789/263=3

Input:   180 degrees & [[3,0],[1,0],[1,2],[0,0],[3,2],[0,1],[2,0],[0,3],[2,1],[0,3],[3,2]]
Output:  0.6+4-0/2/4=0.575

```

# Answer
# SOGL V0.12, ~~70~~ ~~69~~ 67 bytes

```
i⅛⁸Νο;⌡░▼Y6γj±²‘1n4n.⌡Iø,→{_≤whwιh:"/*-+”;W? )Κ; (Κ;}+}:Ƨ)(čøŗoļ=→p

```

Try it Here, or try a version which takes inputs as given in the test-cases

uses SOGLs `I` operator, which rotates the array. Then reads a string as a JavaScript array, and where an operation is used, encase previous result in parentheses, evaluates as JavaScript and then removes the parentheses.
> 4 votes

# Answer
# Dyalog APL, ~~94~~ ~~88~~ ~~86~~ 85 bytes

```
{o,'=',⍎('('\⍨+/'+-×÷'∊⍨o),'[×÷+-]'⎕R')&'⊢o←(((⌽∘⍉⍣⍺)4 4⍴'789÷456×123-00.+')⊃⍨⊂∘⊢)¨⍵}

```

Try it online!

Takes the rotations as left argument, `0-3`, and the 1-based indices as right argument, as a list of `y x` coordinates, like `(1 1)(2 3)(4 5)` etc.

This got quite messy because of the right-handed evaluation of expressions in APL.
> 3 votes

# Answer
# C (gcc), 282 ~~294~~ ~~295~~ ~~296~~ ~~300~~ ~~304~~ ~~306 310~~ bytes

All optimizations need to be turned off and only work on 32-bit GCC.

```
float r,s;k,p,l,i;g(d,x,y){int w[]={y,x,3-y,3-x,y};d=w[d+1]*4+w[d];}f(x,y,z)int**z;{for(i=0;i<=y;i++)putchar(k=i-y?"789/456*123-00.+"[g(x,z[i][0],z[i][1])]:61),57/k*k/48?p?r+=(k-48)*pow(10,p--):(r=10*r+k-48):k-46?s=l?l%2?l%5?l&4?s/r:s+r:s-r:s*r:r,r=p=0,l=k:(p=-1);printf("%.3f",s);}

```

1 byte thanks to @Orion!

Try it online!

Function prototype:

```
f(<Direction 0-3>, <Number of entries>, <a int** typed array in [N][2]>)

```

Input format (as on TIO):

```
<Direction 0~3> <Number of entries>
<Entries 0 Row> <Entries 0 Column>
<Entries 1 Row> <Entries 1 Column>
....
<Entries N Row> <Entries N Column>

```

Ungolfed version with comments:

```
float r, s;
k, p, l, i;
g(d, x, y) {
  int w[] = {
    y,
    x,
    3 - y,
    3 - x,
    y
  };
  d = w[d + 1] * 4 + w[d];
}
f(x, y, z) int **z; {
  for (i = 0; i <= y; i++)
  {
      putchar(k = i - y ?
      "789/456*123-00.+"[g(x, z[i][0], z[i][1])] : 61),     // Print character, otherwise, '='
      57 / k * k / 48 ?                                     // If the character is from '0'~'9'
        p ?                                                 // If it is after or before a dot
            r += (k - 48) * pow(10., p--)                   // +k*10^-p
        :
            (r = 10 * r + k - 48)                           // *10+k
      :
          k - 46 ?                                          // If the character is not '.', that is, an operator, + - * / =
            s = l ?                                         // Calculate the result of previous step (if exist)
                    l % 2 ?                                 // If + - /
                        l % 5 ?                             // If + /
                            l & 4 ?
                                s / r
                            :
                                s + r
                        :
                            s - r
                    :
                        s * r
                 :
                    r,
                    r = p = 0, l = k                        // Reset all bits
          :
            (p = -1);                                       // Reverse the dot bit
  }
  printf("%.3f", s);
}

```

The code can handle cases such as `1+.7` or `-8*4`.

Very sad C doesn't have an `eval` .
> 3 votes

# Answer
## JavaScript (ES6), ~~162~~ ~~160~~ 157 bytes

Takes input as orientation `o` and array of **(y,x)** coordinates `a` in currying syntax `(o)(a)`.

The orientation is an integer in **\[0..3\]**:

* **0** = 0°
* **1** = 90° clockwise
* **2** = 180° clockwise
* **3** = 270° clockwise

```
o=>a=>(s=a.map(([y,x])=>'789/456*123-00.+'[[p=y*4+x,12+(y-=x*4),15-p,3-y][o]]).join``)+'='+eval([...x=`0)+${s}`.split(/(.[\d.]+)/)].fill`(`.join``+x.join`)`)

```

### Test cases

```
let f =

o=>a=>(s=a.map(([y,x])=>'789/456*123-00.+'[[p=y*4+x,12+(y-=x*4),15-p,3-y][o]]).join``)+'='+eval([...x=`0)+${s}`.split(/(.[\d.]+)/)].fill`(`.join``+x.join`)`)

console.log(f(3)([[2,1],[3,2],[3,0],[0,1],[1,1]])) // 517*6=3102
console.log(f(1)([[1,3],[0,0],[1,0],[3,3],[0,2],[3,0],[0,0],[2,0],[0,3],[1,2]])) // 800/4+0.75=200.75
console.log(f(0)([[0,0],[0,1],[0,2],[0,3],[2,1],[1,2],[2,2]])) // 789/263=3
console.log(f(2)([[0,3],[0,1],[2,1],[0,0],[2,3],[1,0],[0,2],[3,0],[1,2],[3,0],[2,3]])) // 0.6+4-0/2/4=0.575
```
> 2 votes

# Answer
# Ruby, ~~135 133~~ 132 bytes

```
->r,c{a="";c.map{|x,y|a=((w="789/456*123-00.+"[[y*4+x,12-x*4+y,15-y*4-x,x*4+3-y][r]])=~/[0-9.]/?a:"#{eval a}")+w;w}*""+"=#{eval a}"}

```

Try it online!

Orientation as integer: 0 for 0°, 1 for 90° and so on.
> 2 votes

# Answer
# Python 3, ~~235~~ ~~234~~ 230 bytes

Bit ugly but it works for all the test cases except the first, which doesn't seem to match the example calculator. I take the rotation as 0-3 (0-270) and multiply by 16 to offset.

`eval()` is a built-in which attempts to compile strings as code and handles converting the text symbols to operators.

```
import re
def f(r,c,J=''.join):
 b='789/456*123-00.+01470258.369+-*/+.00-321*654/987/*-+963.85207410'
 s=t=J([b[r*16+x*4+y]for y,x in c]);t=re.split('([\+\-\/\*])',s)
 while len(t)>2:t=[str(eval(J(t[0:3])))]+t[3:]
 print(s+'='+t[0])

```

Alternate method, it turned out a little bit longer but I really like this SO tip for rotating the array.

```
import re
def f(r,c):
 L=list;b=L(map(L,['789/','456*','123-','00.+']))
 while r:b=L(zip(*b[::-1]));r-=1
 s=''.join([b[x][y]for y,x in c]);t=re.split('([\+\-\/\*])',s)
 while len(t)>2:t=[str(eval(''.join(t[0:3])))]+t[3:]
 print(s+'='+t[0])

```
> 1 votes

# Answer
# Java 10, ~~418~~ ~~380~~ 378 bytes

```
d->a->{String r="",g=d>2?"/*-+963.85207410":d>1?"+.00-321*654/987":d>0?"01470258.369+-*/":"789/456*123-00.+",n[],o[];for(var i:a)r+=g.charAt(i[1]*4+i[0]);n=r.split("[-/\\+\\*]");o=r.split("[[0-9]\\.]");float s=new Float(n[0]),t;for(int i=1,O,j=0;++j<o.length;O=o[j].isEmpty()?99:o[j].charAt(0),s=O<43?s*t:O<44?s+t:O<46?s-t:O<48?s/t:s,i+=1-O/99)t=new Float(n[i]);return r+"="+s;}

```

Decided to answer my own question as well. I'm sure it can be golfed some more by using a different approach.
Input as `int` (`0-3`) and `int[][]` (0-indexed / the same as in the challenge description). Output as `float` with leading `.0` if the result is an integer instead of decimal number.

-2 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
d->a->{                       // Method with int & 2D int-array parameters and String return
  String r="",                //  Result-String, starting empty
    g=d>2?                    //  If the input is 3:
       "/*-+963.85207410"     //   Use 270 degree rotated String
      :d>1?                   //  Else if it's 2:
       "+.00-321*654/987"     //   Use 180 degree rotated String
      :d>0?                   //  Else if it's 1:
       "01470258.369+-*/"     //   Use 90 degree rotated String
      :                       //  Else (it's 0):
       "789/456*123-00.+",    //   Use default String
    n[],o[];                  //  Two temp String-arrays
  for(var i:a)                //  Loop over the coordinates:
    r+=g.charAt(i[1]*4+i[0]); //   Append the result-String with the next char
  n=r.split("[-/\\+\\*]");    //  String-array of all numbers
  o=r.split("[[0-9]\\.]");    //  String-array of all operands (including empty values unfortunately)
  float s=new Float(n[0]),    //  Start the sum at the first number
        t;                    //  A temp decimal
  for(int i=0,                //  Index-integer `i`, starting at 0
      O,                      //  A temp integer
      j=0;++j<o.length        //  Loop `j` over the operands
      ;                       //    After every iteration:
       O=o[j].isEmpty()?      //     If the current operand is an empty String
          99                  //      Set `O` to 99
         :                    //     Else:
          o[j].charAt(0),     //      Set it to the current operand character
       s=O<43?                //     If the operand is '*':
          s*t                 //      Multiply the sum with the next number
         :O<44?               //     Else-if the operand is '+':
          s+t                 //      Add the next number to the sum
         :O<46?               //     Else-if the operand is '-':
          s-t                 //      Subtract the next number from the sum
         :O<48?               //     Else-if the operand is '/':
          s/t                 //      Divide the sum by the next number
         :                    //     Else (the operand is empty):
          s,                  //      Leave the sum the same
       i+=1-O/99)             //     Increase `i` if we've encountered a non-empty operand
    t=new Float(n[i]);        //   Set `t`  to the next number in line
  return r+"="+s;}            //  Return the sum + sum-result

```
> 1 votes

# Answer
# PHP, ~~267~~ ~~235~~ ~~229~~ ~~225~~ ~~221~~ 213 bytes

```
<?php $t=[1,12,15,4,1];$j=$t[$k=$argv[1]];($o=$i=$t[$k+1])<5&&$o--;foreach(json_decode($argv[2])as$c){echo$s='/*-+963.85207410'[($c[0]*$i+$c[1]*$j+$o)%16];strpos(' /*-+',$s)&&$e="($e)";$e.=$s;}eval("echo'=',$e;");

```

Try it online!

6 bytes thanks to @Kevin Cruijssen.

Input directions are: 0 is 0, 1 is 90, 2 is 180 and 3 is 270 degrees.

## Ungolfed

The rotation is tricky, my idea is to re-map the symbols depending on orientation. The re-mapping is done by multiplying the x and y coordinates by different amounts and offsetting the result. So, there is a triple per orientation (stored in $rot). There is probably a better way, but I can't think of it at the moment!

```
$coords = json_decode($argv[2]);
$symbols = '789/456*123-00.+';
$r=$argv[1];
$rot = [1,4,0,12,1,12,15,12,15,4,15,3];
list($xs,$ys,$o)=array_slice($rot,$r*3,3);

$expression='';

foreach($coords as $coord) {
    $symbol=$symbols[($coord[0]*$xs+$coord[1]*$ys+$o)%16];

    if (!is_numeric($symbol) && $symbol!='.') {
        $expression = "($expression)";
    }
    $expression .=$symbol;
    echo $symbol;
}

eval ("echo '='.($expression);");

?>

```
> 1 votes

# Answer
# 05AB1E, ~~57~~ 54 bytes

```
εžm3ôí…/*-ø"00.+"ª€SIFøí}yθèyнè}JD'=s.γžh'.«så}R2ôR».VJ

```

Uses 0-based coordinates similar as the challenge description, and `[0,1,2,3]` for `[0,90,180,270]` respectively as inputs.

Try it online or verify all test cases.

**Explanation:**

```
ε                    # Map over each of the (implicit) input-coordinates:
 žm                  #  Push builtin "9876543210"
   3ô                #  Split it into parts of size 3: [987,654,321,0]
     í               #  Reverse each inner item: [789,456,123,0]
      …/*-           #  Push string "/*-"
          ø          #  Zip the lists together: [["789","/"],["456","*"],["123","-"]]
           "00.+"ª   #  Append string "00.+": [["789","/"],["456","*"],["123","-"],"00.+"]
                  €S #  Convert each inner item to a flattened list of characters
                     #   [[7,8,9,"/"],[4,5,6,"*"],[1,2,3,"-"],[0,0,".","+"]]
 IF                  #  Loop the input-integer amount of times:
   ø                 #   Zip/transpose the character-matrix; swapping rows/columns
    í                #   And then reverse each inner row
 }                   #  Close the loop (we now have our rotated character matrix)
  yθèyнè             #  Index the current coordinate into this matrix to get the character
}J                   # After the map: join all characters together to a single string
  D                  # Duplicate the string
   '=               '# Push string "="
     s               # Swap to get the duplicated string again
      .γ             # Group it by (without changing the order):
        žh           #  Push builtin "0123456789"
          1/         #  Divide it by 1, so it'll become a float with ".0": "0123456789.0"
                     #  (1 byte shorter than simply appending a "." with `'.«`)
            så       #  And check if this string contains the current character
       }             # Close the group-by, which has separating the operators and numbers
                     #  i.e. "800/4+0.75" → ["800","/","4","+","0.75"]
        R            # Reverse this list
                     #  i.e. ["0.75","+","4","/","800"]
         2ô          # Split it into parts of size 2
                     #  i.e. [["0.75","+"],["4","/"],["800"]]
           R         # Reverse the list again
                     #  i.e. [["800"],["4","/"],["0.75","+"]]
            »        # Join each inner list by spaces, and then those strings by newlines
                     #  i.e. "800\n4 /\n0.75 +"
             .V      # Execute this string as 05AB1E code
               J     # Join this with the earlier string and "=" on the stack
                     # (after which the result is output implicitly)

```
> 0 votes

# Answer
# Burlesque, 122 bytes

```
pe'1'9r@3co{".-"".*""./"}z[)FL{'0'0'.".+"}+]j{{}{tp}{)<-<-}{tp)<-}}j!!e!<-Ppra{pPj<-d!}msJ'=_+j{><}gB3co{rtp^}mwpe?+'.;;++

```

Try it online!

Takes args as: `"[[1,2],[2,3],[0,3],[1,0],[1,1]]" 3`

```
pe                  # Push args to stack
'1'9r@              # Range of characters [1,9]
3co                 # Split into chunks of 3
{".-" ".*" "./"}z[  # Zip in the operators
)FL                 # Flatten the resulting list (giving us the first 3 rows)
{'0 '0 '. ".+"}+]   # Add the 4th row
j                   # Swap rotation index to top of stack
{
 {}                 # NOP
 {tp}               # Transpose
 {)<- <-}           # Reverse each column and row
 {tp )<-}           # Transpose and reverse each row
}
j!!e!               # Select which based on rotation spec and eval
<-                  # Reverse the result
Pp                  # Push to hidden stack
ra                  # Read the coords as array
{
 pP                 # Pop from hidden stack
 j<-                # Reverse the coords (tp'd out)
 d!                 # Select this element
}ms                 # For each coord and accumulate result as string
J                   # Duplicate said string
'=_+j               # Put the equals at the end of the other string
{><}gB              # Group by whether digits
3co                 # Split into chunks of 3
{
 rt                 # rotate (putting op in post-fix position)
 p^                 # Ungroup
}mw                 # Map intercalating spaces
pe                  # Evaluate the result
?+                  # Combine the results
'.;;++              # Change .* ./ etc to * /

```
> 0 votes

---
Tags: code-golf, number, arithmetic, integer
---


title: Creating a HQ9+ interpreter

text:
# Question
Title: Creating a HQ9+ interpreter
The goal of this code golf is to create an interpreter for the programming language HQ9+
There are 4 commands in this programming language:

* **H** \- prints "Hello, world!"
* **Q** \- prints the source code of the program
* **9** \- prints the lyrics of the song "99 bottles of beer"
* **+** \- increments the accumulator

The rules:

1. Because the accumulator isn't defined, you can ignore the command **+**
2. Your program should prompt for input (this input will be the source code) or the source code is read from a file
3. You are not allowed to put the lyrics of "99 bottles of beer" in a file, and read the text from the file
4. You are not allowed to use a compression algorithm such as GZip or BZip to compress the song text: you have to create your own compression algorithm. This doesn't have to be a complex algorithm, but try to compress the text as much as possible (remember: this is a code-golf, the code with the fewest bytes wins)
5. If the source code contains a char that isn't **H**, **Q**, **9** or **+**, then output "Source code contains invalid characters" **before running any commands!** This means that, if the source code is `H1` for example, then don't output `Hello, world!` before you output `Source code contains invalid characters`. No, immediately output `Source code contains invalid characters`
6. If your interpreter accepts both uppercase and lowercase characters, then you get **-8** to your character count

Good luck!

# Answer
## APL (Dyalog) (326 - 8 = 318)

Paste it in an editor window and call `H`. Input is taken from the keyboard.

```
H
⎕←'Source code contains invalid characters'/⍨~∧/'HhQq9+'∊⍨V←⍞
B←' of beer'
W←' on the wall'
L←⎕TC[2]
Z←{k←' bottle','s'/⍨⍵≠1⋄⍵<0:'99',k⋄⍵=0:'No',k⋄k,⍨⍕⍵}
{⍵∊'Hh':⎕←'Hello, world!'
⍵∊'Qq':⎕←V
⍵∊'9':{⎕←G,K,(G←Z⍵),B,L,(⊃'Go to the store and buy some more' 'Take one down and pass it around'[1+×⍵]),L,(Z⍵-1),K←B,W,L}¨1-⍨⌽⍳100}¨V

```
> 16 votes

# Answer
# C, 599 587 487 481 467 characters

I'm sure this can be beaten. I'm using C after all. There's a reason you don't see a lot of winning golf entries written in C. This is now 467 characters thanks to criminal abuse of `#define`.

Specify the HQ9+ source file as a command line argument.

EDIT: Now accepts the source from stdin, not a file. Start the program, start typing the code, `CTRL``C` when done to run it.

It compiles at least in MinGW/GCC with: `gcc -o hq9+.exe hq9+.c`

Should work in MSVC, but I didn't feel like creating a whole solution just for this. :)

```
#define B "bottles of beer"
#define C case
#define P printf
#define R break
a,i,j,s;
main(){
char p[9999],c;
for(;;) {
    switch(c=getch()){
    C 'H':C 'Q':C '9':C '+': C 3: R;
    default:P("Source code contains invalid characters\n");
    }
    if (c==3) R;
    p[s++]=c;
}
for(i=0;i<s;i++){
    c = p[i];
    switch(c){
    C 'H':
        P("Hello world!");
        R;
    C 'Q':
        for(j=0;j<s;j++)putchar(p[j]);
        R;
    C '9':
        j=99;
        while(j){
            P("%d "B" on the wall,\n%d "B".\nTake one down, pass it around,\n%d "B".\n",j,j,j-1);
            j--;
        }
        R;
    C '+':
        a++;
    }
}
}

```

Or:

```
#define B "bottles of beer"
#define C case
#define P printf
#define R break
a,i,j,s;main(){char p[9999],c;for(;;){switch(c=getch()){C 'H':C 'Q':C '9':C '+': C 3: R;default:P("Source code contains invalid characters\n");}if (c==3) R;p[s++]=c;}for(i=0;i<s;i++){c = p[i];switch(c){C 'H':P("Hello world!");R;C 'Q':for(j=0;j<s;j++)putchar(p[j]);R;C '9':j=99;while(j){P("%d "B" on the wall,\n%d "B".\nTake one down, pass it around,\n%d "B".\n",j,j,j-1);j--;}R;C '+':a++;}}}

```
> 7 votes

# Answer
# Mathematica, ~~349 346~~ 341 chars

```
h = If[StringMatchQ[#, ("H" | "Q" | "9" | "+") ...],
   b = If[# > 0, ToString@#, "No"] <> " bottle" <>
      If[# == 1, "", "s"] <> " of beer" &;
   w = b@# <> " on the wall" &;
   Print /@
    StringCases[#, {"H" -> "Hello, world!", "Q" -> #,
      "9" -> "" <>
        Table[w@n <> ",\n" <> b@n <>
          ".\ntake one down, pass it around,\n" <> w[n - 1] <>
          If[n == 1, ".", ".\n\n"], {n, 99, 1, -1}]}];,
   "Source code contains invalid characters"] &

```
> 6 votes

# Answer
# Fortran 528 ~~470~~ ~~481~~

~~It requires compiling with `-fpp` flag (+3 to score)1 to use preprocessing directives (which saves way more than 3 chars, so I'm totally okay with that). It is also case insensitive, so there's -8 :D. *Saved 5 chars by not preprocessing the `endif` as that is used once anyway*.~~

Requires the file to have a `.F90` extension (makes sense to call it `hq9+.F90`) so that the compiler forces preprocessing. The code is case-sensitive; making it case-insensitive adds something like 16 characters, so it's not really worth it to save 8 characters. My previous answer did not account for the changing plurals in `bottles` for `9`; this version corrects it (and sadly adds a lot more characters).

```
#define P print*,
#define W " of beer on the wall"
#define N print'(x,i0,a,a)',
#define e enddo
#define S case
#define J len(trim(c))
character(len=99)::c,b=" bottles";read*,c;do i=1,J;if(all(c(i:i)/=["H","Q",'9',"+"])) then;P"Source code contains invalid characters";exit;endif;e;do i=1,J;select S(c(i:i));S("H");P"Hello, world!";S("Q");P c;S("9");l=8;do k=99,1,-1;N k,b(1:l),W;N k,b(1:l)," of beer";P "Take one down, pass it around";if(k==2)l=l-1;if(k==1)exit;N k-1,b(1:l),W;P"";e;P"No more",trim(b),W;S default;endselect;e;end

```

Looks a lot better ungolfed & non-preprocessed (probably because you can see what's going on):

```
program hq9
   character(len=99)::c,b=" bottles"
   read*,c
   do i=1,len(trim(c))
! change the below to ["H","h","Q","q","9","+"] to be case-insensitive
      if(all(c(i:i)/=["H","Q","9","+"]))then
         print*,"Source code contains invalid characters"
         exit
      endif
   enddo
   do i=1,len(trim(c))
      select case(c(i:i))
        case("H")                ! change to case("H","h") for case-insensitive
           print*,"Hello, world!"
        case("Q")                ! change to case("Q","q") for case-insensitive
           print*, c
        case("9")
           l=8
           do k=99,1,-1
              print'(x,i0,a,a)', k,b(1:l)," of beer on the wall"
              print'(x,i0,a)', k,b(1:l)," of beer"
              print*,"Take one down, pass it around"
              if(k==2) l=l-1
              if(k==1) exit
              print'(x,i0,a)', k-1,b(1:l)," of beer on the wall"
              print*,""
           enddo
           print*,"No more",trim(b)," of beer on the wall"
        case default
           ! do nothing
      endselect
   enddo
end program hq9

```
> 3 votes

# Answer
# Python 2, ~~452~~ ~~453~~ 443 bytes

```
q=raw_input()
if set(q)-set('HQ9+'):print'Source code contains invalid characters'
b=' bottles of beer'
b=[b,b.replace('s','')]
w=[a+' on the wall'for a in b]
t='Take one down, pass it around,\n'
c={'H':'Hello, world!','Q':q,'9':''.join(`i`+w[i<2]+',\n'+`i`+b[i<2]+'.\n'+t+(`i`if i>1 else'No')+w[0]+'.\n'for i in range(1,100)[::-1])+'No'+w[0]+',\nNo'+b[0]+'.\n'+'Go to the store, buy some more,\n99'+w[0]+'.'}
for d in q:
 if d in c:print c[d]

```

Try it online!

Bleh. It was already bleh, but then I discovered a bug that cost me a byte to fix. Bleh.

Saved some characters by not exiting on invalid input like I thought you were supposed to.

~~Explained version coming shortly.~~ I gave up. I barely even understand how this monstrosity works any more. If there's demand I'll give it another go but until then it's not happening.
> 3 votes

# Answer
# J - 444 bytes

I liked the number, so stopped golfing. Here 'ya go, single expression function!

```
f=:'Source code contains invalid characters'"_`('Hello, world!'"_`[`((((s=:(<:@[s],L,(v,LF,'Take one down and pass it around, '"_,b@<:,' of beer on the wall.'"_)@[,''"_)`(],(L=:LF,LF),(v=:1&b,' of beer on the wall, '"_,b,' of beer.'"_)@[)@.([<1:))''"_),LF,'Go to the store and buy some more, '"_,(b=:({&'Nn'@([=0:),'o more'"_)`(":@])@.(]>0:),{.&' bottles'@(8:-=&1@])),' of beer on the wall.'"_)@(99"_))`]@.('HQ9+'&i.@])"0 1 0])@.(*./@e.&'HQ9+')

```

Examples:

```
   hq9 '9QHHQ+'
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

...

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
9QHHQ+
Hello, world!
Hello, world!
9QHHQ+
+
   hq9 '9QHHaQ'
Source code contains invalid characters

```
> 3 votes

# Answer
# Perl, 325 - 8 = 317

```
sub p{print@_}$_=<>;$a=' on the wall';$b=' bottle';$e=' of beer';$c='Take one down, pass it around';if(!/^[hqHQ9+]+$/){p"Source code contains invalid characters";exit}$k=$_;for(/./g){/H|h/&&p"Hello, World!";if(/9/){$i=99;$d=$b."s$e";while($i>0){p"$i$d$a
$i$d
$c
";$q=--$i==1?'':'s';$d="$b$q$e";$i||=No;p"$i$d$a
"}}/Q|q/&&p$k}

```

Expanded:

```
sub p{print@_}
$_=<>;
$a=' on the wall';
$b=' bottle';
$e=' of beer';
$c='Take one down, pass it around';
if(!/^[hqHQ9+]+$/){
    p"Source code contains invalid characters";
    exit
}
$k=$_;
for(/./g){
    /H|h/&&p"Hello, World!";
    if(/9/){
        $i=99;
        $d=$b."s$e";
        while($i>0){
            p"$i$d$a
$i$d
$c
";
            $q=--$i==1?'':'s';
            $d="$b$q$e";
            $i||=No;
            p"$i$d$a
"
        }
    }
    /Q|q/&&p$k
}

```
> 3 votes

# Answer
# Ruby, ~~364~~ 360 - 8 = 352

Still has *lots* of room for improvement. 99 bottles code stolen from here.

```
p=gets.upcase
if p=~/[^HQ9+
]/
puts"Source code contains invalid characters"else
p.each_char{|x|case x
when ?H
puts"Hello, world!"
when ?Q
puts p
when ?9
def c;"#{$n} bottle#{'s'if$n>1} of beer on the wall"end
($n=99).times{puts"#{c}, #{c[0..-13]}.
#{$n<2?"Go to the store and buy some more":"Take one down and pass it around"}, #{$n=($n-2)%99+1;c}.

"}end}end

```
> 2 votes

# Answer
# Python 2, 340 - 8 = 332

```
s,o=raw_input(),''
for z in s:
 if z in'Hh':o+='Hello World!'
 elif z in'Qq':o+=s
 elif'9'==z:
  i=298
  while~-i:print i/3or 99,'bottle'+'s of beer on the wall.\n'[2<i<6:9+i%3*12]+'..\nGToa kteo  otnhee  dsotwonr,e ,p absusy  isto maer omuonrde,,'[(i>3)+i%3*68::2];i-=1
 elif'+'!=z:o='Source code contains invalid characters';break
print o

```
> 2 votes

# Answer
# Haskell, 298

```
main=interact g
g s|all(`elem`"HQ9+")s=s>>=(%s)|0<1="Source code contains invalid characters"
'H'%_="hello World!"
'Q'%s=s
'9'%_=drop 32$d 99
_%_=""
k=" bottles of beer on the wall"
d 0="No more"++k++"."
d n|a<-shows n k=[a,".\n\n",a,",\n",take 18a,".\ntake one down, pass it around\n",d$n-1]>>=id

```

this is quite straightforward. `%` returns a command's output (given the source cod for use on `Q`). `d` returns the 99 bottles song with a junk line at the start for golfing reasons. everything is wrapped in an interact (you might want to use `g` instead of `main` when testing)
> 2 votes

# Answer
# Tcl, 515

```
set d [read stdin]
if {![regexp {^[hq9\+HQ]*$} $d]} {puts "Source code contains invalid characters"}
lmap c [split $d {}] {set b { bottles of beer}
switch -- $c H {puts "Hello, world"} Q {puts $d} 9 {for {set i 99} {$i>2} {incr i -1} {puts "$i$b on the wall,
$i$b.
Take one down, pass it around,
[expr $i-1]$b on the wall.
"}
puts "2$b on the wall,
2$b.
Take one down, pass it around,
1 bottle of beer on the wall.

1 bottle of beer on the wall,
1 bottle of beer.
Take one down, pass it around,
No$b on the wall."}}

```

Just a bit golfed, still smaller than C and the correct 99 Bottles of beer end verse.
> 1 votes

# Answer
## JavaScript (ES6), 385

```
s=>{n=99,b=' bottle',j=' of beer',d=' on the wall',e='Take one down, pass it around',k='Go to the store, buy some more',l='No',o='s',f=', ';for(i=s.split(m=v='');~n;)v+=[n||l,b,n-1?o:m,j,d,f,n||l,b,n-1?o:m,j,f,n?e:k,f,--n<1?99:n,b,n-1?o:m,j,d,'! '].join(m);return s.match(/[^HQ9\+]/,r='')?'Source code contains invalid characters':[...s].map(c=>({H:'Hello World!',9:v,Q:s})[c]).join``}

```

Didn't opt for the case-insensitive, would have cost too many characters. Not even close to some of the other entries, but was fun nonetheless!

## JavaScript, 344

I made a version with a less complete version of the song:

```
(function(i){if(s.match(/[^HQ9\+]/)){m='Source code contains invalid characters'}else{n=99,b=' bottles of beer ',d='on the wall',e='take one down, pass it around',f=', ';for(;n;)v+=[n,b,d,f,n,b,f,e,f,--n||'no more',b,d,'! '].join(m);h={H:'Hello World!',Q:arguments.callee+m,9:v};for(;c=i[n++];)m+=h[c]||''}alert(m)})((s=prompt()).split(m=v=''))

```

but after seeing the other entries (and looking at the actual lyrics, who knew!), I thought it was a bit of a cop out!
> 1 votes

# Answer
# Julia, 362

```
s = chomp(readline(STDIN))
l=""
z=" of beer"
q,r,w,t=" bottles$z"," bottle$z"," on the wall.\n","take one down, pass it around,\n"
for j=99:-1:2
b="$j$q"
l*="$b$w$b.\n$t"
end
l*="1$r$(w)1$r.\n$(t)No$q$w"
p=println
all(c->c in "HQ9+", s)||p("Source code contains invalid characters")
for c in s
    c=='Q'&&p(s)
    c=='H'&&p("Hello, world!")
    c=='9'&&p(l)
end

```
> 1 votes

# Answer
# Lua 443 - 8 = 435 ~~464 - 8 = 456~~

I managed to save 21 characters by using multiple `if-end`s instead of `if-elseif-end`. I also had some extra white spaces floating around after a few `)`.

```
p=print o=" of beer"t=" on the wall"B=" bottle"b=" bottles"l=io.read("*l");g=l:lower()if g:match"[^hq9+]"then p("Source code contains invalid characters")end for i=1,#g do s=g:sub(i,i)if s=='h'then p("Hello, world")end if s=='q'then p(l)end if s=='9'then n=99 repeat p(n..b..o..t..", "..n..b..o)n=n-1 p("Take one down, pass it around, "..n..b..o..t..".")p()until n==1 p("1"..B..o..t..", 1"..B..o)p("No more"..b..o..t..", no more"..b..o)end end

```

I'm fairly happy with this one, even though it's not much shorter than my Fortran answer. The 99 bottles of beer code has been modified from this answer by Alessandro. Ungolfed, we have

```
-- reuse stuff
p=print
o=" of beer"
t=" on the wall"
B=" bottle"
b=" bottles"
-- read the line & then lowercase it for case insensitivity
l=io.read("*l");g=l:lower()
if g:match"[^hq9+]" then -- horray for basic regex
   p("Source code contains invalid characters")
end
for i=1,#g do
   s=g:sub(i,i)               -- take substring
   if s=='h' then p("Hello, world") end
   if s=='q' then p(l) end
   if s=='9' then
      n=99
      repeat
         p(n..b..o..t..", "..n..b..o)
         n=n-1
         p("Take one down, pass it around, "..n..b..o..t..".")
         p()
      until n==1
      p("1"..B..o..t..", 1"..B..o)
      p("No more"..b..o..t..", no more"..b..o)
   end
end

```
> 1 votes

# Answer
## Java, 546 bytes

This is my first code golf submission. I am sure we could do more with it. It reads the input as the command line argument. Beer code "borrowed" from "99 Bottles of Beer" java answer (creative commons)

```
class a{public static void main(String[] a){if(a[0].matches("^[HQ9\\Q+\\E]+$")){for(char c:a[0].toCharArray()){if(c=='H')p("Hello, world!");if(c=='Q')p(a[0]);if(c=='9')b();}}else{System.out.println("Source code contains invalid characters");}}static void p(String s){System.out.println(s);}static void b(){String b=" of beer",c=" on the wall",n=".\n",s;for(int i=100;i-->1;){s=" bottle"+(i>1?"s":"");p(i+s+b+c+", "+i+s+b+n+(i<2?"Go to the store and buy some more, 99":"Take one down and pass it around, "+(i-1))+" bottle"+(i!=2?"s":"")+b+c+n);}}}

```

Let me know if command line args is not acceptable. This was a lot of fun!
> 1 votes

# Answer
# C, 562 bytes

```
char*c="%1d %3$s of %4$s on the %5$s, %1d %3$s of %4$s.\n\0Take one down and pass it around, %2d %3$s of %4$s on the %5$s.\n\0Go to the store and buy some more, %1d %3$s of %4$s on the %5$s.\n";main(int a,char**b){int x=0;for(int i=0;i<strlen(b[1]);i++){if(b[1][i]=='+')x++;else if(b[1][i]=='9'){int k=99;while(1){printf(&c[0],k,k,k==1?"bottle":"bottles","beer","wall");if(k!=1){printf(&c[49],k,k,"bottles","beer","wall");k--;}else{k=99;printf(&c[114],k,k,"bottles","beer","wall");break;}}}else printf("%s",b[1][i]=='H'?"Hello, world!":(b[1][i]=='Q'?b[1]:""));}}

```

As a full program. First argument is the HQ9+ program. With an actual accumulator. I challanged myself not to use define statements.

Ungolfed version:

```
char* c = "%1d %3$s of %4$s on the %5$s, %1d %3$s of %4$s.\n\0Take one down and pass it around, %2d %3$s of %4$s on the %5$s.\n\0Go to the store and buy some more, %1d %3$s of %4$s on the %5$s.\n";
main (int a, char** b) {
    int x = 0;
    for (int i = 0; i < strlen(b[1]); i++) {
        if (b[1][i] == '+')
            x++;
        else if (b[1][i] == '9') {
            int k = 99;
            while (1) {
                printf(&c[0], k, k, k == 1 ? "bottle" : "bottles", "beer", "wall");
                if (k != 1) {
                    printf(&c[49], k, k, "bottles", "beer", "wall");
                    k--;
                } else {
                    k=99;
                    printf(&c[114], k, k, "bottles", "beer", "wall");
                    break;
                }
            }
        } else
            printf("%s",b[1][i] == 'H' ? "Hello, world!" : (b[1][i] == 'Q' ? b[1] : ""));
    }
}

```
> 1 votes

# Answer
## GNU C, ~~429~~ 423 bytes

Compiles and runs correctly on GCC-8.3, without any compiler flags. No other configuration was tested.

It considers a file to be a stream of text up to the first `'\n'` that it encounters (this just makes testing easier, can be fixed by replacing the `10` in `(c=getchar())!=10` with a `-1`). However, keep in mind that newlines will not be considered valid.

```
char*b="bottles of beer\0on the wall\0Take one down, pass it around",s[4096];n;Q(){puts(s);}W(){puts("Hello, world!");}B(){for(n=100;--n;){printf("%d %s %s,\n%d %s.\n%s,\n%d %s %s.\n\n",n,b,b+16,n,b,b+28,n-1,b,b+16);}}N(){}l=0,c,i,(*t[])()={[43]=N,[57]=B,[72]=W,[81]=Q};main(){while((c=getchar())!=10){if(c!=43&&c!=57&&c!=72&&c!=81){exit(puts("Source code contains invalid characters"));}s[l++]=c;}for(;i<l;++i)t[s[i]]();}

```

## Degolfed

```
// we stick all the strings in a single string, null separated.
// We will later index into the right indices to print the right pieces.
char*b="bottles of beer\0on the wall\0Take one down, pass it around";

// Here we store the source code. I chose 4kiB, but this was rather arbitrary.
char s[4096];

// n is the counter for the B function
n;

Q() { // Q for quine
    // puts is shorter than printf and it prints a newline for free
    puts(s);
}

W() { // W for world
    puts("Hello, world!");
}

B() { // B for bottles
    // n is the current count
    for (n = 100; --n;) {
        printf("%d %s %s,\n"    // n bottles of beer on the wall,
               "%d %s.\n"       // n bottles of beer.
               "%s,\n"          // Take one down, pass it around,
               "%d %s %s.\n\n", // n-1 bottles of beer on the wall

               n, b, b + 16, // Index into the right positions
               n, b,         // in the string.
               b + 28, n - 1, b, b + 16);
    }
}

N() {} // N for nothing, we need it for the table

// l is the length of source code
// c is the currently read character
// i is an index
l = 0, c, i;

// This array of function pointers is a bit like a jump table.
// This table tells us which function to call depending on the current char.
// It is essentially a hand-rolled switch statement, but shorter.
// NOTE: the [index]=value syntax is a GNU extension
int(*t[])()={
    [43/* ASCII + */] = N, // do nothing
    [57/* ASCII 9 */] = B, // print 99 bottles
    [72/* ASCII H */] = W, // print hello world
    [81/* ASCII Q */] = Q  // print source
};

main() {
    // consume input until we hit \n. this
    while ((c = getchar()) != 10) {
        // if we find a character not in "HQ9+", we log and exit
        if (c != 43 && c != 57 && c != 72 && c != 81) {
            exit(puts("Source code contains invalid characters"));
        }
        // populate the source code
        s[l++] = c;
    }

    // go over the source code (at this point validated)
    // and call the function that is set in the table
    // We can skip initializing i because it is a static, and statics
    // get implicitly initialized to 0. this saves 3 bytes
    for (; i < l; ++i)
        t[s[i]]();
}

```

I will admit I cheated a bit with the 99 bottles.
> 1 votes

# Answer
# Excel VBA, 489 Bytes

Unindented:

```
Sub h(s)
For c=1 To Len(s)
Select Case Mid(s,c,1)
Case "H"
Debug.? "Hello,World!"
Case "Q"
Set v=ActiveWorkbook.VBProject.VBComponents("M").CodeModule:For n=1 To v.countoflines:Debug.? v.Lines(n,1):Next
Case "+"
a=a+1
Case "9"
s=" Bottles of Beer":o=" Bottle of Beer":w=" on the wall":t=". Take 1 down pass it around,":p=",":d=".":For n=99 To 3 Step -1:Debug.? n;s;w;p;n;s;t;n-1;s;w;d:Next:Debug.? 2;s;w;p;2;s;t;1;o;w;d:Debug.? 1;o;w;p;1;o;t;"No";s;w;d
End Select
Next
End Sub

```

---

(indented for readability)

```
Sub h(s)
For c=1 To Len(s)
Select Case Mid(s,c,1)
    Case "H"
        Debug.? "Hello,World!"
    Case "Q"
        Set v=ActiveWorkbook.VBProject.VBComponents("M").CodeModule
        For n=1 To v.countoflines
            Debug.? v.Lines(n,1)
        Next
    Case "+"
        a=a+1
    Case "9"
        s=" Bottles of Beer"
        o=" Bottle of Beer"
        w=" on the wall"
        t=". Take 1 down pass it around,"
        p=","
        d="."
        For n=99 To 3 Step -1
            Debug.? n;s;w;p;n;s;t;n-1;s;w;d
        Next
        Debug.? 2;s;w;p;2;s;t;1;o;w;d
        Debug.? 1;o;w;p;1;o;t;"No";s;w;d
End Select
Next
End Sub

```

Rename default *Module1* to *M*
call with `h "+++++++++Your Code"`
This will also work on other office applications, changing **ActiveWorkbook** to the appropriate document type
> 0 votes

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


title: Checking Word Grids

text:
# Question
Title: Checking Word Grids
**Your Task**

Given a list of words, check if they form a valid word grid. They form a valid grid if there are **N** words with **N** letters and they spell the same words vertically as they do horizontally. The words can be given in any order. `[FILE, ICED, LEAD, EDDY]` = `True` and `[FILE, LEAD, EDDY, ICED]` = `True`. Print `True` if it is valid or `False` if it is not

**Here's some more examples**

```
F I L E
I C E D
L E A D
E D D Y

O G R E
G A I A
R I G S
E A S Y

C A M P
A X E L
M E M O
P L O W

S P A S M
P A S T A
A S P E N
S T E E L
M A N L Y

```

This is code golf so lowest bytes wins

# Answer
> 7 votes
# Pyth - 10 9 bytes

The actual check is very easy, in just three bytes with `CIQ`. The permutation part takes the other 6.

```
.EmCId.pQ

```

Try it online here.

It `m`aps over the `.p`ermutations of the (`Q`) input, each time checking if the loop var(`d`) is `I`nvarient under (`C`) rotation. Then it checks if `.E`any are true.

# Answer
> 5 votes
## CJam (25 24 bytes)

```
q~e!{_z=},"True""False"?

```

Online demo. Pretty trivial apart from the specified output, because CJam doesn't have a Boolean type.

With thanks to Sp3000 for saving one stroke.

# Answer
> 4 votes
# Julia, 114 bytes

Did somebody say "super long solution"?? It just so happens that I have one for you.

```
a->(L=length(a);P(x)=reshape(split(join(x),""),L,L);print(any([P(p)==P(p)'for p=permutations(a)])?"True":"False"))

```

This creates an unnamed function that accepts an array and prints to stdout. It works by generating all permutations, turning the arrays into matrices of letters and checking whether each matrix is equal to its transpose. Unfortunately booleans are lowercase in Julia, otherwise I wouldn't have had to do the ternary.

# Answer
> 3 votes
# Haskell, 51 bytes

```
import Data.List
any((==)=<<transpose).permutations

```

Usage example: `any((==)=<<transpose).permutations $ ["LEAD","FILE","ICED","EDDY"]` -\> `True`.

How it works: check if any of the permutations equals it's transposition. Luckily Haskell's native boolean values are `True` and `False`.

# Answer
> 3 votes
# Python 2, ~~87~~ 85 Bytes

Straightforward solution using `zip()` to transpose.

*Saved two bytes on both thanks to xnor.*

```
from itertools import*
print any(zip(*c)==map(tuple,c)for c in permutations(input()))

```

**Solution without relying on imports, ~~139~~ ~~138~~ 136 Bytes**

```
p=lambda l:[[j]+k for i,j in enumerate(l)for k in p(l[:i]+l[-~i:])]if~-len(l)else[l]
print any(zip(*c)==map(tuple,c)for c in p(input()))

```

If there's a way to get around using enumerate, let me know! :)

Input for both should be formatted like so:

```
["FILE","ICED","EDDY","LEAD"]

```

---

Psst. Hey! Here's a solution in Symbolic, something I'm working on. `Ƥ(Ʌ(ʐ(*c)==ϻ(ϰ,c)ϝcϊƥ(Ί)))`

# Answer
> 3 votes
# Python 2, 74

```
s=input().split()
print all(''.join(s)[s.index(w)::len(w)]in s for w in s)

```

# Answer
> 2 votes
# Brachylog, 6 bytes

```
p⟨\=≡⟩

```

Try it online!

Assuming output can be "true." and "false." instead of "True" and "False".

If not, it's a trivial change to:

### 22 bytes

```
p⟨\=≡⟩∧"True"|∧"False"

```

Try it online!

# Answer
> 1 votes
# Mathematica (48 42 bytes)

```
Or@@(#==#&/@Characters@Permutations@#)&

```

Luckily `Transpose` can be represented by a single unicode character.

# Answer
> 1 votes
# JavaScript ES6, ~~90~~ 58 bytes

```
s=>s.every((l,i)=>s.map(p=>p[i]).join``==l)?'True':'False'

```

Old answer:

```
s=>~(n=s.split`
`).map((l,i)=>n.map(p=>p[i*2]).join` `==l).indexOf(!1)?'False':'True'

```

The newline is significant and counts as a byte.

---

ES5 Demo:
```
function t(s) {
    return ~(n=s.split('\n')).map(function(l,i){return n.map(function(p){return o=p[i*2]}).join(' ')==l}).indexOf(!1)?'False':'True'
}

// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(document.getElementById('input').value)
};
```

```
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Word Grids Snippet</h2><div><div  style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><textarea placeholder="Text here..." style="resize:none;width:70px;height:70px;border:1px solid #DDD;" id="input"></textarea><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>
```

# Answer
> 1 votes
# Ruby, 97 bytes

91 bytes if we remove `.chomp` inside `map`

```
a=gets.chomp.split','.map{|_|_.chomp.chars};p a.permutation.map{|p|p[0].zip(*p[1..-1])===p}.any?

```

# Answer
> 1 votes
# MATLAB - ~~75~~ 98 bytes

*Note:* I didn't see that you had to output `True` or `False`, so I had to create an additional cell array that stores these two choices then we choose from this array when we're done.

---

This is a rather brute-force solution. This assumes that you have loaded `A` in as a character matrix and that `A` is symmetric in size (i.e. # of rows is equal to # of columns):

```
c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

```

The overall process is to first create a 2D array of all possible permutations that goes from 1 up to as many words as we have `N`. Each row of this matrix gives you a permutation enumerated from 1 up to `N`, and we can check either the number of rows or columns for the value `N`. Next, we go through every possible permutation and rearrange the matrix `A`'s rows based on the permutation vector produced by that permutation. For example, if `N=4`, and if we had `[1,4,2,3]` as the permutation vector, it would rearrange the matrix `A` so that row 1 of the original matrix `A` appears first, followed by row 4 of the original matrix `A` appearing second, row 2 of the original matrix `A` appearing third and finally row 3 of the original matrix `A` appearing last.

The above problem is essentially checking to see that if we all of these matrix rearrangements for `A` over all possible permutations, we check to see if this rearranged matrix is equal to its transpose. In order to facilitate this, I do an element-by-element equality check of the characters, and sum over this result. If the sum is equal to the total size of the matrix, then we have a true result. This code **will check** all possible permutations, even if we have found a match before we exhaust all possibilities. The statement `o=0` is an indicator variable `o` that tells us whether we have found the condition being true or false.

Inside the loop, we keep updating `o` and checking for the above summation condition by logical ORing with the current result and with the current rearranged matrix condition. It will be set to `true` if we have found such a condition or it gets to 1, and will stay `false` if we don't, or stays at 0.

## Minor Note

The `for` loop behaviour is rather undocumented, but if you specify a **matrix** to be what is iterating over the `for` loop, each value `k` would be a **column** of the said matrix. For example, if we did:

```
B = [0 0 0 0; 1 1 1 1; 2 2 2 2; 3 3 3 3];
for k = B
    disp(k);
end

```

We would select out the first column of `B`, display it, then the next column of `B`, display it, etc... so you would get a series of `[0,1,2,3]'`s.

---

# Example Runs

```
>> A = ['FILE'; 'ICED'; 'LEAD'; 'EDDY'];
>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    True

>> A = ['FILE'; 'LEAD'; 'EDDY'; 'ICED'];
>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    True

>> A = ['OGRE'; 'GAIA'; 'RIGS'; 'EASY'];
>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    True

>> A = ['CAMP', 'AXEL', 'MEMO', 'PLOW'];
>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    True

>> A = ['SPASM', 'PASTA', 'ASPEN', 'STEEL', 'MANLY'];
>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    True

```

---

Just to be sure, here's an example of where it shouldn't work:

```
>> A = ['CBMP'; 'APEL'; 'MCTO'; 'DLOX'];
>> A

A =

CBMP
APEL
MCTO
DLOX

>> c={'False','True'};o=0;for k=perms(1:size(A,1))'o=o|sum(sum(A(k,:)==A(k,:)'))==numel(A);end,c{o+1}

ans =

    False

```

# Answer
> 0 votes
# 05AB1E, 11 bytes

```
øQi”‰¦”ë”žä

```

Try it online.

**Explanation:**

```
ø        # Zip the (implicit) input, swapping columns and rows
 Q       # Check if it is equal to the (implicit) input
         # That's it, we're done.. If it weren't for the requirement of explicitly
         # outputting the strings "True"/"False" instead of a truthy/falsey result..

i        # If the result is 1 (truthy):
 ”‰¦”    #  Output "True"
ë        # Else:
 ”žä     #  Output "False"

```

See here to understand why `”‰¦”` is `True` and `”žä` is `False`.

---

**11 bytes alternative:**

```
øQ”žä‰¦”#sè

```

Try it online.

# Answer
> 0 votes
# Java (OpenJDK 8), 134 bytes

```
a->{int b=a.length,i=0,j=0;for(;i++<b;){for(;j<b;j++){if(a[j].length()!=b||a[i].charAt(j)!=a[j].charAt(i))return false;}}return true;}

```

Try it online!

### Explanation:

```
int b=a.length,i=0,j=0;                               //Create Variables
for(;i++<b;){for(;j<b;j++){                           //Nested Loop
if(a[j].length()!=b||a[i].charAt(j)!=a[j].charAt(i))  //Is the grid valid?
    return false;                                     //if not, return false
}}
return true;                                     //if it gets this far, return true

```

# Answer
> 0 votes
# PowerShell, 93 bytes

```
param($a)"$($a|%{$n++;''+($_|% t*y|sort)}|sort)"-eq"$(0..--$n|%{''+($a|% ch* $_|sort)}|sort)"

```

Try it online!

Unrolled:

```
param($a)

$x=$a|%{
    $n++                                # number of words
    $letters = $_|% toCharArray|sort    # sorted letters of the current word $_
    ''+$letters                         # convert the letters to a string
}|sort

$y=0..--$n|%{
    $letters = $a|% chars $_|sort       # sorted letters of all words in the $_ position
    ''+$letters                         # convert the letters to a string
}|sort

Write-Output ("$x"-eq"$y")              # convert both arrays to strings, compare them and return a result

```

# Answer
> 0 votes
# Burlesque, 35 bytes

```
ln)wdr@{Jtp==}ay{"True"}{"False"}IE

```

Try it online!

Core calculation is 11 bytes. Most of the cost is in parsing the word square (5 bytes) and outputting true or false rather than 1/0 (19 bytes)

```
ln                   #Split by newlines
)wd                  #Map split by spaces
r@                   #Permutation by words
{
 Jtp==               #If the transpose is the same
}ay                  #Any
{"True"}{"False"}IE  #Print "True" or "False" accordingly

```

---
Tags: code-golf
---


# Question
Title: Average number of strings with Levenshtein distance up to 4
This is a version of this question which should not have such a straightforward solution and so should be more of an interesting coding challenge. It seems, for example, very likely there is no easy to find closed form solution, even though we have only increased the bound by one from the previous version. Having said that, you never know...

The Levenshtein distance between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one. Given a binary string \\$S\\$ of length \\$n\\$, we are a interested in the number of different strings of length \\$n\\$ which have distance at most \\$4\\$ from \\$S\\$.

For example, if \\$S = 0000\\$ there are four strings with Levenshtein distance exactly \\$3\\$ from \\$S\\$, six with distance exactly \\$2\\$, four with distance exactly \\$1\\$ and exactly one with distance \\$0\\$. This makes a total of \\$15\\$ distinct strings with distance at most \\$3\\$ from the string \\$0000\\$. The only string with distance exactly \\$4\\$ is \\$1111\\$.

For this task the input is a value of \\$n \geq 4\\$. Your code must output the average number of binary strings of length \\$n\\$ which have Levenshtein distance at most \\$4\\$ from a uniform and randomly sampled string \\$S\\$. Your answer can be output in any standard way you choose but it must be exact.

# Examples

* n = 4. Average \\$16\\$.
* n = 5. Average 31 \\$\frac{11}{16}\\$.
* n = 6. Average 61 \\$\frac{21}{32}\\$.
* n = 7. Average 116 \\$\frac{7}{8}\\$.
* n = 8. Average 214 \\$\frac{43}{128}\\$.
* n = 9. Average 378 \\$\frac{49}{246}\\$.
* n = 10. Average 640 \\$\frac{301}{512}\\$.
* n = 11. Average 1042 \\$\frac{1}{16}\\$.
* n = 12. Average 1631 \\$\frac{1345}{2048}\\$.
* n = 13. Average 2466 \\$\frac{3909}{4096}\\$.
* n = 14. Average 3614 \\$\frac{563}{8192}\\$

# Score

Your score is the highest value of \\$n\\$ you can reach in less than a minute on my linux box. If two answers get the same value then the first posted (or amended) wins. The timing is for each value separately.

My CPU is an Intel(R) Xeon(R) CPU X5460.

# Answer
# GAP

So my previous approach works indeed when we replace the definition of `nfa` with this:

```
nfa := Automaton("epsilon", 25, 5,
      [[[1,6,7],[2,8,9],[3,10,11],4,5,[6,18],
       [7,19],8,9,10,11,[8,22],[9,23],10,11,
       0,0,18,19,22,23,0,0,0,0],
      [[2,6,13],[3,8,15],[4,10,17],5,0,[8,18],
       [13,21],10,15,0,17,[6,22],[15,25],8,17,
       10,0,0,21,0,25,18,0,22,0],
      [[2,12,7],[3,14,9],[4,16,11],5,0,[12,20],
       [9,19],14,11,16,0,[14,24],[7,23],16,9,
       0,11,20,0,24,0,0,19,0,23],
      [[1,12,13],[2,14,15],[3,16,17],4,5,[14,20],
       [15,21],16,17,0,0,[12,24],[13,25],14,15,
       16,17,0,0,0,0,20,21,24,25],
      [0,0,0,0,0,3,3,4,4,5,5,3,3,4,4,5,5,10,
       11,16,17,10,11,16,17] ],
     [1], [1..25] );

```

This automaton was constructed with a program that I have explained here.

The resulting DFA has 266 states.

We can again compute as much values as we like:

```
n = 16. Average = 7150 23011/32768.
n = 17. Average = 9714 60059/65536.
n = 18. Average = 12940 42919/131072.
n = 19. Average = 16935 3985/8192.
n = 20. Average = 21817 225447/524288.
n = 21. Average = 27711 716517/1048576.
n = 22. Average = 34752 552357/2097152.
n = 23. Average = 43081 714481/1048576.
n = 24. Average = 52850 7923401/8388608.
n = 25. Average = 64219 9352665/16777216.
n = 50. Average = 1508800 387601224486599/562949953421312.
n = 100. Average = 29267070 38719469213378154341013566355/
633825300114114700748351602688.

```

The eigenvalues of the matrix are \\$4,2,1,0\\$ and \\$-1\\$ as before and additionally two conjugate pairs of complex numbers: \\$\pm i\\$, and the third root of unity and its conjugate (which is also its square and its inverse).

Usually complex eigenvalues mean that the closed formula contains trigonometric functions, but since there were already terms corresponding to the eigenvector \\$1\\$ to compensate, I took the liberty to use the periodic functions \\$ n \bmod 3\\$ and \\$ -n \bmod 3\\$ to handle the third root of unity.

The imaginary unit does not contribute to the closed formula. Neither does \\$4\\$, because it comes from the sink state, which is not counted. It can be removed from the automaton, and the resulting matrix no longer has this eigenvalue. The eigenvalue \\$-1\\$ does contribute, even though it didn't in the distance 3 case.

The resulting closed formula, which is quite long, works for \\$n\ge 5\\$. (That's an effect of the \\$0\\$ eigenvalues.) Since the challenge asks for \\$n\ge 4\\$, the following code has a special case for small values.

# Pari/GP

```
f(n)=if(n>4,168264301/345744-4115011/16464*n+19597/336*n^2-161/24*n^3+17/48*n^4+(-9188617/19208-268724/3087*n-4658/441*n^2+449/81*n^3-515/324*n^4+(-1)^n/72+(56188/194481-824/9261*n+4/3969*n^2)*(n%3)+(-1756/64827+94/27783*n-26/3969*n^2)*(-n%3))*2^-n,2^n)

```

Try it online!
> 6 votes

---
Tags: string, math, combinatorics, fastest-code
---


title: Flag Semaphore Encoder

text:
# Question
Title: Flag Semaphore Encoder
Your goal is to write a **flag semaphore encoder**, which will convert a given sentence into the corresponding flag semaphore characters, according to the semaphore system described on Wikipedia.

Assume that the input is a single sentence provided through stdin (or equivalent). Your output should be a series of semaphore characters, with each row representing one word from the sentence. You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters, but you must be able to handle both uppercase and lowercase. Your output is allowed to contain extra whitespace.

Semaphore characters must be displayed as a 3x3 square, with an `O` in the middle and the flag positions represented by the characters `| - / \`. Each semaphore character must be separated from adjacent characters by a space, and each row must be separated by a blank line. Don't worry about wrapping for words that may be too long for your display - pretend that your lines have infinite length.

**Sample input:**

```
abcdefg hijklmn opqrstu vwxyz

```

**Sample output:**

```
        \    |    /
 O  -O   O   O   O   O-  O
/|   |   |   |   |   |   |\

    \    |   |    /
-O   O   O-  O   O   O-  O
/   /       /   /   /   / \

\    |    /         \|  \ /
-O  -O  -O  -O- -O   O   O
                  \

 |    /   / \
 O   O-  O   O-  O-
  \       \       \

```

**Sample input:**

```
This is Code Golf.

```

**Sample output:**

```
\|      \
 O  -O   O  -O
    /   /     \

\
 O  -O
/     \

\   \    |    /
 O  -O   O   O
 |       |   |

    \     /
 O  -O   O   O-
 |\     /    |

```

Since this is , the shortest solution wins.

# Answer
> 6 votes
## Perl, 282 264 251 247 245 243 241 240 236 233 229 227 220 218 216 214 characters

```
$_=lc<>;map{y/a-z//cd;y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;@a=($/)x4;map{$s=ord;$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;$_.=" "for@a}split//;print@a}split

```

With some prettifying line breaks:

```
$_=lc<>;
map{
y/a-z//cd;
y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;
@a=($/)x4;
map{
$s=ord;
$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;
$_.=" "for@a
}split//;
print@a}split

```

It's taken me a while to get this working (my first attempt at a Perl answer). It's based on a similar idea to a lot of the other answers. Each flag can be in one of 8 positions, there are two flags, and the two flags can't ever be in the same position. This means I can encode the position of both flags in one byte - which also means I can translate directly from a character to its encoding using Perl's `y///` function (operator?). So:-

```
a = 01100000 96 = `
b = 01001000 72 = H
c = 01000001 65 = A
d = 01000010 66 = B
e = 01000100 68 = D
f = 01010000 80 = P
etc...

```

Therefore:

```
y/a-z/`HABDP..../;

```

I've escaped a fair few of the characters which are outside the normal used range to make the copying and pasting of the program easy - but I'm fairly sure I could write a program to replace the escape codes with the characters themselves saving me roughly 30 characters.

# Answer
> 6 votes
**Python, ~~244~~ ~~238~~ ~~233~~ 232**

```
e='abhioptuwycdjmnsqxzfgvklebr'
for w in raw_input().split():
 for i in 0,3,6,9:print' '.join(''.join((' '+'\|/-O-/|\ '[j])[`j`in'4'+'6736031025071568328578162735'[e.find(c):][:2]]for j in range(i,9)[:3])for c in w if c.lower()in e)

```

This uses a favorite trick of mine: single-track encoding. I've labeled the semaphore bits (sbits)

```
\|/     012
- -  -> 3 5
/|\     678

```

to obtain the following chart of which sbits occur for which letter:

```
0: ciotuy
1: djkptv
2: elquwx
3: bhopqrs
5: fjmrwyz
6: ahiklmn
7: abcdefg
8: gnsvxz

```

each letter occurs exactly twice in the chart, since the signalman has two arms. Then, I view this as a graph on the letters a-z, with edges between letters sharing sbits, with the edges labeled according to the shared sbit. Ideally, I'd find a Hamilton path through this graph, such that subsequent edges don't have the same label. No such paths exist... so you'll note that the variable `e` contains the letter `b` twice.

With my nearly-Hamilton path `e`, I construct an array `d` of sbit labels used in the traversal of `e`. Then, to figure out where to put her arms, the signalman need only find the desired letter in the following handy chart

```
abhioptuwycdjmnsqxzfgvklebr
6736031025071568328578162735

```

whence her arms go in the position directly below, and below&right of the letter.

# Answer
> 4 votes
### Scala, 272 characters

```
println(readLine.filter(c=>c.isLetter||c==' ').toLowerCase.split(" ").map{_.map(q=>("    O    "/:("^@a,6Tr?W*+5Sq9(2Pn%/-47MU"(q-'a')-27+""))((g,x)=>g.updated(x-'0',"\\|/-O-/|\\"(x-'0'))).grouped(3).toList).transpose.map(_.mkString(" ")).mkString("\n")}.mkString("\n\n"))

```

Ungolfed (well, less-golfed):

```
println(
  readLine.filter(c => c.isLetter || c==' ').
  toLowerCase.
  split(" ").
  map{ s =>
    val lookup = "^@a,6Tr?W*+5Sq9(2Pn%/-47MU".map(c => (c-27).toString)
    s.map(q =>
      ("    O    " /: lookup(q-'a')){(g,x) =>
        g.updated(x-'0', "\\|/-O-/|\\"(x-'0'))
      }.grouped(3).toList
    ).transpose.map(_.mkString(" ")).mkString("\n")
  }.mkString("\n\n")
)

```

# Answer
> 2 votes
### Ruby, 287 characters

```
gets.split.map{|w|puts (0..2).map{|l|w.chars.map{|c|(' '*576+'CAEAEADBCAF DAEBDACAAAI EAFADACAABG BAEAFEL A_ FACABADADAAG AAFBADQ AGX GAFADABAAAAF'.split.zip('\\|/-o-/|\\'.chars).map{|a,c|(a.chars.zip([' ',c]*9).map{|x,z|[z]*(x.ord-64)}.flatten)}.transpose*''*2)[c.ord*9+3*l,3]}*' '},''}

```

Input must be given on STDIN.

# Answer
> 1 votes
## Scala 494 without newlines  520 with newlines:

```
def k(i:Int,d:Int=0):(Int,Int)=if(i<(7-d))(d,i+1)else k(i-(7-d),d+1)
def t(i:Char)=(if(i=='y')i-4 else
if(i=='z')i+2 else
if(i=='j')i+14 else
if(i>='v')i+3 else
if(i>'i')i-1 else i)-'a'
def q(p:(Int,Int),i:Int,c:Char)=if(p._1==i||p._1+p._2==i)""+c else" "
def g(r:Int,c:Char)={val p=k(t(c.toLower))
print((r match{case 1=>q(p,3,'\\')+q(p,4,'|')+q(p,5,'/')
case 2=>q(p,2,'-')+"o"+q(p,6,'-')
case 3=>q(p,1,'/')+q(p,0,'|')+q(p,7,'\\')})+" ")}
for(w<-readLine.split(" ")){println;for(r<-(1 to 3)){w.map(c=>g(r,c));println}}

```

### ungolfed:

```
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
  if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}

def toIdx (i: Char) = {
 (if (i == 'y') i - 4  else
  if (i == 'z') i + 2  else
  if (i == 'j') i + 14 else
  if (i >= 'v') i + 3 else
  if (i > 'i') i - 1 else i ) - 'a'}

def p2c (pair: (Int, Int), i: Int, c: Char) = {
 if (pair._1 == i || pair._1 + pair._2 == i) ""+c else " "
}

def printGrid (row: Int, c: Char) = {
  val idx = toIdx (c.toLower)
  val pair = toClock (idx)
  row match {
    case 1 => { print(
      p2c (pair, 3, '\\') +
      p2c (pair, 4, '|') +
      p2c (pair, 5, '/') + " ")
    }
    case 2 => { print(
      p2c (pair, 2, '-') + "o" +
      p2c (pair, 6, '-') + " ")
    }
    case 3 => { print(
      p2c (pair, 1, '/') +
      p2c (pair, 0, '|') +
      p2c (pair, 7, '\\') + " ")
    }
  }
}

val worte = "This is Code Golf"
(1 to 3).map (row => {worte.map (c => printGrid (row, c));println})

```

### Explanation:

I observed a clock-pattern, but not with 12 hours, but 8. And Starttime is 0 is, where 6 o'clock is, and a, b, c are the first codes, with the first (one) flag on South.

Since flag 1 and 2 are indistinguishable, we can sort all combinations with the lower number for the first flag first. Unfortunately, the fine order from the beginning is disturbed, when j doesn't follow i, but k, l, m, and later it get's a mess.

Therefore I rearrange my keys for the mapping:

```
val iis = is.map {i =>
  if (i == 'y') i - 4  else
  if (i == 'z') i + 2  else
  if (i == 'j') i + 14 else
  if (i >= 'v') i + 3 else
  if (i > 'i') i - 1 else i }.map (_ - 'a')

iis.zipWithIndex .sortBy (_._1) .map (p => (p._1, ('a' + p._2).toChar))

Vector((97,a), (98, b), (99, c), (100,d), (101,e), (102,f), (103,g),
      (104,h), (105,i), (106,k), (107,l), (108,m), (109,n),
      (110,o), (111,p), (112,q), (113,r), (114,s),
      (115,t), (116,u), (117,y), -------
      -------  (120,j), (121,v),
      (122,w), (123,x),
      (124,z))

```

If we substract 'a' from every character, we get the numbers from (0 to 7+6+5+...+1). We can map the numbers of a character-grid

```
3 4 5   \ | /            |
2   6   - o -    - o   - o
1 0 7   / | \    (2, ) (2,2)

```

A pair of two numbers can map two flags, where the first number is the index of 0 to 6 for the first flag, and the second flag isn't a number from 1 to 7 for the second flag, but for the distance from the first to the second flag. (2,2) would mean, the first flag is to WEST, and the second is two steps clockwise from there, to the NORTH.

```
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
  if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}

Vector( (0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7),
    (1,1), (1,2), (1,3), (1,4), (1,5), (1,6),
    (2,1), (2,2), (2,3), (2,4), (2,5),
    (3,1), (3,2), (3,3),
           (4,2), (4,3),
    (5,1), (5,2),
    (6,1))

```

# Answer
> 1 votes
## Haskell ~~331~~ ~~357~~ 339 characters

Golfed:

```
import Data.Char
t[x,y]=q[x,mod(y+1)8]
q z@[x,y]|x==y=[x+1,y+2]|0<1=z
x%y=[x,y]
c 65=0%1
c 74=6%4
c 75=1%4
c 79=2%3
c 84=3%4
c 86=4%7
c 87=5%6
c 89=3%6
c 90=6%7
c x=t$c$pred x
_!9='O'
c!n|n`elem`c="|/-\\"!!mod n 4|0<1=' '
s x=do n<-[3:4%5,2:9%6,1:0%7];'\n':do c<-x;' ':map(c!)n
main=putStr.s.map(c.ord.toUpper)=<<getLine

```

Ungolfed:

```
type Clock = [Int]

tick :: Clock -> Clock
tick [h, m] = tick' [h, mod (m + 1) 8]

tick' :: Clock -> Clock
tick' [h, m]
  | h == m = [h + 1, m + 2]
  | otherwise = [h, m]

clock :: Char -> Clock
clock 'a' = [0,1]
clock 'j' = [6,4]
clock 'k' = [1,4]
clock 'o' = [2,3]
clock 't' = [3,4]
clock 'v' = [4,7]
clock 'w' = [5,6]
clock 'y' = [3,6]
clock 'z' = [6,7]
clock c = tick $ clock $ pred c

arm :: Int -> Char
arm 0 = '|'
arm 1 = '/'
arm 2 = '-'
arm 3 = '\\'

drawAt :: Clock -> Int -> Char
drawAt _ 9 = 'O'
drawAt c n = if n `elem` c
  then arm $ n `mod` 4
  else ' '

-- showClock is not in golfed code. Just there for debugging.
showClock :: Clock -> String
showClock c = unlines $ map (map $ drawAt c) [
    [3,4,5]
  , [2,9,6]
  , [1,0,7]
  ]

showClocks :: [Clock] -> String
showClocks cs = unlines $ map (showClocks' cs) [[3,4,5],[2,9,6],[1,0,7]]

showClocks' :: [Clock] -> [Int] -> String
showClocks' cs ns = cs >>= \c -> ' ' : map (drawAt c)

mainx :: IO ()
mainx = putStr . showClocks . map clock =<< getLine

```

---

```
345    \|/                                     \
2 6 == -O-          -O          tick  -O   ==   O      tick   O   ==  -O
107    /|\          /                 /        /              |\      /
             [1,2] or [2,1]    tick [1,2] == [1,3]     tick [0,7] == [1,2]

```

Encoding is `[hour, minute]` where clocks have 8 hours and 8 minutes. Minutes move faster than hours. If a clock ticks where the hour and minute would be equal, add 1 to the hour and 2 to the minute as well (see second tick example above). That is the only way hours increase. Hours do NOT increase when the minute reaches some arbitrary minute. Only when minutes would equal hours. In the ungolfed code, `clock` turns letters into clocks that represent the semaphore. Most clocks are built based on ticking from previous ones. The rest are hard coded. There's nothing really more to the code.

# Answer
> 1 votes
**Perl, ~~356~~, 275 chars**

Great number of chars was saved by replacing 'if else' to '? :' construction.

```
@_=split('', $ARGV[0]);for (@_){print eval{/[ciotuy]/ ?'\\':' '}.eval{/[djkptv]/ ?'|':' '}.eval{/[elquwx]/ ?'/':' '}."\n".eval{/[bhopqrs]/ ?'-':' '}."0".eval{/[fjmrwyz]/ ?'-':' '}."\n".eval{/[ahiklmn]/ ?'/':' '}.eval{/[abcdefg ]/ ?'|':' '}.eval{/[gnsvxz]/ ?'\\':' '."\n"};}

```

# Answer
> 0 votes
# PowerShell, ~~198~~ ~~192~~ ~~191~~ 188 bytes

```
-split$args|%{$s=$_
"\|/ ciotuy djkptv elquwx","-O- bho-s ^ fjmrwyz","/|\ ahik-n a-g gnsvxz"|%{$f,$p=-split$_
($s|% t*y|%{$c=$_
-join(&{$p|%{" $f"[++$i*($c-match"[$_ ]")]}})})-join' '}
''}

```

Try it online!

The output contains one tail empty line.

Less golfed:

```
-split$args|%{
    $string=$_
    "\|/ ciotuy djkptv elquwx",
    "-O- bho-s ^ fjmrwyz",
    "/|\ ahik-n a-g gnsvxz"|%{
        $flags,$patterns=-split$_
        $row=$string|% toCharArray|%{
            $char=$_
            $semaphoreRow=&{   # call the scriptblock in a new scope to reinit $i
                $patterns|%{
                    " $flags"[++$i*($char-match"[$_ ]")]  # return a flag symbol
                }
            }
            -join($semaphoreRow)
        }
        $row-join' '
    }
    ''
}

```

# Answer
> 0 votes
# Charcoal, 70 bytes

```
Ｆ⪪↧Ｓ «Ｆι«Ｆ⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ＆$↥x-#↖x9｜²λＰe⁸” «Ｐ⊗№λκ↷¹»oＭ³→»⸿Ｍ³↓

```

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

```
Ｆ⪪↧Ｓ «

```

Split the lowercased input on spaces and loop over each word.

```
Ｆι«

```

Loop over each character.

```
Ｆ⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ＆$↥x-#↖x9｜²λＰe⁸” «

```

Split the compressed string `fjmrwyz gnsvxz abcdefg ahiklmn bhopqrs ciotuy djkptv elquwx` on spaces and loop over each letter group.

```
Ｐ⊗№λκ

```

If the group contains the current letter then draw a line in the current direction.

```
↷¹»

```

Rotate 45° clockwise.

```
oＭ³→»

```

Output the centre `o` and move to the position of the next letter.

```
⸿Ｍ³↓

```

Move to the start of the next word.

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


title: Grid crossing sequence

text:
# Question
Title: Grid crossing sequence
If you take a sheet of graph paper and draw a sloped line that goes `m` units right and `n` units up, you cross `n-1` horizontal and `m-1` vertical gridlines in some sequence. Write code to output that sequence.

For example, `m=5` and `n=3` gives:

Possibly related: Generating Euclidian rhythms, Fibonacci tilings, FizzBuzz

**Input:** Two positive integers `m,n` that are relatively prime

**Output:** Return or print the crossings as a sequence of two distinct tokens. For example, it could be a string of `H` and `V`, a list of `True` and `False`, or `0`'s and `1`'s printed on separate lines. There can be a separator between tokens as long as it's always the same, and not, say, a variable number of spaces.

**Test cases:**

The first test case gives empty output or no output.

```
1 1
1 2 H
2 1 V
1 3 HH
3 2 VHV
3 5 HVHHVH
5 3 VHVVHV
10 3 VVVHVVVHVVV
4 11 HHVHHHVHHHVHH
19 17 VHVHVHVHVHVHVHVHVVHVHVHVHVHVHVHVHV
39 100 HHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHH

```

In the format `(m,n,output_as_list_of_0s_and_1s)`:

```
(1, 1, [])
(1, 2, [0])
(2, 1, [1])
(1, 3, [0, 0])
(3, 2, [1, 0, 1])
(3, 5, [0, 1, 0, 0, 1, 0])
(5, 3, [1, 0, 1, 1, 0, 1])
(10, 3, [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1])
(4, 11, [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0])
(19, 17, [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
(39, 100, [0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0])

```

# Answer
> 7 votes
# Ruby, 92; Ostrich 0.7.0, 38

```
f=->m,n{((1..m-1).map{|x|[x,1]}+(1..n-1).map{|x|[1.0*x*m/n,0]}).sort_by(&:first).map &:last}

```

```
:n;:m1-,{)o2W}%n1-,{)m n/*0pW}%+_H$_T%

```

Output for both of them uses 1's and 0's (ex. `101101`).

---

Here's an explanation of the Ostrich one:

```
:n;:m    store n and m as variables, keep m on the stack
1-,      from ex. 5, generate [0 1 2 3]
{...}%   map...
  )        increment, now 5 -> [1 2 3 4]
  o        push 1 (the digit 1 is special-cased as `o')
  2W       wrap the top two stack elements into an array
           we now have [[1 1] [2 1] [3 1] [4 1]]
n1-,     doing the same thing with n
{...}%   map...
  )        increment, now 3 -> [1 2]
  m n/*    multiply by slope to get the x-value for a certain y-value
  0        push 0
  pW       wrap the top two stack elements (2 is special-cased as `p')
+        concatenate the two arrays
_H$      sort-by first element (head)
_T%      map to last element (tail)

```

And an explanation of how the whole thing works, using the Ruby code as a guide:

```
f = ->m,n {
    # general outline:
    # 1. collect a list of the x-coordinates of all the crossings
    # 2. sort this list by x-coordinate
    # 3. transform each coordinate into a 1 or 0 (V or H)
    # observation: there are (m-1) vertical crossings, and (n-1) horizontal
    #   crossings. the vertical ones lie on integer x-values, and the
    #   horizontal on integer y-values
    # collect array (1)
    (
        # horizontal
        (1..m-1).map{|x| [x, 1] } +
        # vertical
        (1..n-1).map{|x| [1.0 * x * m/n, 0] }  # multiply by slope to turn
                                               # y-value into x-value
    )
    .sort_by(&:first)  # sort by x-coordinate (2)
    .map &:last        # transform into 1's and 0's (3)
}

```

# Answer
> 5 votes
# Python, 53

This uses the True/False list output. Nothing special here.

```
lambda m,n:[x%m<1for x in range(1,m*n)if x%m*(x%n)<1]

```

# Answer
> 4 votes
# Pyth - ~~32~~ 24 bytes

```
Jmm,chk@Qddt@Qd2eMS+hJeJ

```

Takes input via stdin with the format `[m,n]`. Prints the result to stdout as a list of 0's and 1's, where 0 = V and 1 = H.

Test it online

---

Explanation:

```
J                           # J =
 m             2            # map(lambda d: ..., range(2))
  m        t@Qd             # map(lambda k: ..., range(input[d] - 1))
   ,chk@Qdd                 # [(k + 1) / input[d], d]
                eMS+hJeJ    # print map(lambda x: x[-1], sorted(J[0] + J[-1])))

```

# Answer
> 4 votes
# IA-32 machine code, 26 bytes

Hexdump of the code:

```
60 8b 7c 24 24 8d 34 11 33 c0 2b d1 74 08 73 03
03 d6 40 aa eb f2 61 c2 04 00

```

I started from the following C code:

```
void doit(int m, int n, uint8_t* out)
{
    int t = m;
    while (true)
    {
        if (t >= n)
        {
            t -= n;
            *out++ = 1;
        }
        else
        {
            t += m;
            *out++ = 0;
        }
        if (t == n)
            break;
    }
}

```

It writes the output into the supplied buffer. It doesn't return the length of the output, but it's not really needed: the output length is always `m + n - 2`:

```
int main()
{
    char out[100];
    int m = 10;
    int n = 3;
    doit(m, n, out);
    for (int i = 0; i < m + n - 2; ++i)
    {
        printf("%d ", out[i]);
    }
}

```

To convert the C code into machine code, I first did some tweaking, to make one of the `if/else` branches empty, and compare with `0` instead of `n`:

```
void doit(int m, int n, char* out)
{
    int t = n;
    while (true)
    {
        int r = 0;
        t -= m;
        if (t == 0)
            break;
        if (t >= 0)
        {
        }
        else
        {
            t += m + n;
            ++r;
        }
        *out++ = r;
    }
}

```

From here, writing the inline-assembly code is straightforward:

```
__declspec(naked) void __fastcall doit(int x, int y, char* out)
{
    _asm
    {
        pushad;                 // save all registers
        mov edi, [esp + 0x24];  // edi is the output address
        lea esi, [ecx + edx];   // esi is the sum m+n
    myloop:                     // edx is the working value (t)
        xor eax, eax;           // eax is the value to write (r)
        sub edx, ecx;
        jz myout;
        jae mywrite;
        add edx, esi;
        inc eax;
    mywrite:
        stosb;                  // write one value to the output
        jmp myloop;
    myout:
        popad;                  // restore all registers
        ret 4;                  // return (discarding 1 parameter on stack)
    }
}

```

# Answer
> 4 votes
# CJam, 15 bytes

```
Ll~_:*,\ff{%!^}

```

Try it here.

It prints `01` for V and `10` for H.

### Explanation

```
L          e# An empty list.
l~         e# Evaluate the input.
_:*,       e# [0, m*n).
\          e# The input (m and n).
ff{%!      e# Test if each number in [0, m*n) is divisible by m and n.
^}         e# If divisible by m, add an 10, or if divisible by n, add an 01 into
           e# the previous list. If divisible by neither, the two 0s cancel out.
           e# It's just for output. So we don't care about what the previous list
           e# is -- as long as it contains neither 0 or 1.

```

The diagonal line crosses a horizontal line for every 1/n of the whole diagonal line, and crosses a vertical line for every 1/m.

# Answer
> 3 votes
# Python - 125 bytes

Uses a very simple algorithm, just increments the coordinates and detects when it crosses the lines and prints out. Am looking to translate to Pyth.

```
a,b=input()
i=1e-4
x=y=l=o=p=0
k=""
while len(k)<a+b-2:x+=i*a;y+=i*b;k+="V"*int(x//1-o//1)+"H"*int(y//1-p//1);o,p=x,y
print k

```

That while loop is checking the number of `l`ines and then checking if any of the values went over an int boundary by subtracting.

Takes input like `39, 100` from stdin and prints out like `HHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHHHVHHVHHHVHHVHHHVHHVHHHVHH` to stdout in one line.

# Answer
> 2 votes
# TI-BASIC, 32

```
Prompt M,N
For(X,1,MN-1
gcd(X,MN
If log(Ans
Disp N=Ans
End

```

Straightforward. Uses a sequence of `0` and `1`, separated by linebreaks. TI-BASIC's advantages are the two-byte `gcd(` and implied multiplication, but its disadvantages are the For loop including the end value and the 5 bytes spent for input.

# Answer
> 2 votes
## Python, 47

```
lambda m,n:[m>i*n%(m+n)for i in range(1,m+n-1)]

```

Like anatolyg's algorithm, but checked directly with moduli.

# Answer
> 2 votes
# 05AB1E, ~~8~~ 7 bytes

```
PLIδÖʒO

```

Inspired by *@jimmy23013*'s CJam answer, so make sure to upvote him as well!

Input as a pair of integers \\$\[m,n\]\\$ and output as a list of `[0,1]` and `[1,0]` pairs for \\$V\\$ and \\$H\\$ respectively.

Try it online or verify all test cases.

**Explanation:**

```
P        # Take the product of the (implicit) input-pair: m*n
 L       # Pop and push a list in the range [1, m*n]
  IδÖ    # Check for each value in this list, whether each value in the input-pair evenly
         # divides it (resulting in [0,0] if the number is neither divisible by `m` nor `n`;
         # [0,1] if the number is only divisible by `m`;
         # [1,0] if the number is only divisible by `n`;
         # [1,1] for the final number m*n, which is divisible by both `m` and `n` obviously)
     ʒ   # Then filter this list of pairs, keeping only the pairs which are truthy for:
      O  #  Where the sum of the pair is exactly 1 (NOTE: only 1 is truthy in 05AB1E)
         # (after which the resulting list is output implicitly)

```

# Answer
> 1 votes
# Haskell, 78 bytes

```
import Data.List
m#n=map snd$sort$[(x,0)|x<-[1..m-1]]++[(y*m/n,1)|y<-[1..n-1]]

```

Usage example:

```
*Main> 19 # 17
[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
*Main> 10 # 3
[0,0,0,1,0,0,0,1,0,0,0]

```

How it works: make a list of the x-values of all vertical crossings `(x,0)` for `x` in \[1,2,...,m-1\] (`0` indicates vertical) and append the list of the x-values of all horizontal crossings `(y*m/n,1)` for `y` in \[1,2,...,n-1\] (`1` indicates horizontal). Sort and take the second elements of the pairs.

Curse of the day: again I have to spent 17 bytes on the `import` because `sort` is in `Data.List` and not in the standard library.

# Answer
> 1 votes
# CJam, ~~26~~ 24 bytes

```
l~:N;:M{TN+Mmd:T;0a*1}*>

```

Try it online

Very straightforward, pretty much a direct implementation of a Bresenham type algorithm.

Explanation:

```
l~    Get input and convert to 2 integers.
:N;   Store away N in variable, and pop from stack.
:M    Store away M in variable.
{     Loop M times.
  T     T is the pending remainder.
  N+    Add N to pending remainder.
  M     Push M.
  md    Calculate div and mod.
  :T;   Store away mod in T, and pop it from stack
  0a    Wrap 0 in array so that it is replicated by *, not multiplied.
  *     Emit div 0s...
  1     ... and a 1.
}*      End of loop over M.
>       Pop the last 1 and 0.

```

The last `01` needs to be popped because the loop went all the way to the end point, which is not part of he desired output. Note that we can **not** simply reduce the loop count by 1. Otherwise, for `N > M`, all the `0`s from the last iteration will be missing, while we only need to get rid of the very last `0`.

# Answer
> 1 votes
# KDB(Q), 44 bytes

```
{"HV"0=mod[asc"f"$1_til[x],1_(x*til y)%y;1]}

```

# Explanation

Find all *x* axis values of intersect points and sort them. If mod 1 is zero its "V", non-zero is "H".

# Test

```
q){"HV"0=mod[asc"f"$1_til[x],1_(x*til y)%y;1]}[5;3]
"VHVVHV"

```

---
Tags: code-golf, sequence, grid
---