title: Alphabet printing challenge

text:
# Question
Title: Alphabet printing challenge
This challenge is related

# Challenge

Your task is to write as many programs/snippets as you can, where each one outputs/prints/ returns an alphabet. The first program must output the letter `A` or `a`, the second one `B` or `b` and so on.

**You can not reuse any characters between the programs (Except Whitespace, it can be reused through snippets). So, if the first program is: `0==0`, then you may not use the characters `0` and `=` again in any of the other programs.** Note: It's allowed to use the same character many times in one program.

### Scoring:

The winner will be the submission that can print alphabets up to the highest, if anyone can print upto `Z` or `z`, it will receive an extra `+50` bounty from me. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total.

### Rules:

* You can only use a single language for all alphabets, polygots not supported
* **Snippets are allowed! But quine snippets like `A` which prints `A` are not allowed.**
* leading and trailing spaces are not allowed. But newlines are allowed
* You may disregard STDERR, as long as the correct output is returned to STDOUT
* You cannot choose to output the letters to STDERR.
* Letters are case sensitive `a != A`.
* **The programs/snippets must be independent**
* **Whitespace can be reused**
* Output is case-insensitive, you may choose to either output `a` or `A` but not both!
* You can't use a function, that does not print anything, such as `f(){print a}` will print `a` when it is called, but if you don't call the function, then that snippet/program is invalid.
* Minimum submission length should be `1` byte, but again quines are not allowed

# Answer
# Whitespace, 390 bytes, A-Z

Exploiting the rules a little:

> * **Whitespace can be reused**

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!

```

```

Try it online!
> 25 votes

# Answer
# PowerShell, A-N 109 bytes

Previously: A-F, 41 bytes || A-G, 53 bytes || A-K, 85 bytes || A-M, 101 bytes

```
eCho a
'b'
"c"
{d}
writE E
‛F‛
(mAn)[7][3]
“H“
”I”
’J’
‘K‘
„L„
‚M‚
sv N;gv N|% N*

```

Try it online!
> 21 votes

# Answer
# 05AB1E, 39 bytes, letters a-n

A: `Th`: 10 converted to hexadecimal.
b: `žNн`: The first consonant.
C: `т.X`: 100 as a Roman numeral.
D: `₂;₂B`: Convert 13 to base 26.
e: `A4è`: The character at index 4 in the alphabet.
f: `Ƶ1ç`: `chr(102)`
g: `'g`: single character string.
H: `"H`: string without closing quote.
i: `‘i`: uppercase compressed string.
j: `’j`: compressed string without spaces.
k: `“k`: lowercase compressed string.
l: `”l`: titlecased compressed string.
m: `„mmθ`: last character of `"mm"`.
n: `…nnn¤`: last character of `"nnn"`.
> 9 votes

# Answer
# Pyth, 34 bytes, letters a-g

```
"a

```

Try it online!

```
\b

```

Try it online!

```
C99

```

Try it online!

```
.H+/TT+T2

```

Try it online!

```
>-!4k4

```

Try it online!

```
@G5

```

Try it online!

```
$chr(103)

```

Try it online!

# Explanation

```
"       # Can be used to start a string literal.
\b      # Corresponds to the one-character string 'b'
C99     # Character with code 99.
T       # Variable initialized to 10 by default.
+/TT+T2 # Prefix notation. Evaluates to 13.
.H      # Convert into hexadecimal.
!4      # Logical negation -> False
k       # Variable initialized to empty string by default.
-       # Casts the first argument (bool) into the type of second argument (str).
>4      # Prints all characters starting from index 4.
G       # Variable initialized to "abcdefghijklmnopqrstuvwxyz" by default.
@ G 5   # Get character at index 5 of G.
$       # begin and end python literal.
chr     # Returns the character represented by the integer.

```

*thanks to FryAmTheEggman*
> 7 votes

# Answer
## Whitespace, 390 bytes (15 bytes per letter), A-Z

S = Space; T = Tab

### A

```
SSSTSSSSST
T
SS

```

### B

```
SSSTSSSSTS
T
SS

```

### C

```
SSSTSSSSTT
T
SS

```

### D

```
SSSTSSSTSS
T
SS

```

### E

```
SSSTSSSTST
T
SS

```

### F

```
SSSTSSSTTS
T
SS

```

### G

```
SSSTSSSTTT
T
SS

```

### H

```
SSSTSSTSSS
T
SS

```

### I

```
SSSTSSTSST
T
SS

```

### J

```
SSSTSSTSTS
T
SS

```

### K

```
SSSTSSTSTT
T
SS

```

### L

```
SSSTSSTTSS
T
SS

```

### M

```
SSSTSSTTST
T
SS

```

### N

```
SSSTSSTTTS
T
SS

```

### O

```
SSSTSSTTTT
T
SS

```

### P

```
SSSTSTSSSS
T
SS

```

### Q

```
SSSTSTSSST
T
SS

```

### R

```
SSSTSTSSTS
T
SS

```

### S

```
SSSTSTSSTT
T
SS

```

### T

```
SSSTSTSTSS
T
SS

```

### U

```
SSSTSTSTST
T
SS

```

### V

```
SSSTSTSTTT
T
SS

```

### W

```
SSSTSTTSSS
T
SS

```

### X

```
SSSTSTTSST
T
SS

```

### Y

```
SSSTSTTSTS
T
SS

```

### Z

```
SSSTSTTSTT
T
SS

```
> 7 votes

# Answer
# Jelly, 25 bytes, `ABCdefG`

```
ØAḢ

```

Try it online!

```
”B

```

Try it online!

```
⁾C

```

Try it online!

Note the trailing newline

```
³Ọ

```

Try it online!

```
.ȷ22ŒṘ2ị

```

Try it online!

```
1÷0ṾṪ

```

Try it online!

```
“G

```

Try it online!

+2 more from Unrelated String

How you can make a string in Jelly:

* Character literals, beginning with
* String literals, using `“”` as delimiters (or `“«`, but that's undefined behaviour that happens to work in our favor). Trailing  can be omitted at the end of the program
* Compressed strings, using `“»` as delimiters
* Two character literals, beginning with
* Converting from a number to a character with
* Using the builtin string constants, almost all of which begin with `Ø`
* Python/Jelly representations

## How they work

* `A`:

```
ØAḢ - Main link. No arguments
ØA   - Yield the uppercase alphabet
  Ḣ  - Head; Take the first element, "A"

```
* `B` uses a character literal `”B`
* `C` uses a two character literal, with a trailing newline, to output `C` and a newline
* `d`:

```
³Ọ - Main link. No arguments
³  - Yield 100
 Ọ - Convert to character "d"

```
* `e`:

```
.ȷ22ŒṘ2ị - Main link. No arguments
.ȷ22     - Literal: 5e+21
    ŒṘ   - Python representation
      2ị - Second character

```
* `f`:

```
1÷0ṾṪ - Main link. No arguments
1÷0   - 1÷0 = inf
   ṾṪ - Last character; "f"

```
* `G` uses a character literal `“G`
> 6 votes

# Answer
# Bubblegum, 1 byte for each, 26 bytes for `a`-`z`

```
B
```

```
C
```

```
D
```

... some programs omitted ...

```
Y
```

```
Z
```

```
[
```

Try them online!
> 5 votes

# Answer
# Keg, 26 bytes (Sbcs) (A through Z)

```
Ȧ
Ɓ
Ƈ
Ɖ
Ɛ
Ƒ
Ɠ
Ƕ
Ȋ
ȷ
Ǩ
Ƚ
Ɯ
Ɲ
Ǫ
Ƿ
Ɋ
Ʀ
Ș
Ț
Ȕ
Ʋ
Ʌ
ƛ
Ƴ
Ƶ

```

Try it online!

Each byte is a program - I simply put them together for convenience. This kids is the power of bad language design - a built-in for each letter of the alphabet, something specifically designed for challenges like this.
> 5 votes

# Answer
# Charcoal, 23 bytes, ABCDEF

```
⌊α

```

Try it online! Explanation: Outputs the minimum of the uppercase letters, i.e. `A`.

```
℅⁶⁶

```

Try it online! Explanation: Outputs the ASCII character 66, i.e. `B`.

```
↥§β²

```

Try it online! Explanation: Outputs the lowercase letter at position 2 (0-indexed), converted to upper case, i.e. `C`.

```
⊟…ψE

```

Try it online! Forms the range of characters up to (but not including) `E`, and takes the last, i.e. `D`.

```
⍘⁴⁰φ

```

Try it online! Explanation: Converts 40 to base 62, which is `E`.

```
Φγ⁼κ³⁸

```

Try it online! Explanation: Outputs the 38th printable ASCII character, counting space as 0, i.e. `F`.
> 4 votes

# Answer
# Zsh, 76 bytes, `abcd`

```
echo a
print b
w=101;x=99;y=104;z=111;${(#)w}${(#)x}${(#)y}${(#)z} ${(#)x}
<<<d

```

Try it online!

+1 score thanks to @Makonede
> 4 votes

# Answer
# Vyxal `K`, 864 bytes, A-Z

The `K` flag treats numbers as ordinal values when printing them, so for everything except the string and character literals, we just need to get the right number, and it gets converted to a character automatically.

**Note: Space is shown used twice, but that is only for readability. The link for `X` has the spaces replaced with newlines.**

```
₄₄₄₄±₄±↲/Ṡ

```

Try it Online!

```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

```

Try it Online!

```
⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐

```

Try it Online!

```
44H

```

Try it Online!

```
111111111111111111111111111111111111111111111111111111111111111111111„1βȧ

```

Try it Online!

```
99999999999999999999999999999999b∑

```

Try it Online!

```
₆›››››››

```

Try it Online!

```
88¦¦¦¦¦¦¦¦G

```

Try it Online!

```
u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-

```

Try it Online!

```
⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧

```

Try it Online!

```
555555555555555555555555555555555555555555555555555555555555555555555555555L

```

Try it Online!

```
76

```

Try it Online!

```
≤mmmmm

```

Try it Online!

```
₈⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩

```

Try it Online!

```
\O

```

Try it Online!

```
«≬λλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλ«żt

```

Try it Online!

```
3²²

```

Try it Online!

```
`R

```

Try it Online!

```
‛S Ǎ

```

Try it Online!

```
×Cd

```

Try it Online!

```
₇‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

```

Try it Online!

```
=:+:+:+:+:+:+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+

```

Try it Online!

```
₀ɽ÷_p

```

Try it Online!

```
2 2*2*2 2*2*J

```

Try it Online!

```
kZḢh

```

Try it Online!

```
»[

```

Try it Online!
> 4 votes

# Answer
# \\/\\/\>, 36 bytes, `abc`

a: `'a'u;`
b: `e7*Uf4*1-00s` program terminator ";" is used up, so `f4*1-00s` places a ";" at 0,0
c: `"␀␁9"2+"c␀␀S"2+mS}S` now both "u" and "U" are used, so I do the same trick to place "U;" at the start. (␀ and ␁ are the actual ascii 0 and 1 characters)
This is the logical limit to the alphabet size since I can only use the "s" instruction twice, can probably still be golfed though.
Alphabet is even smaller for \>\<\> due to not supporting uppercase instructions.

What a neat challenge!
> 3 votes

# Answer
# Vyxal, 15 bytes, a-f

```
kzt

```

Try it Online!

```
\b

```

Try it Online!

```
‛cch

```

Try it Online!

```
₁C

```

Try it Online!

```
«ƛ

```

Try it Online!

```
`f

```

Try it Online!

So, there are only a few ways to get strings in Vyxal:

String literals:

```
\. , ‛.. , `...\`

```

chr(x) - `...C`

compressed string literals - `«...«`

And deriving from a constant (`k...`).

That's all we can really do :P
> 3 votes

# Answer
# Factor, ~~8~~ 14 bytes, ~~`a`~~`ab`

```
"a"print
11 .h

```

Try it online!

In Factor you can `print`, `printf` or `write` to stdout, but they share characters. I don't know of any other suitable output method. But as @Bubbler writes, a-f can be output as hex numerals.
> 2 votes

# Answer
# V ~~a-r 46 bytes~~ ~~a-x 77 bytes~~ ~~a-y 84 bytes~~ a-z 86 bytes

Probably not going to be a contender, but maybe someone can help me improve it. Had fun trying anyways.

EDIT: Got a lot farther than I thought I would! A few of my older answers were invalid, according to the rules, so they've been removed. I don't have any ideas for the last two letters, so I think this is it for this one.

EDIT2: Had another idea. Any ideas for getting `z` are welcome.

EDIT3: Got the last one! I could have sworn I had already used `C` somewhere, but turns out I hadn't. Still not a contender, but it was a fun exercise.

```
aa

```

Try it online!

```
Ab

```

Try it online!

```
ccc

```

Try it online!

```
³dd2Fd

```

Try it online!

```
Re

```

Try it online!

```
Sf

```

Try it online!

```
Ég

```

Try it online!

```
éh

```

Try it online!

```
ii

```

Try it online!

```
Ij

```

Try it online!

```
¬kk

```

Try it online!

```
ál

```

Try it online!

```
Ám

```

Try it online!

```
On

```

Try it online!

```
oo

```

Try it online!

```
í^/p

```

Try it online!

```
±q9X

```

Try it online!

```
²r#r

```

Try it online!

```
ss

```

Try it online!

```
µtótttt

```

Try it online!

```
·uÓuu

```

Try it online!

```
²vD

```

Try it online!

```
¹wÍww

```

Try it online!

```
¶x5Fx5x

```

Try it online!

```
´yyEVP

```

Try it online!

```
Cz

```

Try it online!
> 2 votes

---
Tags: string, code-challenge, restricted-source
---


title: Is this an ordinal transform?

text:
# Question
Title: Is this an ordinal transform?
Related: What's my telephone number? which asks to calculate the terms of A000085, the number of possible ordinal transforms of length n.

## Background

**Ordinal transform** is a transformation on an integer sequence. For a sequence \\$a=(a\_0, a\_1, a\_2, \cdots)\\$, the \\$n\\$-th term of the ordinal transform \\$ord(a)\_n\\$ is defined as the occurrence count of \\$a\_n\\$ in \\$a\_0, a\_1, \cdots, a\_n\\$. Informally, \\$ord(a)\\$ can be described as "the value \\$a\_n\\$ appears the \\$ord(a)\_n\\$-th time in the sequence \\$a\\$".

For example, the sequence `[1, 2, 1, 1, 3, 2, 2, 3, 1]` transforms into `[1, 1, 2, 3, 1, 2, 3, 2, 4]`.

```
1, 2, 1, 1, 3, 2, 2, 3, 1
1, 1, 2, 3, 1, 2, 3, 2, 4
^     ^  ^              ^
|     |  |              4th occurrence of 1
|     |  3rd occurrence of 1
|     2nd occurrence of 1
1st occurrence of 1

```

The number of possible ordinal transforms is A000085. A hint to tackle this problem can be found on the page (search for "ballot sequences").

## Challenge

Given a non-empty finite integer sequence, test if it can be the result of ordinal transform of some integer sequence.

You can assume the input entirely consists of positive integers.

For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code in bytes wins.

## Test cases

**Truthy**

```
[1]
[1, 1]
[1, 2, 3, 1]
[1, 1, 2, 2]
[1, 2, 1, 2, 1, 2, 1]
[1, 2, 3, 4, 5, 6, 7]
[1, 1, 2, 3, 1, 2, 3, 2, 4]
[1, 1, 2, 3, 4, 2, 1, 3, 2, 1]

```

**Falsy**

```
[2]
[6]
[1, 3]
[2, 1, 1]
[1, 2, 2, 1]
[1, 2, 3, 2]
[1, 2, 3, 4, 4]
[1, 2, 3, 2, 1]

```

# Answer
# Jelly, ~~8~~ 7 bytes

```
Ṭ€+\I’Ȧ

```

Try it online!

-1 byte thanks to Jonathan Allan

Outputs an empty array (falsey) if it can be the result, and a non-empty array (truthy) if not.

## How it works

```
Ṭ€+\I’Ȧ - Main link. Takes a list L on the left
 €      - For each integer I in L:
Ṭ       -   Untruth; Generate a list of zeroes of length I, replace the last with 1
   \    - Scan by:
  +     -   Addition
    I   - Get the forward differences of each
     ’  - Decrement
      Ȧ - This array does not contain any 0s

```

For exactly what this does, let's look at this step by step:

| Command | Truthy example | Falsey example |
| --- | --- | --- |
| Start | `[1, 2, 3, 1]` | `[1, 2, 3, 2]` |
| `Ṭ€` | `[[1], [0, 1], [0, 0, 1], [1]]` | `[[1], [0, 1], [0, 0, 1], [0, 1]]` |
| `+\` | `[[1], [1]+[0,1], [1]+[0,1]+[0,0,1], [1]+[0,1]+[0,0,1]+[1]]` `[[1], [1,1], [1,1,1], [2,1,1]]` | `[[1], [1]+[0,1], [1]+[0,1]+[0,0,1], [1]+[0,1]+[0,0,1]+[0,1]]` `[[1], [1,1], [1,1,1], [1,2,1]]` |

At this point, we have running counts of each element. The `i`th element of `Ṭ€+\` is a list `[a,b,c,...,z]` where `a` is the number of counts of `1` in the first `i` elements of the input, `b` the counts of `2` and so on. The input is only truthy if each list is ordered descendingly.

In order to do this, we get the forward differences of each. This will be a list of lists of `-1`, `1` and `0`. If any of the differences have `1`, then it's ascending. We then decrement, mapping `1` to `0` and everything else to a non-zero element. Finally, we check with `Ȧ` that there are no zeroes in the list at any level.
> 4 votes

# Answer
# JavaScript (ES6), 40 bytes

```
a=>a.every(n=>a[a[~n]=-~a[~n],-n]--|n<2)

```

Try it online!

Ungolfed:

```
arr => {
  const count = [Infinity]
  for (let i = 0; i < arr.length; i++) {
    const num = arr[i];
    count[num] = (count[num] || 0) + 1;
    count[num - 1] = (count[num - 1] || 0) - 1;
    if (count[num - 1] < 0) {
      return false;
    }
  }
  return true;
}

```
> 3 votes

# Answer
# Japt, ~~16~~ 15 bytes

~~Quite exhausted so I'm sure I'll improve upon it in the morn'. Less sure that it's actually correct so, mods, please delete if it's not.~~ Shockingly, it *was* correct! Haven't been able to improve much on my score, though.

```
e1g2Æ=¡YôgU è¶X

```

Try it or run all test cases
> 2 votes

---
Tags: code-golf, math, array, decision-problem, integer
---


title: Traffic direction

text:
# Question
Title: Traffic direction
## Rules

Given an ISO3166-1-Alpha-2 country code your task is to decide on the traffic direction for that country:

* Input will be a valid country code (valid as in it's an element of the two lists provided)
* Input may be a list of two characters instead of a string if it helps
* You may choose to take input in lowercase
* You will choose one value, say for *right* (your choice) and will output that value iff the traffic in that country is right-handed and anything else in the other case
* You only have to handle country codes that are contained in one of these lists:

These are all countries where traffic is left-handed:

```
['AI', 'AG', 'AU', 'BS', 'BD', 'BB', 'BM', 'BT', 'BW', 'VG', 'BN', 'KY', 'CX', 'CC', 'CK', 'CY', 'DM', 'FK', 'FJ', 'GD', 'GG', 'GY', 'HK', 'IN', 'ID', 'IE', 'IM', 'JM', 'JP', 'JE', 'KE', 'KI', 'LS', 'MO', 'MW', 'MY', 'MV', 'MT', 'MU', 'MS', 'MZ', 'NA', 'NR', 'NP', 'NZ', 'NU', 'NF', 'PK', 'PG', 'PN', 'SH', 'KN', 'LC', 'VC', 'WS', 'SC', 'SG', 'SB', 'SO', 'ZA', 'GS', 'LK', 'SR', 'SZ', 'TH', 'TL', 'TK', 'TO', 'TT', 'TC', 'TV', 'UG', 'GB', 'TZ', 'VI', 'ZM', 'ZW']

```

And here are all countries where traffic is right-handed:

```
['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AQ', 'AR', 'AM', 'AW', 'AT', 'AZ', 'BH', 'BY', 'BE', 'BZ', 'BJ', 'BO', 'BA', 'BV', 'BR', 'IO', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'CF', 'TD', 'CL', 'CN', 'CO', 'KM', 'CG', 'CR', 'CI', 'HR', 'CU', 'CW', 'CZ', 'KP', 'CD', 'DK', 'DJ', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FO', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GP', 'GU', 'GT', 'GW', 'GN', 'HT', 'HM', 'VA', 'HN', 'HU', 'IS', 'IR', 'IQ', 'IL', 'IT', 'JO', 'KZ', 'KW', 'KG', 'LA', 'LV', 'LB', 'LR', 'LY', 'LI', 'LT', 'LU', 'MG', 'ML', 'MH', 'MQ', 'MR', 'YT', 'MX', 'FM', 'MC', 'MN', 'ME', 'MA', 'MM', 'NL', 'NC', 'NI', 'NG', 'NE', 'MP', 'NO', 'OM', 'PW', 'PA', 'PY', 'PE', 'PH', 'PL', 'PT', 'PR', 'QA', 'KR', 'MD', 'RE', 'RO', 'RU', 'RW', 'BL', 'MF', 'PM', 'SM', 'ST', 'SA', 'SN', 'RS', 'SL', 'BQ', 'SX', 'SK', 'SI', 'SS', 'ES', 'PS', 'SD', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'MK', 'TG', 'TN', 'TR', 'TM', 'UA', 'AE', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE', 'VN', 'WF', 'EH', 'YE']

```

---

For completeness sake, here's a CSV file that contains all the values along with the country names.

## Testcases

Assuming you chose to output `L` for left-handed traffic, here are some valid test cases:

```
'PY' -> 'python'
'PN' -> 'L'
'CN' -> 33
'GY' -> 'L'

```

**Note:** There is a small chance that I missed a country or that there's a wrong classification and I will not change the specs because that might invalidate answers. If I made a mistake I sincerely apologize, please don't take offense!

# Answer
> 13 votes
# Python 2, ~~145~~ ~~136~~ ~~112~~ 109 bytes

```
'TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ'.find

```

Try it online!

Outputs `-1` for right-handed traffic. ~~The string is autogenerated with this Retina script.~~ Thanks to totallyhuman for the 9 bytes shorter lookup string. I was able to get 24 bytes more off through AdmBorkBork suggestion.
Got the lookup string 3 bytes shorter using a python script.

# Answer
> 13 votes
# Jelly, 61 bytes

*Many thanks to @Mr.Xcoder for helping me putting this together*
*Saved 1 byte thanks to @JonathanAllan*

Returns `0` for right-handed or `1` for left-handed.

```
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’ḃ⁴+\
Oḅ⁹×6%⁽£€%566e¢

```

Try it online!

### How?

We convert each country code to an integer **N** by parsing it as base-256 and apply the following hash function, which is collision-free for left-handed vs right-handed traffic:

```
((N * 6) MOD 1513) MOD 566

```

This leads to the following list of values for left-handed traffic:

```
[   8,  14,  27,  37,  52,  60,  62,  68,  71,  84,  85,  88, 103, 105, 114, 119, 135,
  166, 167, 180, 187, 190, 195, 196, 202, 207, 208, 211, 214, 225, 226, 229, 232, 255,
  256, 262, 285, 301, 302, 303, 304, 309, 322, 325, 327, 337, 357, 369, 370, 381, 393,
  401, 408, 413, 420, 430, 453, 467, 473, 478, 492, 503, 509, 513, 516, 527, 528, 541,
  546, 547, 556, 562 ] (72 entries)

```

The average difference between two consecutive entries is close to 8. We delta-encode the list with increments in the range \[1...16\]. It means that whenever an increment is greater than 16, we need to insert an intermediate value on an unused slot (we have to make sure that it's not hit by right-handed traffic). But the hash function was chosen in such a way that we only have to do that for a few positions. This gives:

```
[  8,  6, 13, 10, 15,  8,  2,  6,  3, 13,  1,  3, 15,  2,  9,  5, 16, 15, 16,  1, 13,
   7,  3,  5,  1,  6,  5,  1,  3,  3, 11,  1,  3,  3, 16,  7,  1,  6, 16,  7, 16,  1,
   1,  1,  5, 13,  3,  2, 10, 16,  4, 12,  1, 11, 12,  8,  7,  5,  7, 10, 16,  7, 14,
   6,  5, 14, 11,  6,  4,  3, 11,  1, 13,  5,  1,  9,  6 ] (77 entries)

```

We convert this list from bijective base-16 to the following integer:

```
274705197430389746738026977757328941544772847257562272094076195694133371689429679543810871702

```

which becomes `“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’` in Jelly's base-250 encoding.

The first link rebuilds the original list from this integer and the second one tests whether it contains the hash of the input.

```
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’ḃ⁴+\      - 1st link: takes no input
“ŒỴ¬Ʋ>r¤dị|®ædHẇ⁸ɗH^CŒ³ẇPḷgȤƲȥƓƑ®Ƭṅḅ4ṛḟṄ’          - our big integer
                                         ḃ⁴        - convert it to bijective base-16
                                           +\      - apply delta-decoding

Oḅ⁹×6%⁽£€%566e¢                  - 2nd link: takes the country code  -> e.g. 'GB'
O                                - get ASCII codes                   -> [71, 66]
 ḅ⁹                              - convert from base-256 to integer  -> 18242
   ×6                            - multiply by 6                     -> 109452
     %⁽£€                        - modulo 1513                       -> 516
         %566                    - modulo 566                        -> 516
             e                   - look for it in the decoded list,
              ¢                  - using the first link as a nilad   -> 1

```

# Answer
> 11 votes
# PowerShell, ~~161~~ 148 bytes

```
"$args"-match'A[GIU]|B[BDMNSTW]|[CFHW][CJKSXY]|DM|G[BDGSY]|[IJ][DEMNP]|K[EINY]|L[CKS]|M[OS-WYZ]|N[AFP-Z]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|Z.'

```

Try it online!

~~Naïve~~ regex pattern matching. Outputs `True` for left-handed and `False` for right-handed.

*Saved 13 bytes thanks to mercator golfing the regex.*

# Answer
> 9 votes
# Haskell, 137 bytes

*-5 bytes thanks to ovs.*

```
import Data.List
(`isInfixOf`"MSOBTVGBSBBMZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKNZMWMYMUPKNPGSRNUTKTOTCTZSZWTTH")

```

Try it online!

Generated the original string by hand.

# Answer
> 8 votes
# 05AB1E, ~~82~~ 68 bytes

Outputs **1** for left-traffic and **0** for right-traffic.

```
.•6uγ)₅₄вwÔívtÎĆ–≠5βI·{!ÅÇΔ›íÕ(1.€ò“Ñ¦_£äß₂Ë‹ûÚм2±rrÇQ=ÅÔζ)B†š¢¡ε•så

```

Try it online! or as a Test Suite

Uses the string generated by totallyhuman and improved by ovs

# Answer
> 6 votes
# 05AB1E, 76 bytes

```
.•B6L>õKвΩ~#ëΓnĀÿι–öß/çÄ¸’Û´äηÅÚ‚zÄ¨e÷ö#YʒƒʒjªêKΩoúö‰Öe¡₄Æ∞¤iY¥•#vySANèì})åZ

```

Try it online!

---

```
.•B6L>õKвΩ~#ëΓnĀÿι–öß/çÄ¸’Û´äηÅÚ‚zÄ¨e÷ö#YʒƒʒjªêKΩoúö‰Öe¡₄Æ∞¤iY¥•

```

Outputs the following string:

```
GIU BDMNSTW CKXY M  JK BDGSY K DEMN EMP EINY CKS OSTUVWYZA FPRUZ  GKN   BCGHORZ CHKLOTVZ G CGI S   AMW

```

If I split that on spaces, and interleave the alphabet into each string, it results in all the states that drive on the left side.

---

1 for left, 0 for right; Emigna's is better, but this felt different enough to post :).

# Answer
> 6 votes
# Jelly, 69 bytes

```
ẇ“h¦¤$>Xø3¬I_°Ḷd⁺+ç*p¢7"FU]#x⁹ĿAxḷŻbCȦ]$ḣẒẓST¬ȥ¬ṆṠ®æ÷©#ḄS#MĠỤ4ɱ5’ṃØA¤

```

A monadic link taking a list of characters and returning `1` if left (`0` if right).

**Try it online!**

**How?**

Uses the method as implemented totallyhuman / ovs.

```
ẇ“ ... ’ṃØA¤ - Link: list of characters
           ¤ - nilad followed by link(s) as a nilad:
 “ ... ’     -   base 250 number = 19752831477605543488091668410027486265612829758468833715947215534967455540194888181580207621675010690833131726534873382634884974263558670694315853304
         ØA  -   list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
        ṃ    -   base decompress = "MSOBTVGBSBBNZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKOZMWMYMUPKNPGSRNUTKTOTCUZTZWTTH"
ẇ            - is a sublist of?

```

---

Also, what I did independently came in at **72 bytes**:

```
“¦w/ḳœBẒḂṡẏ,©ḷĿdẎq⁸4ṙ^|ṂỌʋ:vkɱF#ẊṠµd¤w,ḋhn|ȯ24ɦm|×ỵ’ṃ©ØAO0;I<0œṗ®ṭ€"ØAẎċ

```

Also a monadic link taking a list of characters and returning `1` if left (`0` if right).

**Try it online!**

**How?**

```
“ ... ’ṃ©ØAO0;I<0œṗ®ṭ€"ØAẎċ - Link: list of characters
“ ... ’                     - base 250 number = 20449742094039418439524274048234013619715377161457577389098927787850535557806494274193349238496252074719534810320317229
         ØA                 - list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
       ṃ                    - base decompress = "GIUBDMNSTWCKXYMKJKBDGSYKDEMNEMPEINYCKSOSTUVXZZAFPRVZHGKNDCBCGHOSZCHKLOTWZGCGIASCBAMW"
        ©                   - copy to register
           O                - cast to ordinals = [71,73,85,66,68,77,78,83,84,87,67,75,88,89,77,75,74,75,66,68,71,83,89,75,68,69,77,78,69,77,80,69,73,78,89,67,75,83,79,83,84,85,86,88,90,90,65,70,80,82,86,90,72,71,75,78,68,67,66,67,71,72,79,83,90,67,72,75,76,79,84,87,90,71,67,71,73,65,83,67,66,65,77,87]
            0               - literal zero
             ;              - concatenate = [0,71,73,85,66,68,77,78,83,84,87,67,75,88,89,77,75,74,75,66,68,71,83,89,75,68,69,77,78,69,77,80,69,73,78,89,67,75,83,79,83,84,85,86,88,90,90,65,70,80,82,86,90,72,71,75,78,68,67,66,67,71,72,79,83,90,67,72,75,76,79,84,87,90,71,67,71,73,65,83,67,66,65,77,87]
              I             - incremental differences = [71,2,12,-19,2,9,1,5,1,3,-20,8,13,1,-12,-2,-1,1,-9,2,3,12,6,-14,-7,1,8,1,-9,8,3,-11,4,5,11,-22,8,8,-4,4,1,1,1,2,2,0,-25,5,10,2,4,4,-18,-1,4,3,-10,-1,-1,1,4,1,7,4,7,-23,5,3,1,3,5,3,3,-19,-4,4,2,-8,18,-16,-1,-1,12,10]
                0           - literal zero
               <            - less than (vectorises) = [0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,0]
                   ®        - recall from register = "GIUBDMNSTWCKXYMKJKBDGSYKDEMNEMPEINYCKSOSTUVXZZAFPRVZHGKNDCBCGHOSZCHKLOTWZGCGIASCBAMW"
                 œṗ         - partition at truthy indexes = ["GIU","BDMNSTW","CKXY","M","K","JK","BDGSY","K","DEMN","EMP","EINY","CKS","OSTUVXZZ","AFPRVZ","H","GKN","D","C","BCGHOSZ","CHKLOTWZ","G","CGI","AS","C","B","AMW"]
                       ØA   - list of characters = "ABCDEFGHIJKLMNPQRSUVWXZ"
                      "     - zip with:
                    ṭ€      -   tack for €ach = [["AG","AI","AU"],["BB","BD","BM","BN","BS","BT","BW"],["CC","CK","CX","CY"],["DM"],["EK"],["FJ","FK"],["GB","GD","GG","GS","GY"],["HK"],["ID","IE","IM","IN"],["JE","JM","JP"],["KE","KI","KN","KY"],["LC","LK","LS"],["MO","MS","MT","MU","MV","MX","MZ","MZ"],["NA","NF","NP","NR","NV","NZ"],["OH"],["PG","PK","PN"],["QD"],["RC"],["SB","SC","SG","SH","SO","SS","SZ"],["TC","TH","TK","TL","TO","TT","TW","TZ"],["UG"],["VC","VG","VI"],["WA","WS"],["XC"],["YB"],["ZA","ZM","ZW"]]
                         Ẏ  - tighten = ["AG","AI","AU","BB","BD","BM","BN","BS","BT","BW","CC","CK","CX","CY","DM","EK","FJ","FK","GB","GD","GG","GS","GY","HK","ID","IE","IM","IN","JE","JM","JP","KE","KI","KN","KY","LC","LK","LS","MO","MS","MT","MU","MV","MX","MZ","MZ","NA","NF","NP","NR","NV","NZ","OH","PG","PK","PN","QD","RC","SB","SC","SG","SH","SO","SS","SZ","TC","TH","TK","TL","TO","TT","TW","TZ","UG","VC","VG","VI","WA","WS","XC","YB","ZA","ZM","ZW"]
                            - ...this is the left list plus EK, OH, QC, RC, WA, XC, and YB
                            -    (which are not in the right list)
                          ċ - count

```

# Answer
> 6 votes
# Befunge, ~~155~~ ~~152~~ ~~147~~ 146 bytes

```
~48*%10p~20pv
\"`"`"A"+61p>:2g:48*%10g-!20g61g-!#@*#,_\1+:"O"#@`#._
NzBSgCLVStBGiIJknAVGPSuStAKvfCFHPLttBDIJzBIPkMStJn{NsBLMWgBMtAMnMtBMzcKCGmMNSt

```

Try it online!

Outputs `80` for a right-handed country, and anything else indicates a left-handed country.

**Explanation**

The bottom line of the code contains a representation of all the left-handed countries. This is a list of the first characters of the country codes, grouped by their second character. The end of each group is marked by lowercasing the last character in the group.

So for example the first group, `Nz`, represents `NA` and `ZA`. The second group, `BSg`, represents `BB`, `SB`, and `GB`. There is one group for each letter in the alphabet, except for the letter `Q` (no left-hand country codes end in `Q`). That empty group is represented by the character `{`, since that obviously won't match any valid country code.

To determine whether a given country code matches one of these entries, we iterate through the list checking whether any of the characters in the list match the first character of our input (mod 32 to account for the case), and also that the corresponding group, matches the second character of the input. The group character start as `A`, and is incremented every time we encounter a lowercase letter in the list.

We exit when we find a match, outputting the last character value on the stack (which will be the first character of the country code - possibly lowercase). Otherwise we'll exit when we've iterated through the whole list, in which case we will output the last number on the stack, which is always 80.

# Answer
> 6 votes
# Windows Batch, ~~289~~ ~~279~~ ~~199~~ ~~193~~ ~~181~~ ~~130~~ 118 bytes

```
@echo TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ|find "%1"

```

Outputs the ovs' string for left-hand traffic, else outputs nothing.

**Note:** I noticed if the input *contains* any country code in the list above, it will still output L. However, this does not violate the challenge rule as OP mentioned only country codes need to be handled.

---

Explanation:

```
@echo TTHSZ...OTCTZ            :: List all country code.(compressed by ovs)
                   |           :: Pipe the result to the find command.

                    find "%1"  :: Find the first argument in the country code list,
                               :: and output the ovs string if found.

                               :: By default, FIND returns the piped string when
                               :: a match is found.

```

# Answer
> 5 votes
# Excel VBA, 118 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs `0` if the country is right-handed

```
?InStr(1,"TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",[A1])

```

uses ovs' string

# Answer
> 5 votes
# C (gcc), ~~181~~ ~~169~~ 165 bytes

```
f(x){x=strstr("AIAUBSBDBBMBTBWVGBNKYCXCCKCYDMFKFJGDGGYHKINIDIEIMJMJPJEKELSMOMWMYMVMTMUMZNANRNPNZNUNFPKPGPNSHKNLCVCWSSCSGSOZAGSLKSRSZTHTLTKTOTTCTVUGTZVIZMZW",x)?:82;}

```

Try it online!

# Answer
> 5 votes
# Retina, ~~150~~ 117 bytes

```
$
MSOBTVGBSBBMZAINAGDMOAUGGYBDBWSHKYBNRJPNFJMVCKIMTLCCXLSCYFKEVIDIEJELSGSOLKNZMWMYMUPKNPGSRNUTKTOTCTZSZWTTH
^(..).*\1

```

Try it online!

# Answer
> 5 votes
# Python 2, 144 bytes

```
lambda l:l[1]in'GIU,BDMNSTW,CKXY,M,,JK,BDGSY,K,DEMN,EMP,EINY,CKS,OSTUVWYZ,AFPRUZ,,GKN,,,BCGHORZ,CHKLOTVZ,G,CGI,S,,,AMW'.split(',')[ord(l[0])-65]

```

**Try it online!**

Prints `True` for left, `False` for right.

# Answer
> 4 votes
# Japt, ~~126~~ ~~100~~ 97 bytes

Uses ~~totallyhuman's~~ ovs' lookup string. Takes input in lowercase and outputs `false` for RHD or `true` otherwise.

```
`tszwmsgspknzmwvidfkelscyjpnfjmtvcxbnrbw¢kyauggybtlc×Svgbsbbmzaagd¶b¹ejemymunupgsrlktktctz`øU

```

Try it

Everything between the backticks is the lookup string lowercased and compressed and `ø` checks if it contains the input, `U`.

# Answer
> 3 votes
# sed, ~~148+1~~ ~~145+1~~ ~~143+1~~ 142+1 bytes

One extra byte for `-r` flag (POSIX extended regexes).

Outputs empty string for left-handed traffic, original country code for the right-handed traffic.

```
s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//

```

Example:

```
$ echo -e 'PY\nPN\nCN\nGY' | sed -re 's/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//'
PY

CN

$

```

Explained edit history:

```
148 s/A[GIU]|B[BDMNSTW]|C[CKXY]|DM|F[JK]|G[BDGSY]|HK|I[DEMN]|J[EMP]|K[EINY]|L[CKS]|M[OSTUVWYZ]|N[AFPRUZ]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|WS|Z.//
    naïve regexp; the only optimization here is 'Z.'
145 s/A[GIU]|B[BDMNSTW]|C[CKXY]|DM|F[JK]|G[BDGSY]|HK|I[DEMN]|J[EMP]|K[EINY]|L[CKS]|M[OS-WYZ]|N[AFP-Z]|P[GKN]|S[BCGHORZ]|T[CHKLOTVZ]|UG|V[CGI]|WS|Z.//
    M[OSTUVWYZ] → M[OS-WYZ]
    N[AFPRUZ] → N[AFP-Z]
    the replacements can match inexistent coutries, which is totally fine
143 s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[EMP]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//
    |[^DMS]K (which also matches impossible country codes) allows these changes:
    C[CKXY] → C[CXY]
    F[JK] → FJ
    |HK → ∅
    L[CKS] → L[CS]
    P[GKN] → P[GN]
    T[CHKLOTVZ] → T[CHLOTVZ]
142 s/A[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K//
    J[EMP] → J[^O] (thanks @Neil)

```

## sed, ~~158+1~~ ~~155+1~~ ~~153+1~~ 152+1 bytes, non-empty answer

Slight variation of the previous one. Returns `L` for left-handed traffic.

```
s/[GIU]|B[BDMNSTW]|C[CXY]|DM|FJ|G[BDGSY]|I[DEMN]|J[^O]|K[EINY]|L[CS]|M[OS-WYZ]|N[AFP-Z]|P[GN]|S[BCGHORZ]|T[CHLOTVZ]|UG|V[CGI]|WS|Z.|[^DMS]K/&L/;s/^..//

```

# Answer
> 3 votes
# Pyth, ~~60~~ ~~57~~ ~~55~~ ~~50~~ ~~47~~ ~~46~~ 44 bytes

```
00000000: 736d 406a 4322 579f 235e 804c c3eb 6f49  sm@jC"W.#^.L..oI
00000010: aee5 1f3d be3d 4e13 f326 1934 a181 a210  ...=.=N..&.4....
00000020: 7158 3f94 2232 2f43 5164 5336            qX?."2/CQdS6

```

Run online

Takes the input as an uppercase quoted string (`'AI'`). Returns `3` for left and non-`3` for right.

### How it works

```
sm@jC"…"2/CQdS6
 m           S6   map for d in [1, …, 6]:
     "…"            string literal
    C               convert to integer from base 256
   j    2           digits in base 2
  @                 wrapping index at:
           Q          input string
          C           convert to integer from base 256
         /  d         integer division by d
s                 sum

```

### Generating the magic string

```
import binascii
import z3
n, k, c = 239, 6, 3
a = [z3.Bool('a{}'.format(i)) for i in range(n)]
def f(s0, s1):
    return z3.Sum([z3.If(a[(ord(s0) * 256 + ord(s1)) // j % n], 1, 0) for j in range(1, k + 1)]) == c
solver = z3.Solver()
solver.add(a[0])
for s0, s1 in ['AI', 'AG', 'AU', 'BS', 'BD', 'BB', 'BM', 'BT', 'BW', 'VG', 'BN', 'KY', 'CX', 'CC', 'CK', 'CY', 'DM', 'FK', 'FJ', 'GD', 'GG', 'GY', 'HK', 'IN', 'ID', 'IE', 'IM', 'JM', 'JP', 'JE', 'KE', 'KI', 'LS', 'MO', 'MW', 'MY', 'MV', 'MT', 'MU', 'MS', 'MZ', 'NA', 'NR', 'NP', 'NZ', 'NU', 'NF', 'PK', 'PG', 'PN', 'SH', 'KN', 'LC', 'VC', 'WS', 'SC', 'SG', 'SB', 'SO', 'ZA', 'GS', 'LK', 'SR', 'SZ', 'TH', 'TL', 'TK', 'TO', 'TT', 'TC', 'TV', 'UG', 'GB', 'TZ', 'VI', 'ZM', 'ZW']:
    solver.add(f(s0, s1))
for s0, s1 in ['AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AQ', 'AR', 'AM', 'AW', 'AT', 'AZ', 'BH', 'BY', 'BE', 'BZ', 'BJ', 'BO', 'BA', 'BV', 'BR', 'IO', 'BG', 'BF', 'BI', 'CV', 'KH', 'CM', 'CA', 'CF', 'TD', 'CL', 'CN', 'CO', 'KM', 'CG', 'CR', 'CI', 'HR', 'CU', 'CW', 'CZ', 'KP', 'CD', 'DK', 'DJ', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FO', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GP', 'GU', 'GT', 'GW', 'GN', 'HT', 'HM', 'VA', 'HN', 'HU', 'IS', 'IR', 'IQ', 'IL', 'IT', 'JO', 'KZ', 'KW', 'KG', 'LA', 'LV', 'LB', 'LR', 'LY', 'LI', 'LT', 'LU', 'MG', 'ML', 'MH', 'MQ', 'MR', 'YT', 'MX', 'FM', 'MC', 'MN', 'ME', 'MA', 'MM', 'NL', 'NC', 'NI', 'NG', 'NE', 'MP', 'NO', 'OM', 'PW', 'PA', 'PY', 'PE', 'PH', 'PL', 'PT', 'PR', 'QA', 'KR', 'MD', 'RE', 'RO', 'RU', 'RW', 'BL', 'MF', 'PM', 'SM', 'ST', 'SA', 'SN', 'RS', 'SL', 'BQ', 'SX', 'SK', 'SI', 'SS', 'ES', 'PS', 'SD', 'SJ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'MK', 'TG', 'TN', 'TR', 'TM', 'UA', 'AE', 'UM', 'US', 'UY', 'UZ', 'VU', 'VE', 'VN', 'WF', 'EH', 'YE']:
    solver.add(z3.Not(f(s0, s1)))
res = solver.check()
print(res)
if res == z3.sat:
    m = solver.model()
    print('n={} k={} c={} a={!r}'.format(n, k, c, binascii.unhexlify('{:0{}x}'.format(
        int(''.join('01'[z3.is_true(m[x])] for x in a), 2), n // 8 * 2))))

```

# Answer
> 2 votes
# APL (Dyalog), 108 bytes

```
1∊⍷∘'TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ'

```

Try it online!

Using the lookup string by ovs.

Left-handed traffic = `1`.
Right-handed traffic = `0`.

# Answer
> 2 votes
# Javascript (ES6), ~~118~~ 116 bytes

Saved 2 bytes thanks to @Craig Ayre

```
s=>"SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ".match(s)

```

Returns `null` for right-handed traffic

## Test Cases

```
f=s=>"SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ".match(s)

console.log("AI,AG,AU,BS,BD,BB,BM,BT,BW,VG,BN,KY,CX,CC,CK,CY,DM,FK,FJ,GD,GG,GY,HK,IN,ID,IE,IM,JM,JP,JE,KE,KI,LS,MO,MW,MY,MV,MT,MU,MS,MZ,NA,NR,NP,NZ,NU,NF,PK,PG,PN,SH,KN,LC,VC,WS,SC,SG,SB,SO,ZA,GS,LK,SR,SZ,TH,TL,TK,TO,TT,TC,TV,UG,GB,TZ,VI,ZM,ZW".split`,`.every(s=>f(s)!=null))
console.log("AF,AX,AL,DZ,AS,AD,AO,AQ,AR,AM,AW,AT,AZ,BH,BY,BE,BZ,BJ,BO,BA,BV,BR,IO,BG,BF,BI,CV,KH,CM,CA,CF,TD,CL,CN,CO,KM,CG,CR,CI,HR,CU,CW,CZ,KP,CD,DK,DJ,DO,EC,EG,SV,GQ,ER,EE,ET,FO,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GP,GU,GT,GW,GN,HT,HM,VA,HN,HU,IS,IR,IQ,IL,IT,JO,KZ,KW,KG,LA,LV,LB,LR,LY,LI,LT,LU,MG,ML,MH,MQ,MR,YT,MX,FM,MC,MN,ME,MA,MM,NL,NC,NI,NG,NE,MP,NO,OM,PW,PA,PY,PE,PH,PL,PT,PR,QA,KR,MD,RE,RO,RU,RW,BL,MF,PM,SM,ST,SA,SN,RS,SL,BQ,SX,SK,SI,SS,ES,PS,SD,SJ,SE,CH,SY,TW,TJ,MK,TG,TN,TR,TM,UA,AE,UM,US,UY,UZ,VU,VE,VN,WF,EH,YE".split`,`.every(s=>f(s)==null))
```

# Answer
> 2 votes
**K, 105 bytes**

For information about K/Q languages see code.kx.com

Use: Country-code (2-char string, example "XY") after

```
in[;+\-48+5h$"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"]@26/:-65+5h$

```

Generates `1b` (Left-handed traffic) or `0b` (not Left-handed traffic)

Explanation:

* `5h$"XX"` generates ascii codes for each char of the 2-char string (country-code), Example `5h$"TB"` generates 84 66
* `-65+integerList` substract 65 to each integer in the list. Example `-65+5h$"TB"` generates 19 1
* `26/:integerList` computes integer equivalent to that list as digits in 26-base. Example `26/:-65+5h$"TB"` generates 495 (country-code as integer)
* `in[;listOfCountryCodesAsIntegers]@x` returns boolean value (1b = true, 0b = false). True if x is in the list
* `+\-48+5h$"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"` calculates list of integers for each country code with Left-handed traffic

+ `"62<729151368=1>a1A23<6<C181A83?45;488F411112115:235Q43r141738353135247F42Tl<:"` is the 'distance string' (distance between each pair of integer-country-codes in ascending order, codified as char). Distance n is codified as ascii char 48+n
    + `-48+5h$".."` calculates ascii value of each char in string ".." and recover original distance as ascii-code - 48. The result is the list of distances
    + `+\integerList` calculates partial summation of items from the list -\> absolute integer-country-codes from distances between codes.

NOTES.-

* Returns `0b` for any non-left-handed country-code, including not valid country codes
* We can save a char reformatting the code, but requires to write country-code "XX" inside the code (i don't know if it's valid, but i'm quite sure it's not elegant) `in[26/:-65+5h$"XX";+\-48+5h$"..."]`

# Answer
> 1 votes
# Vim, ~~117~~ ~~109~~ 108 keystrokes

```
oSZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ␛kg*D

```

Try it online! (replace `SE` in the header with the country code)

is the escape key. The program prints the following text for right-handed traffic:

```

SZAINAGGDMOAUGBBSCCKIMWSHKYLSBMVGSGYBDBTHBWBNRMZMTLCXSRTVCYPNFKNPKEFJMYVIDIEJPGJEMUNZWMSONULKTKTOTTCTZ

```

## Explanation

```
oSZAINA...OTTCTZ␛ Input the lookup-string on a new line
kg*D              Delete the everything after the last occurence of the country code
                   on the same line

```

# Answer
> 1 votes
# MY-BASIC, 162 bytes

Anonymous Function that takes input as an unwrapped string (that is, without parenthesis) and outputs to the console

```
Input"",x$,
For y=0 To 100
z=z+(Mid("TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",y,2)=x$)
Next
Print z

```

Returns `0` for right-handed and `1` for left-handed traffic, try it online!

# Answer
> 1 votes
# Yabasic, 127 bytes

Anonymous function that takes input as an unwrapped string (no `"..."`) and outputs `0` if the Country is right-handed and `1` if the country is left handed.

```
Input""A$
?InStr("TTHSZWMSGSONPKNZMWVIDFKELSCYJPNFJMTVCXBNRBWSHKYAUGGYBTLCCKIMVGBSBBMZAINAGDMOBDIEJEMYMUNUPGSRLKTKTOTCTZ",A$)>0

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~115~~ 107 bytes

```
f(short*x){x=!wcschr(L"䥁䝁啁卂䑂䉂䵂呂坂䝖乂奋塃䍃䭃奃䵄䭆䩆䑇䝇奇䭈义䑉䕉䵉䵊偊䕊䕋䥋卌位坍奍噍呍啍卍婍䅎剎偎婎啎䙎䭐䝐乐䡓之䍌䍖南䍓䝓䉓体䅚升䭌剓婓䡔䱔䭔佔呔䍔噔䝕䉇婔䥖䵚坚",*x);}

```

Try it online!

Returns `0` if left handed. -4 thanks to @JonathanFrech

# Answer
> 1 votes
# Vyxal `r`, 65 bytes

```
⇩«°ǎ+₃∧M⋏⁼•¼¾E⇧M∪∵IḞ½ð∷⅛ḃxṀ⌊ż‹←∵o8ƒ₈£…₌⌈⋏L⟑₇₌±M…uġεƛǏ∆%zKɾ\@(L-«c

```

Try it Online!

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


# Question
Title: All in all it's just, uh, another trick in code golf
The purpose of this challenge is to produce an ASCII version of the cover of this great album by the rock band Pink Floyd.

The brick junctions are made of characters `_` and `|`. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is:

```
_________
|       |
|       |
_________

```

Each row of bricks is **offset by half a brick width** (4 chars) with respect to the previous row:

```
________________________________________
  |       |       |       |       |
  |       |       |       |       |
________________________________________
      |       |       |       |       |
      |       |       |       |       |
________________________________________
  |       |       |       |       |
  |       |       |       |       |

```

The wall is **parameterized** as follows. All parameters are measured in chars including junctions:

1. **Horizontal offset** of first row, `F`. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are `0`, `1`, ..., `7`.
2. Total **width**, `W`. This includes junctions. Its value is a positive integer.
3. Total **height**, `H`. This includes junctions. Its value is a positive integer.

The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of `3`). For example, here's the output for `6`, `44`, `11`:

```
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

```

and a visual explanation of parameters:

```
          F=6
         ......
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
H=11 .     |       |       |       |       |       |
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |

         ............................................
                             W=44

```

## Additional rules

You may provide a program or a function.

Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings.

Trailing spaces or newlines are allowed.

Shortest code in bytes wins.

## Test cases

Inputs are in the order given above, that is: horizontal offset of first row, total width, total height.

```
6, 44, 11:
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

2, 20, 10:
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

1, 1, 1:
_

1, 2, 3:
__
 |
 |

3, 80, 21:
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |

```

# Answer
> 17 votes
# Pyth, ~~43~~ 27 bytes

I ***need*** to golf it heavily... the score is too shameful.

```
AQVE<*H?%N3X*8d+G*4/N3\|\_H

```

Try it online already.

### Input format

```
6,44
11

```

### Output format

```
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

```

## Explanation

```
AQVE<*H?%N3X*8d+G*4/N3\|\_H   First two inputs as list in Q,
                              third input as E.

AQ                            Assign G to the first item in Q
                              and H to the second item in Q.
  VE                          For N from 0 to E-1:
                   /N3            N floor-div 3.
                                    if N gives a remainder of 3 or 4 or 5
                                    when divided by 6, this will be odd;
                                    otherwise, this will be even.
                 *4               Multiply by 4.
                                    if the above is odd, this will leave
                                    a remainder of 4 when divided by 8;
                                    otherwise, the remainder would be 0.
               +G                 Add G (as an offset).
           X*8d       \|          In the string "        " (*8d),
                                  replace (X) the character with the
                                  index above with "|" (modular indexing,
                                  hence the manipulation above).
       ?%N3             \_        If N%3 is non-zero, use the above;
                                  otherwise, use "_".
     *H                           The above repeated H times.
    <                     H       Take the first H characters of above.
                                  Implicitly print with newline.

```

# Answer
> 30 votes
# C, 86 85 83 82 bytes

3 bytes saved thanks to Lynn.
1 byte saved thanks to charlie.

```
i;f(o,w,h){++w;for(i=0;++i<w*h;)putchar(i%w?i/w%3?i%w+i/w/3*4+~o&7?32:124:95:10);}

```

# Answer
> 26 votes
# C, 92 bytes

```
b(f,w,h,y,x){for(y=0;y<h;y++,puts(""))for(x=0;x<w;x++)putchar(y%3?(x+y/3*4-f)%8?32:124:95);}

```

Invoke as `b(F, W, H)`.

# Answer
> 13 votes
# Perl, 63 bytes

```
#!perl -nl
$y+=print+map$y%3?$_++-$`&7?$":'|':_,($y%6&4)x$&for/ \d+/..$'

```

Counting the shebang as 2, input is taken from stdin, whitespace separated.

**Sample Usage**

```
$ echo 2 20 10 | perl bricks.pl
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

```

# Answer
> 11 votes
## Haskell, 83 bytes

```
q s="_":[s,s]
(f!w)h=take h$cycle$take w.drop(7-f).cycle<$>q"       |"++q"   |    "

```

This defines a ternary infix function `!` which returns a list of strings. Usage example:

```
*Main> putStrLn $ unlines $ (3!14) 7
______________
   |       |
   |       |
______________
       |
       |
______________

```

How it works:

```
            q"       |"++q"   |    "  -- build a list of 6 strings
                                      --   1:     "_"
                                      --   2:     "       |"
                                      --   3:     "       |"
                                      --   4:     "_"
                                      --   5:     "   |    "
                                      --   6:     "   |    "
         <$>                          -- for each of the strings
     take w.drop(7-f).cycle           -- repeat infinitely, drop the first 7-f chars
                                      --    and take the next w chars
  cycle                               -- infinitely repeat the resulting list
take h                                -- and take the first h elements

```

# Answer
> 10 votes
## JavaScript (ES6), ~~96~~ 95 bytes

```
g=
(f,w,h)=>[...Array(h)].map((_,i)=>(i%3?`       |`:`_`).repeat(w+7).substr(f^7^i%6&4,w)).join`
`
;
```

```
<div onchange=o.textContent=g(f.value,w.value,+h.value)><input id=f type=number min=0 max=7 placeholder=Offset><input id=w type=number min=0 placeholder=Width><input id=h type=number min=0 placeholder=Height></div><pre id=o>
```

Explanation: Creates a string of either the repeating 7 spaces plus `|` pattern or just repeated `_`s, but at least long enough to be able to extract the `w` characters required for each row. The first three rows start at position `f^7` and then the next three rows start at position `f^3`, so I achieve this by ~~toggling bit 2 of `f` on every third row~~ using the opposite bit 2 on the last two rows of each block of 6 for a saving of 1 byte.

# Answer
> 7 votes
# Python 2, ~~93~~ 88 bytes

~~2nd indentation level is tab~~ Saving some bytes thanks to Leaky Nun and some own modifications, also now correct offset:

```
def f(F,W,H):
 for h in range(H):print["_"*W,((("|"+7*" ")*W)[8-F+h%6/3*4:])[:W]][h%3>0]

```

previous code:

```
def f(F,W,H,x="|"+7*" "):
 for h in range(H):
    print ["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]

```

Same length as unnamed lambda:

```
lambda F,W,H,x="|"+7*" ":"\n".join(["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]for h in range(H))

```

# Answer
> 7 votes
# MATL, ~~42~~ ~~36~~ 33 bytes

```
:-Q'_ | |'[DClCl]Y"8et4YShwi:3$)!

```

Input format is: `nCols`, `offset`, `nRows`

**Try it Online**

The approach here is that we setup a "template" which we then index into by using the row indices (`[1 2 ... nRows]`) and column indices shifted by the first input (`[1 2 ... nCols] - shift`). Thanks to MATL's modular indexing, it will automatically result in a tiled output. As a side-note, to save some space, technically I work with a transposed version of the template and then just take a transpose (`!`) at the end.

The template is this:

```
________
       |
       |
________
  |
  |

```

# Answer
> 6 votes
# QBasic, ~~121~~ 109 bytes

## (Tested on QB64)

Thanks to @DLosc for golfing my `IF` statement with a mathematical equivalent. That was worth 12 bytes.

## General Method:

Loop through each cell one at a time and determine whether it should be a `_`, , or `|` depending on its location. `MOD` statements and boolean logic are used to determine brick boundaries and how much to stagger the bricks.

## Code:

```
INPUT F,W,H
FOR y=0TO H-1:FOR x=0TO W-1
?CHR$((y MOD 3>0)*(((x-(y MOD 6>3)*4)MOD 8=F)*92+63)+95);
NEXT:?:NEXT

```

## Usage Note:

QBasic expects input to be numbers separated by commas.

# Answer
> 5 votes
# Java, ~~149~~, ~~147~~, ~~146~~, 143 bytes

Golfed:

```
String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;}

```

Ungolfed:

```
public class AllInAllItsJustUhAnotherTrickInCodeGolf {

  public static void main(String[] args) {
    int offset = 6;
    int width = 44;
    int height = 11;
    System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf()
        .f(offset, width, height));
  }

  // Begin golf
  String f(int o, int w, int h) {
    String s = "";
    for (int y = 0, x; y < h; ++y) {
      for (x = 0; x < w; ++x) {
        s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_';
      }
      s += '\n';
    }
    return s;
  }
  // End golf

}

```

# Answer
> 4 votes
# Julia: ~~150~~ ~~128~~ ~~116~~ ~~108~~ 107 bytes

```
# in codegolf.jl
r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...)

```

to run with arguments: `julia -e 'o=2;h=18;w=40;include("codegolf.jl")'`

If you feel calling from bash is cheating and you want a function inside the interpreter, then the function version is 117 bytes :)

```
f(o,h,w)=(r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...))

```

demo

(Thanks, @glen-o for the extra byte-saving tip!)

# Answer
> 4 votes
# Ruby, ~~72~~ 66 bytes

```
->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}}

```

Thanks @Value Ink for 6 bytes!

Simple string multiplication and slicing.

Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error).

# Answer
> 3 votes
## JavaScript, ~~172~~ ~~168~~ ~~165~~ ~~157~~ ~~147~~ ~~142~~ 137 bytes

```
(O,W,H)=>{t='_'.repeat(W),x='|       '.repeat(W),f=t+`
`;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+`
`;return f}

```

```
N = (O,W,H)=>{t='_'.repeat(W),x='|       '.repeat(W),f=t+`
`;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+`
`;return f}

let test_data = [[6,44,11],
                 [2,20,10],
                 [1,1,1],
                 [1,2,3],
                 [3,80,21]];

for (test of test_data)
    console.log(N(...test));
```

# Answer
> 3 votes
# Dyalog APL, 29 bytes

`↑⎕⍴⎕⍴¨a,4⌽¨a←'_',2⍴⊂⌽⎕⌽¯8↑'|'`

tests: `6 44 11`, `2 20 10`, `1 1 1`, `1 2 3`, `3 80 21`

is evaluated input; as the expression executes from right to left, it prompts for `F`, `W`, and `H` in that order

`¯8↑'|'` is `' |'`

`⎕⌽` is rotate, it chops F chars from the front and puts them at the end of the string

the other  means reverse

`'_',2⍴⊂` creates a 3-tuple of '\_' followed by two separate copies of the string so far

`a,4⌽¨a←` append the 4-rotation of everything so far, we end up with a 6-tuple

`⎕⍴¨` reshape each element to the width

`⎕⍴` reshape to the height

mix vector of vectors into a matrix

# Answer
> 3 votes
# 05AB1E, ~~25~~ ~~24~~ 23 bytes

```
'_'|7úD)³∍ε73N3÷è¹-._²∍

```

-1 byte thanks to *@Grimmy*.

Inputs in the order \\$\text{offset}, \text{width}, \text{height}\\$.
Output as a list of string-lines.

Try it online or verify all test cases.

**Explanation:**

```
'_           '# Push "_"
'|           '# Push "|"
  7ú          # Pad 7 leading spaces: "       |"
    D         # Duplicate it
     )        # Wrap all three values on the stack into a list
³∍            # Extend this list to the (third) input-height amount of lines
              #  i.e. height=7 → ["_","       |","       |","_","       |","       |","_"]
ε             # Map over each line:
   N          #  Push the (0-based) map-index
    3÷        #  Integer-divide it by 3
 73   è       #  Index it into 73 (0-based and with wraparound)
              #   i.e. indices=[0,1,2,3,4,5,6,7,...] → [7,7,7,3,3,3,7,7,...]
       ¹+     #  Subtract the (first) input-offset
              #   i.e. offset=6 → [-3,-3,-3,1,1,1,-3,-3,...]
         ._   #  Rotate the string that many times towards the left
              #   i.e. ["_","       |","       |","_","       |","       |","_"] and
              #     [-3,-3,-3,1,1,1,-3] → ["_","      | ","      | ","_","  |     ","  |     ","_"]
           ²∍ #  After this inner loop: push the (second) input-width
              #  Extend/shorten the line to a size equal to the (second) input-width
              #   i.e. width=5 and line="   |    " → "   | "
              #   i.e. width=20 and line="   |    " → "   |       |       |"
              #   i.e. width=5 and line="_" → "_____"
              #   i.e. width=20 and line="_" → "____________________"
              # (after which the list of string-lines is output implicitly as result)

```

`73N3÷è` could alternatively be `₃€ÐÍNè` for the same byte-count:

Try it online or verify all test cases.

```
 ₃            #  Push builtin 95
  €Ð          #  Triplicate each digit: [9,9,9,5,5,5]
    Í         #  Decrease each by 2: [7,7,7,3,3,3]
     Nè       #  Index the (0-based) map-index into this (0-based and with wraparound)

```

# Answer
> 2 votes
# Actually, ~~44~~ ~~43~~ 40 bytes

This is an Actually port of the algorithm in Neil's JS answer. Golfing suggestions welcome. Try it online!

```
╗╝r⌠;6(%4&╜7^^╛'|7" "*+*t╛@H╛'_*3(%YI⌡Mi

```

**Ungolfing:**

```
          Takes implicit input in the order h, w, f.
╗╝        Save f to register 0. Save w to register 1.
r⌠...⌡M   Map over range [0..h-1]. Call this variable i.
  ;         Duplicate i
  6(%       i%6...
  4&        ...&4
  ╜7^^      ...^i^7. Call it c.
  ╛         Push w.
  '|7" "*+  The string "       |"
  *t╛@H     (("       |" * w)[c:])[:w]
  ╛'_*      Push "_" * w
  3(%       Push 3, move duplicate i to TOS, mod.
  YI        If not i%3, take "_"*w, else (("       |" * w)[c:])[:w]
            Function ends here.
i         Flatten the resulting list and print the bricks implicitly.

```

# Answer
> 2 votes
# PowerShell, ~~101~~ 88 bytes

```
param($n,$w,$h)0..--$h|%{(('|       '*$w|% S*g(8-$n+4*($_%6-gt3))$w),('_'*$w))[!($_%3)]}

```

Try it online!

# Answer
> 2 votes
# Vyxal, 30 bytes

```
(n₃[¹\_*,|7\|꘍¹*⁰ǔǔn3ḭ∷[4ǔ]¹Ẏ,

```

Try it Online!

A big mess.

```
(                              # (height) times (to make each row)
 n₃[                           # If the iteration is divisible by 3 (flat row) then...
    ¹\_*,                      # (width) underscores
         |                     # Else (part of a brick)...
          7\|꘍                 # Prepend seven spaces to an underscore
              ¹*               # Repeat (width) times
                ⁰ǔǔ            # Cycle by (offset), then cycle once more
                   n3ḭ∷[  ]    # If it's an offset row
                        4ǔ     # Cycle once more
                           ¹Ẏ, # Trim to the correct length and print.

```

# Answer
> 1 votes
# Octave ~~80~~ 76 bytes

```
% in file codegolf.m
c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;char(repmat(c+32,h,w)(1:h,o+1:o+w))

```

to run from terminal: `octave --eval "o=2;h=18;w=44; codegolf"`

(alternatively, if you think the terminal call is cheating :p then an anonymous function implementation takes 86 bytes :)

```
c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;f=@(o,h,w)char(repmat(c+32,h,w)(1:h,o+1:o+w))

```

Call `f(2,18,44)` at the octave interpreter.

# Answer
> 1 votes
# Bash + Sed, ~~411~~ ~~395~~ ~~381~~ 370 bytes:

```
F=`printf '_%.s' $(eval echo {1..$2})`;V="       |";(($[($2-$1)/8]>0))&&L=`printf "$V%.s" $(eval echo {1..$[($2-$1)/8]})`||L=;Z=`printf "%$1.s|%s\n" e "$L"`;I=$[($2-(${#Z}-4))/8];(($I>0))&&W=`printf "$V%.s" $(eval echo {1..$I})`||W=;J=${Z:4}$W;for i in `eval echo {1..$[$3/3+1]}`;{ (($[$i%2]<1))&&O+="$F\n$J\n$J\n"||O+="$F\n$Z\n$Z\n";};echo "`echo -e "$O"|sed -n 1,$3p`"

```

Well, here is my very first answer in Bash, or any shell scripting language for that matter. This is also by far the longest answer here. Takes in a sequence of space-separated command line arguments in the format `Offset Width Height`. This can probably be a lot shorter than it currently is, so any tips and/or tricks for golfing this down more are appreciated.

# Answer
> 1 votes
## Delphi/Object Pascal, 305, 302, 292 bytes

Full console program that reads 3 parameters.

```
uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end.

```

### ungolfed

```
uses
  SySutils,
  Math;
var
  i,q,o,w,h:byte;
begin
  o:=StrToInt(paramstr(1));
  w:=StrToInt(paramstr(2));
  h:=StrToInt(paramstr(3));

  for q := 0 to h-1 do
  begin
    for i := 1 to w do
      if q mod 3 = 0  then
        Write('_')
      else
        if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then
          Write('|')
        else Write(' ');
    Writeln('');
  end
end.

```

Sadly, Delphi does not have a ternary operator and it is quite a verbose language.

### test case

```
D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

```

Edit: Could shave of 3 bytes by using byte as type for all variables.

Edit 2: And console applications do not *need* the program declaration, -10

# Answer
> 1 votes
# JavaScript (ES6),  ~~81 78~~  77 bytes

*Saved 3 bytes thanks to @mypronounismonicareinstate*

Takes input as `(F, W)(H)`.

```
(F,W,x=y=0)=>g=H=>y<H?`
|_ `[x++<W?y%3?(x+~F^y/3<<2)&7?3:1:2:x=+!++y]+g(H):''

```

Try it online!

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


title: Generate the shortest De Bruijn

text:
# Question
Title: Generate the shortest De Bruijn
A De Bruijn sequence is interesting: It is the shortest, cyclic sequence that contains all possible sequences of a given alphabet of a given length. For example, if we were considering the alphabet A,B,C and a length of 3, a possible output is:

```
AAABBBCCCABCACCBBAACBCBABAC

```

You will notice that every possible 3-character sequence using the letters `A`, `B`, and `C` are in there.

Your challenge is to generate a De Bruijn sequence in as few characters as possible. Your function should take two parameters, an integer representing the length of the sequences, and a list containing the alphabet. Your output should be the sequence in list form.

You may assume that every item in the alphabet is distinct.

An example generator can be found here

Standard loopholes apply

# Answer
> 6 votes
# Pyth, 31 bytes

This is the direct conversion of the algorithm used in my CJam answer. Tips for golfing welcome!

```
Mu?G}H+GG+G>Hefq<HT>G-lGTUH^GHk

```

This code defines a function `g` which takes two arguments, the string of list of characters and the number.

Example usage:

```
Mu?G}H+GG+G>Hefq<HT>G-lGTUH^GHkg"ABC"3

```

Output:

```
AAABAACABBABCACBACCBBBCBCCC

```

Code expansion:

```
M                 # def g(G,H):
 u                #   return reduce(lambda G, H:
  ?G              #     (G if
    }H            #       (H in
      +GG         #          add(G,G)) else
    +G            #       add(G,
      >H          #         slice_end(H,
        e         #           last_element(
         f        #             Pfilter(lambda T:
          q       #               equal(
           <HT    #                 slice_start(H,T),
           >G     #                 slice_end(G,
             -lGT #                   minus(Plen(G),T))),
          UH      #               urange(H)))))),
  ^GH             #     cartesian_product(G,H),
  k               #     "")

```

Try it here

# Answer
> 4 votes
# CJam, ~~52 49~~ 48 bytes

This is surprisingly long. This can be golfed a lot, taking in tips from the Pyth translation.

```
q~a*{m*:s}*{:H\:G_+\#)GGHH,,{_H<G,@-G>=},W=>+?}*

```

The input goes like

```
3 "ABC"

```

i.e. - String of list of characters and the length.

and output is the De Bruijn string

```
AAABAACABBABCACBACCBBBCBCCC

```

Try it online here

# Answer
> 3 votes
# CJam, ~~52~~ 49 bytes

Here is a different approach in CJam:

```
l~:N;:L,(:Ma{_N*N<0{;)_!}g(+_0a=!}g]{,N\%!},:~Lf=

```

Takes input like this:

```
"ABC" 3

```

and produces a Lyndon work like

```
CCCBCCACBBCBACABCAABBBABAAA

```

Try it here.

This makes use of the relation with Lyndon words. It generates all Lyndon words of length *n* in lexicographic order (as outlined in that Wikipedia article), then drops those whose length doesn't divide *n*. This already yields the De Bruijn sequence, but since I'm generating the Lyndon words as strings of digits, I also need to replace those with the corresponding letters at the end.

For golfing reasons, I consider the later letters in the alphabet to have lower lexicographic order.

# Answer
> 2 votes
# Jelly, 15 bytes

```
ṁL*¥Œ!;`wⱮẠɗƇṗḢ

```

Try it online!

Pretty slow, uses a brute force approach with around an \\$O(n \times m \times (n \times m)!)\\$ complexity, where \\$n\\$ is the integer input and \\$m\\$ is the length of the string. Times out if both \\$n\\$ and \\$m\\$ are greater than 3 on TIO

## How it works

The length of the De Bruijn sequence will always be \\$m^n\\$ and each symbol in the provided alphabet will occur the same number of times, \\$m^{n-1}\\$. Therefore, we generate the string with that many symbols, then filter its permutations to find valid De Bruijn sequences.

```
ṁL*¥Œ!ẋ2wⱮẠʋƇṗḢ - Main link. Takes an alphabet A on the left and n on the right
   ¥            - Last 2 links as a dyad f(A, n):
 L              -   Length of A
  *             -   Raised to the power n
ṁ               - Mold A to that length
    Œ!          - All permutations
             ṗ  - Powerset; Get all length n combinations of A. Call that C
           ʋƇ   - Filter the permutations P on the following dyad g(P, C):
      ẋ2        -   Repeat P twice
         Ɱ      -   For each element E in C:
        w       -     Is it a sublist of P?
          Ạ     -   Is this true for all elements of C?
              Ḣ - Take the first one

```

# Answer
> 1 votes
# JavaScript (ES6) 143

Using Lyndon words, like Martin's aswer, just 3 times long...

```
F=(a,n)=>{
  for(w=[-a[l='length']],r='';w[0];)
  {
    n%w[l]||w.map(x=>r+=a[~x]);
    for(;w.push(...w)<=n;);
    for(w[l]=n;!~(z=w.pop()););
    w.push(z+1)
  }
  return r
}

```

**Test** In FireFox/FireBug console

```
console.log(F("ABC",3),F("10",4))

```

*Output*

```
CCCBCCACBBCBACABCAABBBABAAA 0000100110101111

```

# Answer
> 1 votes
# Python 2, 114 bytes

I'm not really sure how to golf it more, due to my approach.

```
def f(a,n):
 s=a[-1]*n
 while 1:
    for c in a:
     if((s+c)[len(s+c)-n:]in s)<1:s+=c;break
    else:break
 print s[:1-n]

```

**Try it online**

**Ungolfed:**

This code is a trivial modification from my solution to more recent challenge.

```
def f(a,n):
    s=a[-1]*n
    while 1:
        for c in a:
            p=s+c
            if p[len(p)-n:]in s:
                continue
            else:
                s=p
                break
        else:
            break
    print s[:1-n]

```

The only reason `[:1-n]` is needed is because the sequence includes the wrap-around.

# Answer
> 1 votes
# Powershell, ~~164~~ 96 bytes

*-68 bytes with -match `O($n*2^n)` instead recursive generator `O(n*log(n))`*

```
param($s,$n)for(;$z=$s|% t*y|?{"$($s[-1])"*($n-1)+$x-notmatch-join"$x$_"[-$n..-1]}){$x+=$z[0]}$x

```

Ungolfed & test script:

```
$f = {

param($s,$n)                    # $s is a alphabet, $n is a subsequence length
for(;                           # repeat until...
    $z=$s|% t*y|?{              # at least a character from the alphabet returns $true for expression:
        "$($s[-1])"*($n-1)+$x-notmatch  # the old sequence that follows two characters (the last letter from the alphabet) not contains
        -join"$x$_"[-$n..-1]    # n last characters from the new sequence
}){
    $x+=$z[0]                   # replace old sequence with new sequence
}
$x                              # return the sequence

}

@(
    ,("ABC",  2, "AABACBBCC")
    ,("ABC",  3, "AAABAACABBABCACBACCBBBCBCCC")
    ,("ABC",  4, "AAAABAAACAABBAABCAACBAACCABABACABBBABBCABCBABCCACACBBACBCACCBACCCBBBBCBBCCBCBCCCC")
    ,("ABC",  5, "AAAAABAAAACAAABBAAABCAAACBAAACCAABABAABACAABBBAABBCAABCBAABCCAACABAACACAACBBAACBCAACCBAACCCABABBABABCABACBABACCABBACABBBBABBBCABBCBABBCCABCACABCBBABCBCABCCBABCCCACACBACACCACBBBACBBCACBCBACBCCACCBBACCBCACCCBACCCCBBBBBCBBBCCBBCBCBBCCCBCBCCBCCCCC")
    ,("ABC",  6, "AAAAAABAAAAACAAAABBAAAABCAAAACBAAAACCAAABABAAABACAAABBBAAABBCAAABCBAAABCCAAACABAAACACAAACBBAAACBCAAACCBAAACCCAABAABAACAABABBAABABCAABACBAABACCAABBABAABBACAABBBBAABBBCAABBCBAABBCCAABCABAABCACAABCBBAABCBCAABCCBAABCCCAACAACABBAACABCAACACBAACACCAACBABAACBACAACBBBAACBBCAACBCBAACBCCAACCABAACCACAACCBBAACCBCAACCCBAACCCCABABABACABABBBABABBCABABCBABABCCABACACABACBBABACBCABACCBABACCCABBABBABCABBACBABBACCABBBACABBBBBABBBBCABBBCBABBBCCABBCACABBCBBABBCBCABBCCBABBCCCABCABCACBABCACCABCBACABCBBBABCBBCABCBCBABCBCCABCCACABCCBBABCCBCABCCCBABCCCCACACACBBACACBCACACCBACACCCACBACBACCACBBBBACBBBCACBBCBACBBCCACBCBBACBCBCACBCCBACBCCCACCACCBBBACCBBCACCBCBACCBCCACCCBBACCCBCACCCCBACCCCCBBBBBBCBBBBCCBBBCBCBBBCCCBBCBBCBCCBBCCBCBBCCCCBCBCBCCCBCCBCCCCCC")
    ,("01",   3, "00010111")
    ,("01",   4, "0000100110101111")
    ,("abcd", 2, "aabacadbbcbdccdd")
    ,("0123456789", 3, "0001002003004005006007008009011012013014015016017018019021022023024025026027028029031032033034035036037038039041042043044045046047048049051052053054055056057058059061062063064065066067068069071072073074075076077078079081082083084085086087088089091092093094095096097098099111211311411511611711811912212312412512612712812913213313413513613713813914214314414514614714814915215315415515615715815916216316416516616716816917217317417517617717817918218318418518618718818919219319419519619719819922232242252262272282292332342352362372382392432442452462472482492532542552562572582592632642652662672682692732742752762772782792832842852862872882892932942952962972982993334335336337338339344345346347348349354355356357358359364365366367368369374375376377378379384385386387388389394395396397398399444544644744844945545645745845946546646746846947547647747847948548648748848949549649749849955565575585595665675685695765775785795865875885895965975985996667668669677678679687688689697698699777877978878979879988898999")
    ,("9876543210", 3, "9998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888788688588488388288188087787687587487387287187086786686586486386286186085785685585485385285185084784684584484384284184083783683583483383283183082782682582482382282182081781681581481381281181080780680580480380280180077767757747737727717707667657647637627617607567557547537527517507467457447437427417407367357347337327317307267257247237227217207167157147137127117107067057047037027017006665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555455355255155054454354254154053453353253153052452352252152051451351251151050450350250150044434424414404334324314304234224214204134124114104034024014003332331330322321320312311310302301300222122021121020120011101000")
) |% {
    $s,$n,$e = $_
    $r = &$f $s $n
    "$($r-eq$e): $r"
}

```

Output:

```
True: AABACBBCC
True: AAABAACABBABCACBACCBBBCBCCC
True: AAAABAAACAABBAABCAACBAACCABABACABBBABBCABCBABCCACACBBACBCACCBACCCBBBBCBBCCBCBCCCC
True: AAAAABAAAACAAABBAAABCAAACBAAACCAABABAABACAABBBAABBCAABCBAABCCAACABAACACAACBBAACBCAACCBAACCCABABBABABCABACBABACCABBACABBBBABBBCABBCBABBCCABCACABCBBABCBCABCCBABCCCACACBACACCACBBBACBBCACBCBACBCCACCBBACCBCACCCBACCCCBBBBBCBBBCCBBCBCBBCCCBCBCCBCCCCC
True: AAAAAABAAAAACAAAABBAAAABCAAAACBAAAACCAAABABAAABACAAABBBAAABBCAAABCBAAABCCAAACABAAACACAAACBBAAACBCAAACCBAAACCCAABAABAACAABABBAABABCAABACBAABACCAABBABAABBACAABBBBAABBBCAABBCBAABBCCAABCABAABCACAABCBBAABCBCAABCCBAABCCCAACAACABBAACABCAACACBAACACCAACBABAACBACAACBBBAACBBCAACBCBAACBCCAACCABAACCACAACCBBAACCBCAACCCBAACCCCABABABACABABBBABABBCABABCBABABCCABACACABACBBABACBCABACCBABACCCABBABBABCABBACBABBACCABBBACABBBBBABBBBCABBBCBABBBCCABBCACABBCBBABBCBCABBCCBABBCCCABCABCACBABCACCABCBACABCBBBABCBBCABCBCBABCBCCABCCACABCCBBABCCBCABCCCBABCCCCACACACBBACACBCACACCBACACCCACBACBACCACBBBBACBBBCACBBCBACBBCCACBCBBACBCBCACBCCBACBCCCACCACCBBBACCBBCACCBCBACCBCCACCCBBACCCBCACCCCBACCCCCBBBBBBCBBBBCCBBBCBCBBBCCCBBCBBCBCCBBCCBCBBCCCCBCBCBCCCBCCBCCCCCC
True: 00010111
True: 0000100110101111
True: aabacadbbcbdccdd
True: 0001002003004005006007008009011012013014015016017018019021022023024025026027028029031032033034035036037038039041042043044045046047048049051052053054055056057058059061062063064065066067068069071072073074075076077078079081082083084085086087088089091092093094095096097098099111211311411511611711811912212312412512612712812913213313413513613713813914214314414514614714814915215315415515615715815916216316416516616716816917217317417517617717817918218318418518618718818919219319419519619719819922232242252262272282292332342352362372382392432442452462472482492532542552562572582592632642652662672682692732742752762772782792832842852862872882892932942952962972982993334335336337338339344345346347348349354355356357358359364365366367368369374375376377378379384385386387388389394395396397398399444544644744844945545645745845946546646746846947547647747847948548648748848949549649749849955565575585595665675685695765775785795865875885895965975985996667668669677678679687688689697698699777877978878979879988898999
True: 9998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888788688588488388288188087787687587487387287187086786686586486386286186085785685585485385285185084784684584484384284184083783683583483383283183082782682582482382282182081781681581481381281181080780680580480380280180077767757747737727717707667657647637627617607567557547537527517507467457447437427417407367357347337327317307267257247237227217207167157147137127117107067057047037027017006665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555455355255155054454354254154053453353253153052452352252152051451351251151050450350250150044434424414404334324314304234224214204134124114104034024014003332331330322321320312311310302301300222122021121020120011101000

```

---

See also: One Ring to rule them all. One String to contain them all

# Answer
> 1 votes
# Python 3, 72 bytes

```
f=lambda a,n:(a[:n]in a[1:])*a[n:]or max((f(c+a,n)for c in{*a}),key=len)

```

Try it online!

---
Tags: code-golf, combinatorics
---