title: Scroll Word's font size selector

text:
# Question
Title: Scroll Word's font size selector
Word's `**A**` and  buttons change the font size according to these rules:

1. The starting font size is 11.
2. If  is pressed when the font size is 1, the size stays 1.
3. The font size changes with 1 point in the range 1 – 12.
4. The font size changes with 2 points in the range 12 – 28.
5. The choices are 28, 36, 48, 72, and 80 in the range 28 – 80.
6. The font size changes with 10 points in the range 80 – 1630.
7. The font size changes with 8 points in the range 1630 – 1638.
8. If `**A**` is pressed when the font size is 1638, the size stays 1638.

### Task

In as few bytes as possible, determine the resulting font size when given a set of button presses in any reasonable format.

### Examples

`[3,-1,2]`, meaning `**A**``**A**``**A**``**A**``**A**`: The result is 18.

Some possible formats are `'^^^v^^'`, `[1 1 1 -1 1 1]`, `[True,True,True,False,True,True]`, `["+","+","+","-","+","+"]`, `"‘‘‘’‘‘"`, `"⛄⛄⛄⛄⛄"`, `111011`, `"CaB"`, etc...

`[2]`: 14

`[-1]`:10

`[13]`:80

`[-11,1]`: 2

`[11,-1]`: 36

`[170,-1]`: 1630

`[2000,-2,100]`: 1638

# Answer
# MATL, ~~49~~ ~~47~~ 45 bytes

```
11: 9:E10+'$*H'o8:163 10*1638v11ihl180h&Ys0))

```

Input format is `[1 1 -1 1 1 -1 -1 -1]` or `[2 -1 2 -3]`, with optional commas.

Try it online! Or verify all test cases.

### Explanation

```
11:         % Push [1 2 ... 11]
9:          % Push [1 2 ... 9]
E10+        % Times 2, plus 10: gives [12 14 ... 28]
'$*H'       % Push this string
o           % Convert to double: gives ASCII codes, that is, [36 48 72]
8:163       % Push [8 9 ... 163]
10*         % Times 10: gives [80 90 ... 1630]
1638        % Push 1638
v           % Concatenate everything into a column vector
11          % Push 11
ih          % Input array and concatenate with 11
l180h       % Push [1 180]
&Ys         % Cumulative sum with limits 1 and 180
0)          % Get last value
)           % Index into column vector of font sizes. Implicitly display

```
> 6 votes

# Answer
# Word VBA, <sub>~~199~~ ~~147~~ ~~126~~ ~~116~~ ~~102~~ ~~100~~ ~~87~~</sub> 85 Bytes

*Why emulate when you can do?!*

Declared function in the `ThisDocument` module that takes input `n` in the form of `Array(true,true,false,true)` and **outputs to the Word font size selector** **`:P`**

**Golfed:**

```
Sub a(n):Set f=Content.Font:For Each i In n
If i Then f.Grow Else f.Shrink
Next:End Sub

```

**Ungolfed:**

```
Sub a(n)
    Set f=ThisDocument.Content.Font
    For Each i In n
        If i Then
            f.Grow
        Else
            f.Shrink
        End if
    Next
    ''  Implicitly output font size to MS Word Font Size Selector
End Sub

```

## .GIF of usage

## Thanks

-21 thanks to @Adám (removed `Selection.WholeStory:` call)

-10 thanks to @Adám (assume clean environment; remove `f.size=11:` call)

-14 thanks to @Adám (cheeky output word font size selector)

-2 thanks to @Adám (bool ParamArray)

-13 for changing `ParamArray n()` to `n` and expecting input as Boolean Array

-2 for moving from a code module to the `ThisDocument` module

## Old Version 114 Bytes

Takes input `n` as a ParamArray, in the form of `true,true,false,true` and outputs word vbe immediates window

```
Sub a(ParamArray n()):Set f=Selection.Font:For Each i In n
If i Then f.Grow Else f.Shrink
Next:Debug.?f.Size:End Sub

```

## Older version, 199 Bytes

Takes input in the form of `170,-4,6,-1` (accepts numbers larger than 1 in magnitude)

```
Sub a(ParamArray n()):Selection.WholeStory:Set f=Selection.Font:f.Size=12:For Each i In n
If i>1 Then
For j=i To 0 Step -1:f.Grow:Next
Else
For j=i To 0:f.Shrink:Next:End If:Next:Debug.?f.Size:End Sub

```
> 46 votes

# Answer
## JavaScript (ES6), ~~103~~ 101 bytes

Takes input as an array of `-1` / `1`.

```
a=>a.map(k=>[1,12,28,36,48,72,80,1630,1638].map((v,i)=>n+=n>v&&k*[1,1,6,4,12,-16,2,-2,-8][i]),n=11)|n

```

### Test

```
let f =

a=>a.map(k=>[1,12,28,36,48,72,80,1630,1638].map((v,i)=>n+=n>v&&k*[1,1,6,4,12,-16,2,-2,-8][i]),n=11)|n

console.log(f([]));
console.log(f([1]));
console.log(f([-1]));
console.log(f([1,1,1,-1,1,1,1,1,1,1,1,1]));
console.log(f(Array(2000).fill(1)));
```

*Saved 2 bytes thanks to ETHproductions*
> 12 votes

# Answer
# Python 2, 111 107 bytes

```
i=10;r=range
for d in input():i+=d*(0<i+d<179)
print(r(1,12)+r(12,29,2)+[36,48,72]+r(80,1631,10)+[1638])[i]

```

Requires input to be in the `[-1, 1, 1, -1, ...]` format. It works with the examples for some bytes extra:

```
for d in input():i=min(max(0,i+d),179)

```
> 9 votes

# Answer
# Octave, ~~93~~ ~~89~~ 87 bytes

The input array can have integers larger than 1 or smaller than -1 to represent multiplicity of action

```
L=11;for k=input(''),L=min(max(L+k,1),180);end;[1:11 [6:14 18 24 36 40:5:815 819]*2](L)

```

Thanks to Adám, Changed language to Octave only to be able to use direct indexing into an array.

Saved 2 bytes thanks to rahnema1.

## Test

On Ideone
> 6 votes

# Answer
# Ruby, 106 bytes

I managed to shave a couple of bytes off the python solution (and it took a while of shaving).

```
->n{[*1..12,*(14..28).step(2),36,48,72,*(80..1630).step(10),1638][n.inject(11){|a,b|[0,179,a+b].sort[1]}]}

```

It's an anonymous function that takes the input in the form of `[1, -1, 1, 1, ...]`. It seems to deal quite well with input in the form `[170,-12]` as well, but I can't guarantee it will work 100% of the time, so I'll play it safe and say it works with `[1, -1, 1, 1, ...]`.

## Tricks I used:

* `[0,179,a+b].sort[1]`: This clamps `a+b` to be between 0 and 179, which are the valid indexes of the font-size array.
* Using the splat operator on ranges converts them into arrays, so the available font sizes is generated from `[*1..12,*(14..28).step(2),36,48,72,*(80..1630).step(10),1638]`. Which is a flat array containing the values from each of the flattened elements:

+ `1..12` is a range from 1 to 12 (inclusive). The splat operator turns it into the values `1, 2, 3, ..., 11, 12`.
    + `(14..28).step(2)` is an enumerator for the given range, where each step goes up by 2. The splat operator turns it into the values `14, 16, 18, ..., 26, 28`.
    + The individual values (`36, 48, 72, 1638`) are all concatenated in their position into the great font-size array.
* I used the `inject`(/`reduce`) method, which uses each element of the input array, while reducing them down into a 'memo' variable (as ruby puts it). I initialise this to 11, and the body of each inject iteration is to set this memo variable to the result of adding the current element of the input to the current memo value, and then clamping it between 0 and 180.

All hail the splat operator!
> 4 votes

# Answer
# PHP, 116 bytes

first generates the size index (from 1 to 180 inclusive),
then maps that to the point size and prints the result.

```
for($s=11;$d=$argv[++$i];$s=min($s+$d,180)?:1);echo$s>12?$s>20?$s>23?$s*10-160-2*($s>179):24+(12<<$s-21):$s*2-12:$s;

```

takes `+N` and `-1` from command line arguments.
(`-N` is also accepted; just take care that the size does not hop below zero!)

Run with `-nr`.
> 2 votes

# Answer
# Perl 5, ~~123~~ 106 bytes

```
@a=(1..12,map$_*2,7..14,18,24,36,map$_*5,8..163,163.8);$i=10;$\=$a[$i=($"=$i+$_)<0?0:$">179?179:$"]for@F}{

```

Try it online!

Input format:

```
32 -32 12 4 -2

```
> 1 votes

# Answer
# C (gcc), ~~157~~ 154 bytes

-3 bytes thanks to ceilingcat.

Takes a string of `+` (step up) and non-`+` (step down). Returns the final font size.

```
n,d;f(char*s){for(n=11;*s;n=n>28&n<81?index("\34$0HP",n-d)[2*d-1]:n-d+((n>1&n<29)+(n>12&n<29)+(n>80&n<1639)*8+(n>80&n<1631)*2)*(2*d-1))n+=d=*s++==43;s=n;}

```

Try it online!
> 1 votes

# Answer
# Zsh, 98 bytes

```
a=({1..12} {14..28..2} 36 48 72 {8..163}0 1638)
r=11
for i;((r+=i,r=(r>$#a)?$#a:(r?r:1)))
<<<$a[r]

```

Try it online!

Iterate through the arguments, clamping our index between `1` and `$#a` (length of `$a`).
> 1 votes

---
Tags: code-golf, number, sequence, subsequence
---


title: Count the Shantens

text:
# Question
Title: Count the Shantens
# Introduction to Mahjong tiles

Mahjong (麻雀) is a board game that originates from China. Mahjong tiles used in this challenge are in Unicode points U+1F000 – U+1F021:

```

```

They are categorized as:

* **Winds** (風牌): (East Wind), (South Wind), (West Wind), (North Wind)
* **Dragons** (三元牌): (Red Dragon), (Green Dragon), (White Dragon)
* **Ten Thousands** (萬子): (One of the Ten Thousands) through (Nine of the Ten Thousands)
* **Bamboos** (索子): (One of the Bamboos; note that it depicts a bird) through (Nine of the Bamboos)
* **Circles** (筒子): (One of the Circles) through (Nine of the Circles)
* Winds and Dragons are together called **Honors** (字牌).
* Ten Thousands, Bamboos and Circles are each called a **suit** and together called **Numbers** (数牌). They have **ranks** from 1 to 9.
* Among Numbers, the Ones and the Nines are called **Terminals** (老頭牌). The Twos through the Eights are called **Simples** (中張牌).
* Honors and Terminals are together called **Orphans** (幺九牌).

Every Mahjong tiles have 4 copies of themselves.

# Mahjong Hand

A legal **Hand** consists of:

* A **Head** (対子), which is 2 identical tiles.
* 4 **Bodies** (面子), each which is either:

+ A **Sequence** (順子), which is 3 consecutive Numbers with same suit.
    + A **Triplet** (刻子), which is 3 identical tiles.

Hence, a Hand consists of 14 tiles.

There are exceptional valid Hands. **Seven Heads** (七対子), which is 7 *distinct* Heads, and **Thirteen Orphans** (国士無双), which collects all 13 Orphans with an additional Orphan.

# Tenpais and Shantens

13 Mahjong tiles will be given as the input. If an additional tile would make a valid Hand, this is called **Tenpai** (聽牌). Tenpai is zero Shantens.

If a tile must be exchanged to be Tenpai, this is **1-Shanten** (1向聴).

If a tile must be exchanged to be 1-Shanten, this is **2-Shantens**, and so on.

The objective is to output the number of Shantens.

# Examples

: **Tenpai** waiting for or to make a Sequence. An example of **Two-sided Wait** (兩面待機).

: **Tenpai** waiting for or to make a Triplet. An example of **Wait for a Triplet** (双碰待機).

: **Tenpai** waiting for to make a Sequence. An example of **One-sided Wait** (邊張待機).

: **Tenpai** waiting for to make a Sequence. An example of **Wait for the Middle** (坎張待機).

: **Tenpai** waiting for to make a Head. An example of **Wait for a Head** (單騎待機).

: **Tenpai** waiting for , , or . This example demonstrates how multiple ways of waiting can be combined.

: **Tenpai** waiting for any of Ten Thousands. This is called **Nine Gates** (九蓮宝燈), and has the highest possible number of tiles to wait for to be a "normal" Hand.

: **Tenpai** waiting for to make a Head. An example of Seven Heads.

: **Tenpai** waiting for . An example of Thirteen Orphans.

: **Tenpai** waiting for any of Orphans. Another example of Thirteen Orphans.

: **1-Shanten**. Note that this is not Tenpai waiting for because it would be a fifth .

: **1-Shanten**. Note that this is not Tenpai for Seven Heads because getting will result in a duplicated Head.

: **2-Shantens**.

: **6-Shantens**. This is the highest possible number of Shantens.

You can demonstrate arbitrary examples here. (for 13 or 14 tiles)

# Rules about code golf

* Input type and format doesn't matter, but it must consist of the Unicode characters above. In C++, valid examples include `std::u8string` (sorted or not) , `u32char_t[13]`, and `std::multiset<u32char_t>`.
* Output type and format doesn't matter either.
* Invalid input (not exactly 13 tiles, contains 5 copies of the same tile, contains a character not in U+1F000 – U+1F021, etc) falls into *don't care* situation.

# Answer
# 05AB1E, ~~80~~ ~~77~~ ~~73~~ ~~72~~ ~~77~~ 74 bytes

```
₂Ý8+3ä€ü3€`4иML3δи©«4ã®€¦©âʒ˜D¢à5‹}®7.Æ«8L•1«þï•₆в«D¸â«ε˜•1óñ•+çJœIœδ.L}W<

```

-5 bytes thanks to *@Grimmy*, and also for teaching me about a hidden builtin
+5 bytes to fix two bugs

Brute-force approach that's extremely slow, so obviously no TIO with test cases.

Although TIO is too slow for the entire solution, I've added a TIO after each section so you can verify the individual parts work as intended. Note that the final TIO-link only uses a portion of each hand (including the input).

### General explanation:

1. Generate a list of all valid 14-tile hands
2. Get every possible permutation of every 14-tile hand
3. Get the input-hand and get all its permutations as well
4. Get the Levenshtein distance between every input-hand permutation and every valid 14-tile hand permutation
5. Keep the lowest Levenshtein distance across all these checks, and decrease it by 1 to get the number of Shantens

### Code explanation:

Create a list of all overlapping consecutive triplets of the Numbers:

```
₂Ý                # Push a list in the range [0,26]
  8+              # Add 8 to each to make the range [8,34]
    3ä            # Split it into 3 equal-sized parts: [[8,16],[17,25],[26,34]]
      €           # For each inner list:
       ü3         #  Create all overlapping triplets of this list
                  #   [a,b,c,d,e,...] → [[a,b,c],[b,c,d],[c,d,e],...]
         €`       # Then flatten one level down to have a list of triplets
           4и     # And repeat each consecutive triplet 4 times in the list

```

Try it online.

Create a list of all possible triplets of all tiles:

```
M                 # Push the largest value on the stack thus far (including inner lists),
                  # which is 34
 L                # Pop and push a list in the range [1,34]
   δ              # For each value in this list,
  3 и             #  Repeat it 3 times as list
     ©            # Store the list of identical triplets in variable `®` (without popping)

```

Try it online.

Then:

```
«                 # Merge the two lists together
 4ã               # And take the cartesian product of 4 with this list

```

Which results in all possible combinations of 4 Bodies: Try it online.

Then we'll generate all possible Heads:

```
®                 # Push the list of identical triplets from variable `®`
 €¦               # Remove one value from each so we have identical pairs (Heads) instead
   ©              # Store that as new variable `®` (without popping)

```

Try it online.

And create every possible combination of these 1 Heads + 4 Bodies:

```
â                 # By taking the cartesian product of the two lists
 ʒ      }         # And then filtering it so we won't use more than 4 of the same tile:
  ˜               #  Flatten the pairs/triplets to a single list
   D¢             #  Duplicate it, and count for each item how much it occurs
     à            #  Get the maximum for the tile that occurs the most
      5‹          #  And check that this it smaller than 5

```

Now we have all possible regular 14-tile hands: Try it online.

Next we'll also create the special type of 14-tile heads, starting with the 7 Heads:

```
®                 # Push the list of identical pairs (Heads) from variable `®` again
 7.Æ              # Get all 7-element combinations of these distinct heads
    «             # And merge it to the earlier created valid 14-tile hands

```

Try it online.

And the final valid 14-tile hands are the 13+1 Orphans:

```
8L                # Push a list in the range [1,8] (4 Winds, 3 Dragons, and One of the Ten Thousands)
  •1«þï•          # Push compressed integer 27700378
        ₆в        # Convert it to base-36 as list: [16,17,25,26,34] (Nine of the Ten Thousands,
                  #  One & Nine of the Bamboos, One & Nine of the Circles)
          «       # Merge those together
           D¸     # Duplicate this list of 13 Orphans, and wrap it into a list
             â    # And take the cartesian product of the two
              «   # And also merge those to the earlier created valid 14-tile hands

```

Try it online.

Now that we finally have all our valid 14-tile hands, we're going to get all their permutations as well as the permutations of the input, and check the Levenshtein-distance between each possible combination. After which the lowest Levenshtein-distance across all permutation-comparisons minus 1 is our number of Shatens:

```
ε                 # Map over each valid 14-tile hand:
 ˜                #  Flatten the pairs/triplets to a single 14-length list
  •1óñ•           #  Push compressed integer 126975
       +          #  Add it to each value in the list
        ç         #  Convert each from integer to their unicode character
         J        #  And join it together to a single string
          œ       #  Get all permutations of this hand
 Iœ               #  Then push the input, and get all its permutations as well
 δ                #  And then check for every possible combination of the permutations:
  .L              #   What the Levenshtein-distance is between the two

```

And finally get the (flattened) lowest one to calculate the number of Shantens:

```
}W                # After the map: push the flattened lowest Levenshtein-distance
  <               # And subtract it by 1 to get the number of Shantens
                  # (after which this is output implicitly as result)

```

Try it online with just a portion of the valid hands, each cut into a smaller hand, and with added debug-lines.

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•1«þï•` is `27700378`; `•1«þï•₆в` is `[16,17,25,26,34]`; and `•1óñ•` is `126975`.

## How slow?

To give you an idea of how slow this approach is, here are some numbers:

*Regular hands: \\$34×118^4-X\\$*

* There are \\$118\\$ valid Bodies (including duplicated subsequent triplets for the Numbers, which each occur four time), and thus \\$118^4\\$ combinations of 4 Bodies (yes, this includes duplicated combinations due to the duplicated subsequent Number triplets).
* There are \\$34\\$ valid Heads, and thus \\$34×118^4\\$ combinations of 1 Head + 4 Bodies.
* After which \\$X\\$ (*TODO: do the math..*) combinations are removed, because they contain a certain tile more than four times.

*Special hands: \\$\binom{34}{7} + 13\\$*

* There are again \\$34\\$ valid Heads, and thus \\$\binom{34}{7}\\$ combinations of 7 distinct Heads.
* There are \\$13\\$ Orphans (\\$4\\$ Winds + \\$3\\$ Dragons + \\$3\\$ Ones + \\$3\\$ Nines), and thus \\$13\\$ valid Orphan hands.

There are therefore a total of \\$34×118^4-X + \binom{34}{7} + 13 = 6597224013-X\\$ valid 14-tile hands.

*Comparing the input-hand and a single valid-hand: \\$14!×13!\\$*

* Getting all permutations of the 14-tile hands means there are \\$14!\\$ permutations.
* Getting all permutations of the 13-tile input-hand means there are \\$13!\\$ permutations.
* Checking each permutation of a valid 14-tile hand with each permutation of the input-hand are therefore \\$14!×13! = 542861032610856960000\\$ valid permutation-pairs.

**So in conclusion:**

Assuming a standard Levenshtein algorithm is used in the `.L` builtin, the complexity is in general about \\$O(n^2)\\$ (\\$n\\$ being the length of the string). Which in this case would be complexity \\$O(14^2) = O(196)\\$ for each of the \\$14!×13! × (34×118^4-X + \binom{34}{7} + 13) = \\$\\$3581375840062321621020180480000 - 542861032610856960000×X\\$ permutation-combinations across all valid hands (after which we still have to get the flattened \\$minimum-1\\$).
Safe to say: way too slow for a TIO link for even a single test case, let alone a test suite of all test cases. ;)
> 5 votes

---
Tags: code-golf, game, board-game, unicode
---


title: Self-loathing program/function

text:
# Question
Title: Self-loathing program/function
Simple task, write a program/function that returns error **if and only if** presented with itself.

The program must give a valid output for any input other than itself.

For the error part, you can only use errors already built in errors that comes with your language of choice. New/ self-defined error messages are not allowed.

The output should be of the same type as the input. (int, float, string, array, boolean, etc.) Except in the case if presented with itself of course.

Standard loopholes forbidden, lowest byte wins.

# Answer
# 05AB1E, 20 bytes

```
"34çìD«QiF"34çìD«QiF

```

Outputs the input if it's not equal to the program. If it is equal, it will output the error:

> \** (RuntimeError) Could not convert `"34çìD«QiF"34çìD«QiF` to integer.

Try it online.

**Explanation:**

It's based on this base quine: `"34çìD«"34çìD«`.

```
"34çìD«QiF"           # Push string "34çìD«QiF"
           34ç        # Push 34, converted to a character: '"'
              ì       # Prepend it to the string: '"34çìDJQiF'
               D«     # Append a copy of itself: '"34çìDJQiF"34çìDJQiF'
                 Qi   # If it's equal to the (implicit) input-string:
                   F  #  Start a loop, using the (implicit) input-string as argument,
                      #  resulting in the error
                      # (implicit else: use the implicit input as implicit output)

```
> 1 votes

---
Tags: code-golf
---


title: Name an arbitrary string

text:
# Question
Title: Name an arbitrary string
This should be easy: given an arbitrary string, your program will give it a name.

# Requirements

Your program will accept an input of a UTF8 string, and output a string representing the input's "name", how you define this name is arbitrary, but it must comply with some conditions.

# I/O Ranges

The input will at most be 382 UTF 8 characters long (making the input space 1112064^382 long). Don't ask me why this number, it was random. Your program must support all of them. Consider not forcing you to deal with arbitrary input size an act of mercy.

You can use any character set to build your output space. ASCII, Unicode, only Wingdings characters, etc. all are fair game. This output space must be smaller than the input space (easy enough), and name collisions must be uniformly distributed (every name will refer to roughly the same number of input strings, ~1% fluctuation is the max. accepted difference).

Yes I'm asking you to build a watered down hash function. Just in case you're wondering.

Name collisions must be sufficiently rare that it does not happen in everyday use. 1 in \\$2^{100}\\$ sounds reasonable enough a limit. This forces your output space to be at least 7540 bits long (the input space is a little larger than \\$2^{7640}\\$). (I tried cheating my own challenge by only outputting 0 and 1, you are not allowed to cheat like I did).

# Conditions

1. Name collisions must be rare enough (see above) and must not be, by any method, deliberately generated. This is similar to hash collisions.
2. Name space must be smaller that input space (whats the point of having a name longer than the string)
3. Your program must be deterministic. Same string must be assigned the same name every time.

# Winning

The program with a name of at most 10 characters long and pronounceable (edit: since someone pointed out pronounceable is hard to define, this condition is now changed to \<=10 characters of **the same spoken language**) wins. If this win condition is not met, scoring is lowest byte wins as usual.

The same language above means any **one** of the languages that people use. If one language uses some characters from another, that is fine as long as it is within normal use. (French uses English characters, for example) Mixing different language's characters that are not within formal use is not allowed (e.g. Korean characters and English alphabets)

Also give your program's name in the answer, even though it is unlikely to be \<=10 characters and/or unpronounceable. I am curious what your program is called.

# Answer
# 05AB1E, 2 bytes

```
₂∍

```

Try it online!

---

### Explanation

```
 ₂                - 26
  ∍               - Extend/shorten to this length

```

Extend will repeat the string until it is length 26, shorten will remove chars from the right until it is length 26.

This means that some strings will be slightly more likely (the repeated ones since `ab, abab, ababab, ababababab` etc all produce `ababababababababababababab`, but it will fall within the 1%, since these cases of collision only occur for strings below length 26.

---

# 05AB1E, 8 bytes (Winning)

```
HSAsèJ₆∍

```

Try it online!

Program's name: faegdahbbafaegdahbbafaegdahbbafaegda

---

### Explanation

```
HSAsèJ          - Convert it to a string of the first 10 letters of the english alphabet
      ₆∍        - Extend shorten to base 36 (10^36 > 2^100)

```

Can definitely be shorter, but why bother. It wins.
> 2 votes

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


title: Spell out numbers in French

text:
# Question
Title: Spell out numbers in French
There was a challenge to convert a number to its numeral in English, but that was too straightforward. Given a number 0–100, your task is to output the corresponding numeral in French. The French numeral system has a more complex logic behind it compared to the English one:

```
Number  Numeral
---------------
 0      zéro (note the accent)
 1      un
 2      deux
 3      trois
 4      quatre
 5      cinq
 6      six
 7      sept
 8      huit
 9      neuf
10      dix
11      onze
12      douze
13      treize
14      quatorze
15      quinze
16      seize
17      dix-sept (literally ten seven)
18      dix-huit
19      dix-neuf
20      vingt
21      vingt et un (no hyphens)
22      vingt-deux
...
30      trente
...
40      quarante
...
50      cinquante
...
60      soixante
...
70      soixante-dix (literally sixty ten)
71      soixante et onze
...
80      quatre-vingts (note the s; literally four twenties)
81      quatre-vingt-un (note the hyphens)
...
90      quatre-vingt-dix
91      quatre-vingt-onze
...
99      quatre-vingt-dix-neuf (4*20+10+9)
100     cent

```

For a complete list, follow http://quizlet.com/996950/ (http://www.webcitation.org/6RNppaJx0).

## Further rules/explanations

* There will always be a hyphen between words EXCEPT when the number ends in 1.
* When the number ends in 1, the word *et* (meaning *and*) is added before the *un* or *onze*. (31 = trente et un)
* However, 81 and 91 are formatted the same as the other numbers. (81 = quatre-vingt-un)
* At 60, the system switches from base 10 to base 20.
* There are some minor discrepancies across the web about this; refer to the list linked above for questions.
* Loopholes that are forbidden by default are not allowed.
* Using an external source such as a website, as well as any libraries, APIs, functions, or the like that convert numbers to numerals or translate to French are not allowed.
* This is , so the answer with the fewest bytes wins.
* If available, please link to an online compiler to allow for easy testing of your code.

## Input

* Input shall be taken from however your language takes input. (STDIN, command line, etc.)
* Input will be a single string, consisting of a whole number between 0 and 100 inclusive (leading zeroes optional).
* You can assume the input will always be well-formed.

## Output

* The result shall be output to the most convenient method for your language. (STDOUT, dialog box, etc.)
* Case does not matter in the output.

## Examples

Test your code against these:

```
Input  Output
-------------
0      zéro
18     dix-huit
51     cinquante et un
80     quatre-vingts
91     quatre-vingt-onze
99     quatre-vingt-dix-neuf

```

# Answer
> 7 votes
# JavaScript (ES6) 318 ~~321~~

*Edit* Bug fix (managing leading 0s) and golfed more

*Credit for the camel case trick* @Core1024

**With input/output via popup**

```
alert((n=prompt(),w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'.match(/[A-Z][^A-Z]+/g),
u=n%10,s=u-1|n>80?d='-':' et ',n>99?'Cent':n<21?w[n|0]:n<70?w[18+n/10|0]+(u?s+w[u]:''):(n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')))

```

**As a testable function**

```
F=n=>(
  w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'
  .match(/[A-Z][^A-Z]+/g),
  u=n%10,s=u-1|n>80?d='-':' et ',
  n>99?'Cent':
  n<21?w[n|0]:
  n<70?w[18+n/10|0]+(u?s+w[u]:''):
  (n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')
)

```

**To Test** In FireFox console or FireBug

```
for (i = 0; i < 100; console.log(r),i+= 10)
  for (j=0, r=''; j < 10; j++)
    r+=(i+j)+':'+F(i+j+'')+", "; // specific: input is a string
F('100')

```

**Test Output**

```
0:Zéro, 1:Un, 2:Deux, 3:Trois, 4:Quatre, 5:Cinq, 6:Six, 7:Sept, 8:Huit, 9:Neuf,
10:Dix, 11:Onze, 12:Douze, 13:Treize, 14:Quatorze, 15:Quinze, 16:Seize, 17:Dix-sept, 18:Dix-huit, 19:Dix-neuf,
20:Vingt, 21:Vingt et Un, 22:Vingt-Deux, 23:Vingt-Trois, 24:Vingt-Quatre, 25:Vingt-Cinq, 26:Vingt-Six, 27:Vingt-Sept, 28:Vingt-Huit, 29:Vingt-Neuf,
30:Trente, 31:Trente et Un, 32:Trente-Deux, 33:Trente-Trois, 34:Trente-Quatre, 35:Trente-Cinq, 36:Trente-Six, 37:Trente-Sept, 38:Trente-Huit, 39:Trente-Neuf,
40:Quarante, 41:Quarante et Un, 42:Quarante-Deux, 43:Quarante-Trois, 44:Quarante-Quatre, 45:Quarante-Cinq, 46:Quarante-Six, 47:Quarante-Sept, 48:Quarante-Huit, 49:Quarante-Neuf,
50:Cinquante, 51:Cinquante et Un, 52:Cinquante-Deux, 53:Cinquante-Trois, 54:Cinquante-Quatre, 55:Cinquante-Cinq, 56:Cinquante-Six, 57:Cinquante-Sept, 58:Cinquante-Huit, 59:Cinquante-Neuf,
60:Soixante, 61:Soixante et Un, 62:Soixante-Deux, 63:Soixante-Trois, 64:Soixante-Quatre, 65:Soixante-Cinq, 66:Soixante-Six, 67:Soixante-Sept, 68:Soixante-Huit, 69:Soixante-Neuf,
70:Soixante-Dix, 71:Soixante et Onze, 72:Soixante-Douze, 73:Soixante-Treize, 74:Soixante-Quatorze, 75:Soixante-Quinze, 76:Soixante-Seize, 77:Soixante-Dix-sept, 78:Soixante-Dix-huit, 79:Soixante-Dix-neuf,
80:Quatre-Vingts, 81:Quatre-Vingt-Un, 82:Quatre-Vingt-Deux, 83:Quatre-Vingt-Trois, 84:Quatre-Vingt-Quatre, 85:Quatre-Vingt-Cinq, 86:Quatre-Vingt-Six, 87:Quatre-Vingt-Sept, 88:Quatre-Vingt-Huit, 89:Quatre-Vingt-Neuf,
90:Quatre-Vingt-Dix, 91:Quatre-Vingt-Onze, 92:Quatre-Vingt-Douze, 93:Quatre-Vingt-Treize, 94:Quatre-Vingt-Quatorze, 95:Quatre-Vingt-Quinze, 96:Quatre-Vingt-Seize, 97:Quatre-Vingt-Dix-sept, 98:Quatre-Vingt-Dix-huit, 99:Quatre-Vingt-Dix-neuf,
"Cent"

```

# Answer
> 6 votes
# Python - 344 ~~(348)(380)(445)(537)~~ bytes

Thanks to grc, Ray and isaacg for their help in the golfing process.

The code consists of the initial dictionary definition and a list comprehension that fills in the blanks with the junction of the dictionary's elements.

You can check the code online at repl.it

```
r=range
def f(a):b=a/60*10+10;d[a]=d[a-a%b]+(' et ','-')[a%10!=1or a>80]+d[a%b]
d=dict(zip(r(17)+r(20,70,10)+[80,100],'zéro un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante quatre-vingt cent'.split()))
[f(v)for v in r(100)if(v in d)<1]
d[80]+='s'
print d[input()]

```

My latest attempts to golf this code have been to forgo the generation process and with that reduction refine the function to just generate the requested number on the spot. However, since the 60 and 80's numbers need uncalculated elements, the struggle has been to create such a function while decreasing code.

# Answer
> 6 votes
# Haskell, 390 bytes

```
b=(words"zéro un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize vingt trente quarante cinquante soixante"!!)
a!b=a++"-"++b
f 0=b 0
f 71=f 60++" et onze"
f 80=f 4!b 17++"s"
f 100="cent"
f x|x<17=b x|x<20=b 10!b(x-10)|x>80=b 4!b 17!f(x-80)|m==1=f(x-1)++" et un"|x>60=f 60!f(x-60)|m==0=b(15+div x 10)|1<2=f(x-m)!f m where m=mod x 10
main=interact$f.read

```

Ungolfed

```
base :: Int -> String
--              0    1  2    3     4      5    6   7    8    9    10  11   12     13     14       15     16    17    18     19       20        21
base i = words "zéro un deux trois quatre cinq six sept huit neuf dix onze douze  treize quatorze quinze seize vingt trente quarante cinquante soixante" !! i

hyphen :: String -> String -> String
a `hyphen` b = a ++ "-" ++ b

say :: Int -> String
say 0 = base 0
say 71 = say 60 ++ " et onze"
say 80 = say 4 `hyphen` base 17 ++ "s"
say 100 = "cent"
say x
  | x < 17 = base x
  | x < 20 = base 10 `hyphen` base (x - 10)
  | x > 80 = base 4 `hyphen` base 17 `hyphen` say (x - 80)
  | m == 1 = say (x - 1) ++ " et un"
  | x > 60 = say 60 `hyphen` say (x - 60)
  | m == 0 = base (div x 10 + 15)
  | otherwise = say (x - m) `hyphen` say m
  where m = mod x 10

main = putStr.say.read=<<getLine

```

Functional programming languages are quite suitable for this job.

# Answer
> 5 votes
## Ruby, 333 bytes

```
l=['']+%w{un deux trois quatre cinq six sept huit neuf dix onze douze treize quatorze quinze seize}
d=%w{vingt trente quarante cinquante soixante _ quatre-vingt}+['']*2
n=gets.to_i
v=n%20
t=n%10
puts n<1?'zéro':n>99?'cent':d[(n<70?n:n-v)/10-2]+(n<21||t<1&&n<61?'':v<1??s:t==1&&n<80?' et ':?-)+(n>60||n<20?v<17?l[v]:'dix-'+l[t]:l[t])

```

It's mostly just two look up tables and a bunch of ternary operators that encode all of the weird rules and tell you which lookup table to use when. Let me know if you want to know more. ;)

# Answer
> 4 votes
# Python - 392 bytes

It has a list with base numbers which it uses to generate the other numbers. Most of the generation logic is in the list comprehension on line 2, using list indexing for conditionals. Once the list is generated it then looks up the inputted number and prints it.

Edit: Shortened from 426 bytes using grc's tip.

```
a='_un_deux_trois_quatre_cinq_six_sept_huit_neuf_dix_onze_douze_treize_quatorze_quinze_seize_dix-sept_dix-huit_dix-neut'.split('_')
a+=[[['vingt','trente'],['quarante','cinquante'],['soixante']*2,[a[4]+'-vingt']*2][b][c>9]+['','-',' et '][(c%[10,20][b>1]>0)+(c%10==1)*(b<3)]+a[c%[10,20][b>1]]for b in[0,1,2,3]for c in range(20)]
a[0]='zéro'
a[80]+='s'
a+=['cent']
print(a[int(input())])

```

# Answer
> 2 votes
# 05AB1E, ~~150~~ 149 bytes

```
`UV7*Y8÷6*xsYαƵΓYåi<6LXåDX«U_}X8+).•2!ÛÄÒÁw§#Kºγ‚¼8&òo£Ù0ÿM¾…hTвcтv›IÈΩ{т3)`pñ"O|BεÆõ¿-∍£¸±<¥Ð~„Ñzä₂-bζÅ'á`†^=/Rú÷hÕS»•#ÁsèõK…-ˆÆ ć‚R7L1«IåèýI_i"zéro

```

Try it online! or validate all possible inputs

Takes input 0-padded to length 3.

# Answer
> 1 votes
# Python 3, (503 bytes)

Compress the table using bzip2 and then use ascii85 encoding to store the result. The table is:

```
zéro
un
deux
trois
quatre
cinq
...
cent

```

Very naive method, but it's not that bad.

# Golfed

```
import bz2,base64 as B
print(bz2.decompress(B.a85decode('6<\\%_0gSqh;d"=$\\VU:fOjTBn&3p:MiVu^S+:%s4!Q6o8\\8%r<Bp,5\\LT&Q+19!OmJC@3n\'bD<]UHekq<8OP<;]9BZ,;>836X4<[@KJ,)FsD^8j9Q=]O]&/8\'rjSK&0Sh0W[ru0E0!!M-tL69NZF6N\'Lc#$Q=?S_P0+uEZP"[H;%Ucch??nYC76\'k<)isZIBqqOKi(,IHp""^8d/EqRpc_I<IRj[\'4KB`/."%5,"pjr&27q+&t.6J+ik=Jdd2A)j]\'jt5ts0>:sr9.@E>V0F9L?9r&pX\'E.NUP:r&?>\'*(gKmd;/1QkUb*1&JhfWiE7Kl,P,o1go+.3O&l))Y,$/PO)%"al^4H2,n-l\\PuM!W1rBB9t.,U>DhAs83burMn(%%-qHG<gr+^')).decode().split('\n')[int(input())])

```

## Ungolfed

```
import bz2, base64
s = '6<\\%_0gSqh;d"=$\\VU:fOjTBn&3p:MiVu^S+:%s4!Q6o8\\8%r<Bp,5\\LT&Q+19!OmJC@3n\'bD<]UHekq<8OP<;]9BZ,;>836X4<[@KJ,)FsD^8j9Q=]O]&/8\'rjSK&0Sh0W[ru0E0!!M-tL69NZF6N\'Lc#$Q=?S_P0+uEZP"[H;%Ucch??nYC76\'k<)isZIBqqOKi(,IHp""^8d/EqRpc_I<IRj[\'4KB`/."%5,"pjr&27q+&t.6J+ik=Jdd2A)j]\'jt5ts0>:sr9.@E>V0F9L?9r&pX\'E.NUP:r&?>\'*(gKmd;/1QkUb*1&JhfWiE7Kl,P,o1go+.3O&l))Y,$/PO)%"al^4H2,n-l\\PuM!W1rBB9t.,U>DhAs83burMn(%%-qHG<gr+^'
table = bz2.decompress(base64.a85decode(s)).decode().split('\n')
num = int(input())
print(table[num])

```

---

## Bonus

Can you find the word "Vim" in the compressed string ?

# Answer
> 1 votes
# Bash, ~~456 440 421~~ 408

Assumes valid input (integer from 0 to 100 with any number of leading zeroes).

```
v=`sed 's/0*//'<<<$1`
f=('' dix vingt trente quarante cinquante soixante soixante-dix quatre-vingts quatre-vingt-dix)
s=('' ' et un' -deux -trois -quatre -cinq -six -sept -huit -neuf)
o=${f[${v: -2:1}]}${s[${v: -1:1}]}
[ "${o:0:1}" = \  ]&&o=un
((v>99))&&o=cent
sed 's/^-//
s/s-/-/
s/s et /-/
s/dix et un/onze/
s/di.*ux/douze/
s/d.*s$/treize/
s/d.*re/quatorze/
s/d.*q/quinze/
s/di.*ix/seize/'<<<${o:-zéro}

```

# Answer
> 1 votes
# JavaScript 459 (No Camel Casing)

@edc65 can't take that from you... ;)

`A="0un0deux0trois0quatre0cinq0six0sept0huit0neuf0dix0onze0douze0treize0quatorze0quinze0seize0dix-sept0dix-huit0dix-neuf".split(0);S="soixante";Q=A[4]+"-vingt";T=10;V=20;N=59;for(b=5;1<b--;)for(c=V;c--;)X=b*V+c,A[X]=[,["vingt","trente"],["quarante","cinquante"],[S,S],[Q,Q]][b][c/T|0]+(X%T?X>N?X%V==T?"-dix":"":"":"")+(1>X%T?"":(1==X%(X>N?V:T)|71==X)&81!=X?" et ":"-")+(X>N&X%V==T?"-dix":A[c%(X>N?V:T)]);A[0]="zéro";A[80]+="s";A[100]="cent";alert(A[prompt()])`

---
Tags: code-golf, number, kolmogorov-complexity, natural-language
---


# Question
Title: Implement a Caesar Cipher with a Digit Shift
I assume everyone here is familiar with the Caesar Cipher that shifts letters to a certain index. https://en.wikipedia.org/wiki/Caesar\_cipher for those who still needs introduction.

But, we can all agree that plain Caesar is unfun and way too easy. So here's a version that also shifts characters around. This version first applies a cyclic position shift of a given amount to the string, for each character in the string separated with punctuations (space counts as character in this context, positive index means to the right).

For example, `Hello world` with shift +3 becomes `rldHello wo`.
`Hello! World` becomes `lloHe!rld Wo` with the same shift however because the ! separated the string.

After that, your program applies the Caesar cipher to the shifted text, and outputs the result. (easy enough)
The first example becomes `uogKhoor zr` after the Caesar cipher of +3.
The second example becomes `iilEb!oia Tl` after a Caesar shift of -3 (or +23 in alphabets)

As seen above, the index of the two shifts may or may not be equal.

**Task**

Write a encode and decode program or function (or whatever your language of choice calls them), they may or may not be the same one. It must implement the aforementioned rules of double shifting, and the decode function must successfully reverse it.

**Conditions**

Your program must at the very least function on ASCII characters, ASCII 0-9 (48-57, inclusive), A to Z (65-90), a to z (97-122) and Space (32) counts as characters in this context, with every other ASCII character counting as punctuation and breaking up the string.

Bonus points to those whose program functions on your language of choice's codebase. Since non-ASCII language contain special characters the "punctuation" rule is omitted in this use case. You only need to implement the cyclic shift and then the Caesar shift on your language's codebase.
`¡¢£¤` in Jelly becomes `©¤¥¦` with a position shift of +1 and Caesar shift of -253.

**You may assume:**

The index input are integers. It may be negative or zero.
If only one number is provided, encode both shifts with that number.
If no number is provided, perform whatever default shifts your heart desire (except 0 and 0, that is boring).
**Edit: Due to overwhelming demand, you may assume that there will be at least one number provided. Code that has defaults would still be preferred but no extra scoring.**
The input string is in ASCII. Or in your language's codebase if you decide to input that to your program.

**Scoring**

Of course programs that successfully include their codebase will be prioritized. Include the shifted version of your program in your answer to reflect this.

The other criteria is lowest byte wins. This counts both the encoder and decoder. List the sum and respective length separately please.

**Test cases**

```
+3 -5 "Hello,world" becomes "ggjCz,mgyrj"
+10 "Implement a Caesar Cipher with a Digit Shift" becomes "sqsd Crspd Swzvowoxd k Mkockb mszrob gsdr k N"
-2 -11 "Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift."
becomes "thpg rxewtgRp,ahd zcdlc ph Rpthpg p'rxewtgh ,wt hwxui rxewtg i,pthpg'h rdst dg Rpthpg hwxui R."

```

PS. Of course I am aware that the two shifts can be carried out in any order and produce the same result, it is just my way of visualizing things. Plus, the first input means position shift index.

PPS. If the test cases are wrong I apologize, I am not a good coder.

# Answer
> 2 votes
# 05AB1E, 23 (12+11) bytes

Uses the 05AB1E encoding for the Caesar-shifting.

**Encoder:**

```
žĆDII(._kI+è

```

Input order as `string`, `shift`, (optional `Caesar-shift`). I/O of the strings as character-list.

Try it online or try it online with debug step-by-step lines and single shift-input.

**Decoder:**

```
žĆDIkI-èI._

```

Input order as `string`, (optional `Caesar-shift`), `shift`. I/O of the strings as character-list.

Try it online or try it online with debug step-by-step lines and single shift-input.

**Explanation:**

```
              # ENCODER:
žĆ            # Push the 05AB1E codepage
  D           # Duplicate it
   I          # Push the first character-list input
    I         # Push the second shift integer
     (        # Negate it
      ._      # Shift the character-list that many times towards the left
        k     # Get the index of each character in the duplicated codepage
         I    # Push the second shift input again or the optional third Caesar-shift input
          +   # Add it to each index
           è  # And index it into the 05AB1E codepage
              # (after which the resulting character-list is output implicitly as result)

              # DECODER:
žĆ            # Push the 05AB1E codepage
  D           # Duplicate it
   I          # Push the first character-list input
    k         # Get the index of each in the duplicated codepage
     I        # Push the optional Caesar-shift or shift integer
      -       # Subtract it from each index
       è      # Index it into the 05AB1E codepage
        I     # Push the second/third shift integer
         ._   # And rotate the character-list that many times towards the left
              # (after which the resulting character-list is output implicitly as result)

```

# Answer
> 2 votes
# Jelly, (8 + 11 = 19?) 11 + 14 = 25 bytes

Uses the code-page, no punctuation option

19 + 6 = 25 bytes handling the `only 1 number option` by taking a list of numbers as one of the two arguments.

**Encoder +:** (`Shift(s), plaintext`)

```
0ịØJ,ṙ¥yṙ⁸Ḣ

```

**Decoder +:** (`Shift(s), cyphertext`)

```
0ịNØJ,ṙ¥yṙ⁸N¤Ḣ

```

These Links build on the below programs:

**Encoder:** (`Caesar shift, plaintext, Cyclic shift`)

```
ØJ,ṙ¥yṙ⁵

```

**Decoder:** (`Caesar shift, cyphertext, Cyclic shift`)

```
NØJ,ṙ¥yṙ⁵N¤

```

# How?

### Encoder

```
ØJ,ṙ¥yṙ⁵ - Main Link: Caesar shift, plaintext
ØJ       - code-page characters
    ¥    - last two links as a dyad:
   ṙ     -   rotate (code-page) left by (Caesar shift)
  ,      -   (code-page) pair with (that)
     y   - (plaintext) translated using (that mapping)
       ⁵ - get program's 3rd argument (Cyclic shift)
      ṙ  - rotate (translated) left by (Cyclic shift)
         - implicit print

```

### Decoder

```
NØJ,ṙ¥yṙ⁵N¤ - Main Link: Caesar shift, cyphertext
N           - (Caesar shift) negated
 ØJ         - code-page characters
     ¥      - last two links as a dyad:
    ṙ       -   rotate (code-page) left by (negated Caesar shift)
   ,        -   pair
      y     - (cyphertext) translated using (that mapping)
          ¤ - nilad followed by link(s) as a nilad:
        ⁵   -   get program's 3rd argument (Cyclic shift)
         N  -   negated
       ṙ    - rotate (translated) left by (negated Cyclic shift)
            - implicit print

```

# Answer
> 1 votes
# Jelly, ~~25~~ 23 bytes (10 + 13)

```
ØJiⱮṙ+⁵ịØJ
ØJiⱮṙN}¥_⁵ịØJ

```

**Encoder**:

```
   Ɱ          For each character on the input string
  i           get its index on
ØJ            the Jelly code page.
    ṙ         Then rotate the list we get by as much as the cyclic shift input
     +⁵       and add to each number as much as the Caesar shift input.
       ị      Finally use those numbers to index
        ØJ    on Jelly's code page again.

```

**Decoder**:

```
   Ɱ             For each character on the input string
  i              get its index on
ØJ               the Jelly code page.
    ṙ            Then rotate the list of indices
     N}¥         by the symmetric of the cyclic shift input.
        _⁵       Then subtract from each number as much as the Caesar shift input.
          ị      Finally use those numbers to index
           ØJ    on Jelly's code page again.

```

@Jonathan saved me 2 bytes! Kudos to him :D

Inputs are the string to encode, the shift corresponding to the "rotation" of the string and the shift corresponding to the Caesar encoding. I am encoding the whole Jelly codepage.

You can try the encoder or the decoder. You can also check the encoder and decoder are the inverse of one another (swap the order of the encoder/decoder to verify they are the inverses on both sides).

# Answer
> 0 votes
First version, a bit verbose yet, I'll try to optimize:

* "fully cyclic caesar" (`9`+1 becomes `0`, `z`+1 becomes `a`, `Z`+1 becomes `A`)
* breaks on anything not a space or char (`a-z A-Z 0-1`) (I think your last example is wrong, it breaks on the last `'`, which is intended)
* default values if missing: 1 / 1 (same value for both, could be up to 9 without extra byte)
* originally planned to use PHP's char increment, convenient way to loop over alpha values (`$c='Z';$c++;` makes `'AA'`), but decrement is not implemented (so no negative values or decoding)!
* should be prioritized IMO because it supports its own codebase, UTF-8 ;)

**ENCODER + DECODER = TOTAL**

# PHP, 430 + 71 = 501 bytes

```
function a($a,$b='',$c=''){$b!==''?:$b=$c;$c!==''?:$c=$b;$t="/([^a-zA-Z0-9 ]+)/";preg_match_all($t,$a,$s);$r=preg_split($t,$a);for($i=0;null!==$d=$r[$i];$i++){if($j=strlen($d)){$n=-$b%$j;$d=substr($d,$n).substr($d,0,$n);for(;$j--;){if(' '!=$e=$d[$j]){$n=($t=ctype_digit($e))?10:26;$f=$c%$n+$e=ord($e);$d[$j]=chr($t&$f>57|$f>122|$e<91&$f>90?$f-$n:($t&$f<48|!$t&$f<65|$e>96&$f<97?$f+$n:$f));}}}$r[$i]=$d.$s[1][$i];}return join($r);}function b($a,$b='',$c=''){return a($a,$b!==''?-$b:'',$c!==''?-$c:'');}

```

Try it online!

**BONUS - Encoder with line breaks and comments:** (not updated)

```
$a=$argv;                     //arguments short alias
$b=$a[2]?$a[2]:$a[3];         //argument 1 defaults to 2 if missing
$c=$a[3]?$a[3]:($b?$b:$b=1);  //argument 2 defaults to 1 or both default to "1"
$t="/([^a-zA-Z0-9 ]+)/";      //breaking on anything not alpha or digit or space
preg_match_all($t,$a[1],$s);  //saving breaking chars for later
$r=preg_split($t,$a[1]);      //splitting at breaks
for($i=0;null!==$d=$r[$i];){  //for any non null split
    if($j=strlen($d)){                     //if it has a length
        $n=-$b%$j;                         //modulo for shifting
        $d=substr($d,$n).substr($d,0,$n);  //the shifting
        for(;$j--;){                       //for every char
            if(' '!=$e=$d[$j]){                //which is not a space
                $n=($t=ctype_digit($e))?10:26; //char code range depending if digit or alpha
                $f=$c%$n+$e=ord($e);           //new char code and save current one
                $d[$j]=chr($t&$f>57|$f>122|$e<91&$f>90?$f-$n:($t&$f<48|!$t&$f<65|$e>96&$f<97?$f+$n:$f));    //applying char code $f or using range $n to calculate if out
            }
        }
    }
    echo$d.$s[1][$i++];       //display current split with breaking chars
}

```

**BONUS 2 - shifted version of the program with -2 / -11:**

```
crixdc puj($p,$q='',$r=''){$q!==''?:$q=$r;$r!==''?:$r=$q;$i="/([^p-oP-O9-8 ]+)/";tveg_irwbp_apa($i,$p,$h);$g=tveg_axihe($i,$p);gud($x=9;aacj!==$s=$g[$x];$x++){xu($y=gatchi($s)){$c=-$q%$y;$s=qhighj($s,$c).qhighj($s,9,$c);gud(;$y--;){xu(' '!=$t=$s[$y]){$c=($i=netri_vxisx($t))?09:15;$u=$r%$c+$t=sdg($t);$s[$y]=grw($i&$u>46|$u>101|$t<80&$u>89?$u-$c:($i&$u<37|!$i&$u<54|$t>85&$u<86?$u+$c:$u));}}}$g[$x]=$s.$h[0][$x];}ijgc ydxcgt($g);}crixdc quj($p,$q='',$r=''){ijgc pgt($p,$q!==''?-$q:'',$r!==''?-$r:'');}

```

EDIT: saved 10 bytes by refactoring to remove brackets + replaced `''!==` by `''!=` \+ replaced logical operators `||`/`&&` by bitwise `|`/`&`

EDIT2: saved 1 byte by using `$l=strlen(` in for declaration instead of `''!=` and reusing it after, but +4 bytes correcting a bug for `$f<65` picking numbers, changed to `!$t&$f<65`

EDIT3: fixed bug of prematurely breaking first loop when string begins by a punctuation, forces new `if` to prevent division by zero, but uses split length `$j` to shorten second loop declaration

EDIT4: improved with a function and advices from 640KB but didn't want to go too far while questions not resolved and didn't want to end with same code - gave up default values when both arguments miss, supports now zero shifting

# Answer
> 0 votes
# PHP, 398 bytes

```
function e($z,$x,$y=null){$y=is_null($y)?$x:$y;for($i=0,$o=preg_split('/([^A-Za-z0-9 ])/',$z,0,2);$i<count($o);$o[$i]=$s,$i+=2)for($s=substr(($s=$o[$i]).$s.$s,($l=strlen($s))-$x,$l),$j=0;$j<strlen($s);$j++)if(($c=$s[$j])!=' ')$s[$j]=(chr(ctype_digit($c)?(ord($c)+$y-38)%10+48:(ord($c)+$y-($p=ctype_lower($c)?97:65)+26)%26+$p));return join($o);}function d($z,$x,$y=null){return e($z,-$x,-($y?:$x));}

```

Try it online!

Submitted as two functions:

* Encode: `e( $string, $index_shift, [ $caesar_shift ] ) : string`
* Decode: `d( $string, $index_shift, [ $caesar_shift ] ) : string`

Yes, this is not very golfed yet, but I thought it would be helpful to post to verify my assumptions about this challenge, while waiting for answers to my questions to the OP above.

Still unclear to me is:

1. Case of inputs `+1 "Z" == "A"`, `+1 "z" == "a"`, `+1 "9" == "0"`?
2. *Only* UTF-8 / ASCII languages are required to implement the "punctuation delimiter" rule?
3. Verify output with posted test cases, which as I've pointed out, I believe the second two are incorrect.

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


# Question
Title: Count switches in a smallest square root sequence mod \$2^n\$
### Definition

For any \\$a\equiv1\ (\text{mod }8)\\$ and \\$n\ge3\\$, there are exactly 4 roots to the equation \\$x^2\equiv a\ (\text{mod }2^n)\\$. Now, let \\$x\_k(a)\\$ be the smallest root to the equation \\$x^2\equiv a\ (\text{mod }2^k)\\$, then $$\\{x\_3(a),x\_4(a),x\_5(a),x\_6(a),\cdots\\}$$ is a smallest square root sequence (SSRS) of \\$a\\$ mod \\$2^n\\$.

John D. Cook published a quick algorithm that calculates such roots in \\$O(n)\\$ time. Assume \\$x\_k\\$ is a root to the equation \\$x^2\equiv a\ (\text{mod }2^k)\\$. Then, $$x\_{k+1}=\begin{cases}x\_k&\text{if }\frac{x\_k^2-a}{2^k}\text{ is even}\\x\_k+2^{k-1}&\text{otherwise}\end{cases}$$ is a root to the equation \\$x^2\equiv a\ (\text{mod }2^{k+1})\\$.

Now we define two lists A and B. \\$A=\\{A\_k|k\ge3\\}\\$ is the list of values generated by the algorithm above with initial values \\$A\_3=1\\$ and \\$B=\\{B\_k|k\ge3\\}\\$ is the list of values generated with initial values \\$B\_3=3\\$. Each entry in the SSRS \\$x\_k(a)\\$ takes the smallest value among \\$A\_k\\$ and \\$B\_k\\$. We say a switch in SSRS occurs whenever the choice changes from A to B or from B to A.

To illustrate the definition, take \\$a=17\\$:

The smallest numbers are highlighted. From the picture there are 13 switches up to mod \\$2^{24}\\$.

### Challenge

Write a function or program, that receives 2 integers \\$a,\ k\\$ as input (where \\$a\equiv1\ (\text{mod }8)\\$ and \\$k\ge3\\$) and output how many switches occur in the SSRS of \\$a\\$ mod \\$2^n\\$ up to \\$n=k\\$.

### Sample I/O

```
1, 3 -> 0
9, 4 -> 1
1, 8 -> 0
9, 16 -> 1
17, 24 -> 13
25, 32 -> 2
33, 40 -> 18
41, 48 -> 17
49, 56 -> 1
1048577, 2048 -> 959
1048585, 2048 -> 970

```

### Winning Condition

This is a code-golf challenge, so shortest valid submission of each language wins. Standard loopholes are forbidden by default.

# Answer
> 4 votes
# 05AB1E, ~~15~~ 14 bytes

```
LoεLnαy%0k}üÊO

```

Try it online!

For each `n`, this finds the smallest square root of `a` by brute-force.

## 05AB1E, ~~26~~ 23 bytes (fast)

```
13v¹yλ£DnIαN>o%2÷+]@γg<

```

Try it online!

This one properly uses Cook's formula.

```
13                    # literal 13
  v               ]   # for each digit:
   ¹                  #  push the input k
    y             ]   #  push the digit
     λ£               #  recurse k times with base case y:
       Dn             #   square of the current value
         Iα           #   absolute difference with input a
           N>o%       #   modulo 2**(N+1)
               2÷     #   integer divide by 2
                 +    #   add to the current value
@                     # compare the two lists element-wise
 γ                    # group consecutive equal elements
  g                   # length
   <                  # -1

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~88~~  87 bytes

Takes input as `(a)(k)`.

Because of the bitwise operations, this is only guaranteed to work for \\$k\le32\\$.

```
a=>K=>(x=[p=1,3],F=k=>k<K&&(p^(x=x.map(v=>q=v+=(v*v-a>>k&1)<<k-1),p=x[0]<q))+F(k+1))(2)

```

Try it online!

# Answer
> 1 votes
# Charcoal, 50 bytes

```
≔⁰ζ⊞υ¹⊞υ³ＦＸ²…³Ｎ«ＵＭυ⁺κ∧﹪÷⁻×κκηι²⊘ιＦ⌕υ⌊υ«≦⊕ζ≔⮌υυ»»Ｉζ

```

Try it online! Link is to verbose version of code. Takes input in the order \\$ \small k, a \\$. Explanation:

```
≔⁰ζ⊞υ¹⊞υ³

```

Start off with \\$ \small 0 \\$ swaps and initial values \\$ \small A\_3 = 1 \\$ and \\$ \small B\_3 = 3 \\$ in a list.

```
ＦＸ²…³Ｎ«

```

Loop over the powers of \\$ \small 2^n \\$ from \\$ \small 2^3 \\$ to \\$ \small 2^{k-1} \\$.

```
ＵＭυ⁺κ∧﹪÷⁻×κκηι²⊘ι

```

Map over the list calculating the next values \\$ \small A\_{n+1} \\$ and \\$ \small B\_{n+1} \\$.

```
Ｆ⌕υ⌊υ«

```

Test whether the smallest value is at the start of the list.

```
≦⊕ζ≔⮌υυ

```

If it isn't then increment the number of swaps and reverse the list so that the smallest value is at the start again.

```
»»Ｉζ

```

Print the number of swaps.

I have a ~~48~~ 47 byte version that seems to work on the test cases but I don't know why.

```
≔⁰ζ≔¹δ≔⁰εＦＸ²…³Ｎ«≔﹪÷⁻Ｘδ²ηι²θ≧⁺¬⁼θεζ≔θε≧⁺∧ε⊘ιδ»Ｉζ

```

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

```
≔⁰ζ≔¹δ≔⁰ε

```

Start off with \\$ \small 0 \\$ swaps, \\$ \small A\_3 = 1 \\$ and \\$ \small A\_3 \< B\_3 \\$.

```
ＦＸ²…³Ｎ«

```

Loop over the powers of \\$ \small 2^n \\$ from \\$ \small 2^3 \\$ to \\$ \small 2^{k-1} \\$.

```
≔﹪÷⁻Ｘδ²ηι²θ

```

Work out whether \\$ \small A\_{n+1} \> B\_{n+1} \\$.

```
≧⁺¬⁼θεζ

```

If this is a change from \\$ \small A\_n \> B\_n \\$ then increment the number of swaps.

```
≔θε

```

Save this for the next loop.

```
≧⁺∧ε⊘ιδ

```

Add \\$ \small 2^{n-1} \\$ if \\$ \small A\_{n+1} \> B\_{n+1} \\$.

```
»Ｉζ

```

Print the number of swaps.

# Answer
> 0 votes
# Jelly, ~~31~~ 29 bytes

```
²_⁴ọ2>
R1,3;€¹2*H+ʋ@ç?\€>/IAS

```

Try it online!

A full program taking \\$n\\$ as its left argument and \\$k\\$ as its right argument. Prints the number of switches.

Will post explanation once have more time to further optimise.

# Answer
> 0 votes
# Python 3, <sup>~~230~~ \\$\cdots\\$ ~~180~~</sup> 175 bytes

```
def f(x,a,k,p=4):
 l=[x]
 for n in range(3,k):x+=p*(((x*x-a)>>n)&1);p*=2;l+=[x]
 return l
def g(a,n):
 i=c=0
 for q in zip(f(1,a,n),f(3,a,n)):j=q[1-i]<q[i];c+=j;i^=j
 return c

```

Try it online!

A function `g` that uses Cook's formula (function `f`).

---
Tags: code-golf, number, number-theory
---


title: Classic VCS ASCII Adventure

text:
# Question
Title: Classic VCS ASCII Adventure
Growing up, my first console game system was an Atari 2600 and I will always have a love for some of those games I so enjoyed as a child. Many of the graphics are still memorable, perhaps even iconic.

It turns out that these sprites are very simplistic bitmaps, 8 pixels wide with variable height where the binary representation is the arrangement of the pixels.

For example, the hex bytes 0x18, 0x24, 0x18 would draw a crude circle like so:

```
0x18: 00011000
0x24: 00100100
0x18: 00011000

```

As 8 pixels wide creates fairly small graphics (even by Atari 2600 standards) it was common to double or quadruple either the height, width or both to create a larger (though more blocky and distorted) version of the same image. They would commonly also be flipped vertically or horizontal for both player sprites and playfields. The game *Combat* is a good example of this.

The challenge is, to write code to display these sprites as "graphics" in ASCII form including the ability to stretch or flip them vertically, horizontally or both. This must be in the form of either a full program, or callable function.

## Input:

* An array of bytes, each representing the horizontal bits for that line.
* A non-zero integer value for each direction, horizontal and vertical representing the scaling factor for that dimension.
* A negative value indicates that the dimension should also be flipped along it's axis.

## Output:

* ASCII representation to STDOUT or a newline-separated string, using a space character for black (0) pixels and any printable, non-space character of your choice for white (1) pixels.

## Test data:

```
bmp1 = [ 0x06, 0x0F, 0xF3, 0xFE, 0x0E, 0x04, 0x04, 0x1E, 0x3F, 0x7F, 0xE3, 0xC3, 0xC3, 0xC7, 0xFF, 0x3C, 0x08, 0x8F, 0xE1, 0x3F ]
bmp2 = [ 0x07, 0xFD, 0xA7 ]
bmp3 = [ 0x00, 0x8E, 0x84, 0xFF, 0xFF, 0x04, 0x0E, 0x00 ]
bmp4 = [ 0x00, 0xFC, 0xFC, 0x38, 0x3F, 0x38, 0xFC, 0xFC]

```

Note: Above example input arrays of bytes are provided as hex. If your platform does not accept hex literals for byte representation you may convert them to a native byte-equivalent literal.

## Example Output:

```
f( bmp1, 1, 1 ) =>
--------
     XX
    XXXX
XXXX  XX
XXXXXXX
    XXX
     X
     X
   XXXX
  XXXXXX
 XXXXXXX
XXX   XX
XX    XX
XX    XX
XX   XXX
XXXXXXXX
  XXXX
    X
X   XXXX
XXX    X
  XXXXXX
--------

f( bmp1, -2, 1 ) =>
----------------
  XXXX
XXXXXXXX
XXXX    XXXXXXXX
  XXXXXXXXXXXXXX
  XXXXXX
    XX
    XX
  XXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXXXX
XXXX      XXXXXX
XXXX        XXXX
XXXX        XXXX
XXXXXX      XXXX
XXXXXXXXXXXXXXXX
    XXXXXXXX
      XX
XXXXXXXX      XX
XX        XXXXXX
XXXXXXXXXXXX
----------------

f( bmp2, 1, 2 ) =>
--------
     XXX
     XXX
XXXXXX X
XXXXXX X
X X  XXX
X X  XXX
--------

f( bmp2, 2, 1 ) =>
----------------
          XXXXXX
XXXXXXXXXXXX  XX
XX  XX    XXXXXX
----------------

f( bmp2, -2, -2 ) =>
----------------
XXXXXX    XX  XX
XXXXXX    XX  XX
XX  XXXXXXXXXXXX
XX  XXXXXXXXXXXX
XXXXXX
XXXXXX
----------------

f( bmp3, 1, -1 ) =>
--------

    XXX
     X
XXXXXXXX
XXXXXXXX
X    X
X   XXX

--------

f( bmp3, 3, 3 ) =>
------------------------

XXX         XXXXXXXXX
XXX         XXXXXXXXX
XXX         XXXXXXXXX
XXX            XXX
XXX            XXX
XXX            XXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
               XXX
               XXX
               XXX
            XXXXXXXXX
            XXXXXXXXX
            XXXXXXXXX

------------------------

f( bmp4, -1, -1 ) =>
--------
  XXXXXX
  XXXXXX
   XXX
XXXXXX
   XXX
  XXXXXX
  XXXXXX

--------

f( bmp4, 4, 2 ) =>
--------------------------------

XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
        XXXXXXXXXXXX
        XXXXXXXXXXXX
        XXXXXXXXXXXXXXXXXXXXXXXX
        XXXXXXXXXXXXXXXXXXXXXXXX
        XXXXXXXXXXXX
        XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
--------------------------------

```

Note: the horizontal lines above and below are to show the beginning and end of the output. They are not required in the output, however empty lines (represented by all zeros/spaces) at the beginning and/or end are required, as shown.

Note 2: these test bitmaps were inspired by and re-drawn/coded based on game screenshots tagged as "fair use" on Wikipedia.

## Winning Criteria

* This is , so the shortest code in bytes per language wins.
* Standard loopholes are forbidden.

# Answer
# 05AB1E, ~~27~~ 26 bytes

```
εS²Ä×J³Äи²0‹ií]³0‹iR}˜0ð:»

```

Takes the input as a list of 8-bit binary-strings, and outputs with `1` as non-space character.

-1 byte thanks to *@MagicOctopusUrn*.

Try it online or verify all test cases.

**Explanation:**

```
ε         # Map the (implicit) input-list to:
 S        #  Convert the binary-String to a list of characters
  ²Ä      #  Take the absolute value of the second input
    ×     #  And repeat each character that many times
     J    #  And then join it back together to a single string again
 ³Ä       #  Take the absolute value of the third input
   и      #  Repeat that string as a list that many times
 ²0‹i     #  If the second input is negative:
     í    #   Reverse each string in the list
]         # Close both the if-statement and (outer) map
³0‹i }    # If the third input is negative:
    R     #  Reverse the list of lists
      ˜   # Flatten the list of lists to a list of strings
0ð:       # Replace all 0s with spaces " "
   »      # And join the strings by newlines (which is output implicitly)

```
> 5 votes

# Answer
# Python 2, 117 bytes

```
def f(m,w,h):
 for r in m[::cmp(h,0)]:print(''.join(' X'[1<<i&r>0]*abs(w)for i in range(8)[::cmp(0,w)])+'\n')*abs(h),

```

Try it online!
> 5 votes

# Answer
# Dyalog APL, ~~46~~ ~~42~~ 33 bytes

```
' #'[⍉⊃{⊖⍣(0>⍺)⍉⍵/⍨|⍺}/⎕,⊂⎕⊤⍨8/2]

```

Try it online!

-9 thanks to ngn!
> 3 votes

# Answer
# MATL, ~~24~~ 19 bytes

```
B,!i|1&Y"2M0<?XP]Zc

```

Inputs are an array of decimal numbers, horizontal scale, vertical scale.

Try it online!

### Explanation

```
B        % Implicit input: array of numbers. Convert to binary. Gives a zero-one
         % matrix, each row containing the binary expansion of a number
,        % Do twice
  !      %   Transpose
  i      %   Input: number
  |      %   Absolute value
  1&Y"   %   Repeat each row that many times
  2M     %   Push the latest input again
  0<     %   Is it negative?
  ?      %   If so:
    XP   %     Flip vertically
  ]      %   End
  Zc     %   Convert each nonzero into '#'. Zeros are displayed as space
         % Implicit end. Implicit display

```
> 3 votes

# Answer
# Prolog (SWI), 252 bytes

```
N+E+R:-N<1,R=[];N-1+E+S,R=[E|S].
N*E*R:-R=E,E=[];N<0,reverse(E,F),-N*F*R;[H|T]=E,N+H+S,N*T*U,append(S,U,R).
N/E/R:-N<1,R=[];(E<N,D=E,F=32;D=E-N,F=35),N/2/D/C,R=[F|C].
[H|T]^X^Y^R:-128/H/A,X*A*B,Y*[[10|B]]*C,append(C,D),(T=[],R=D;T^X^Y^S,append(D,S,R)).

```

Try it online!

### Explanation

```
N+E+R:-N<1,R=[];N-1+E+S,R=[E|S].   Make `R` a list containing `E` repeated `N` times
       N<1,R=[]                    If `N<1`, let `R` be the empty list
       N-1+E+S                     Else recurse with `N-1`, `E` and `S`
           R=[E|S]                 Let `R` be a new list with `E` as head and `S` as tail
N*E*R:-R=E,E=[];N<0,reverse(E,F),-N*F*R;[H|T]=E,N+H+S,N*T*U,append(S,U,R).
                                   Let `R` be a list
                                   with each element in `E` repeated `N` times
                                   e.g. 2*[3, 6] -> [3, 3, 6, 6]
       R=E,E=[]                    Let `R` be `E` if `E` is the empty list
       N<0,reverse(E,F)            Else if `N<0`, let `F` be the reverse of `E`
           -N*F*R                  Recurse with `-N`, `F` and `R`
       [H|T]=E                     Else let `H` be the head and `T` be the tail of `E`
           N+H+S                   Let `S` be `N+H+S` (our function, not addition)
           N*T*U                   Recurse with `N`, `T` and `U`
           append(S,U,R)           let `R` be the concatenation of `S` and `U`
N/E/R:-N<1,R=[];(E<N,D=E,F=32;D=E-N,F=35),N/2/D/C,R=[F|C].
                                   Make `R` the binary representation of `E`
                                   with `N` as the value of the current bit
                                   where 0 and 1 are space and hash respectively
    N<1,R=[]                       If `N<1` let `R` be the empty list
    (
        E<N,D=E,F=32               If `E<N` the bit isn't set, so `D=E`, `F=space`
        D=E-N,F=35                 Else `D=E-N`, `F=hash`
    )
        N/2/D/C                    Recurse with `N/2`, `D` and `C`
        R=[F|C]                    Let `R` be a new list with `F` as head and `C` as tail
[H|T]^X^Y^R:-128/H/A,X*A*B,Y*[[10|B]]*C,append(C,D),(T=[],R=D;T^X^Y^S,append(D,S,R)).
                                   Make `R` the result,
                                   with inputs being the list `[H|T]`
                                   and the scales `X` and `Y`
   128/H/A                         Let `A` be the binary representation of `H` (8 bits)
   X*A*B                           Let `B` be `A` with each element repeated `X` times
   Y*[[10|B]]*C                    Let `C` be `B` with a newline prepended,
                                   repeated `Y` times
   append(C,D)                     Let `D` be `C` flattened by one level (joining lines)
   (
       T=[],R=D                    If `T` is empty, let `R` be `D`
       T^X^Y^S                     Else recurse with `T`, `X`, `Y` and `S`
           append(D,S,R)           Let `R` be the concatenation of `D` and `S`
   )

```
> 3 votes

# Answer
# Charcoal, 28 bytes

```
ＦθＥ↔ζ⭆⮌↨ι²×§ Xμ↔ηＦ›η⁰‖Ｆ‹ζ⁰‖↓

```

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

```
Ｆθ

```

Loop over the list of bytes.

```
Ｅ↔ζ

```

Map over the vertical scaling factor, thus multiplying the output lines.

```
⭆⮌↨ι²×§ Xμ↔η

```

Convert the input to base 2, reverse it, map the digits to space and `X`, then multiply each character by the horizontal scaling factor.

```
Ｆ›η⁰‖

```

If the horizontal scaling factor was positive, reflect to get the image the correct way around again.

```
Ｆ‹ζ⁰‖↓

```

Reflect vertically if the vertical scaling factor was negative.
> 2 votes

# Answer
# C (clang), 120 bytes

```
k,w,l,_;f(*o,z,x,y){for(w=z*y;w;)for(k=w>0?z*y-w--:++w,_=l=8*x;_;putchar(_?o[k/y]>>(l>0?--l/x:7-++l/x)&1?88:46:10))_=l;}

```

Try it online!
> 2 votes

# Answer
# Common Lisp, 157 bytes

```
(lambda(l x y)(dolist(i(if(< y 0)(reverse l)l))(dotimes(j(abs y))(dotimes(n 8)(dotimes(k(abs x))(princ(if(logbitp(if(< x 0)n(- 7 n))i)"#"" "))))(princ"
"))))

```

Try it online!

### Explanation

```
(lambda(l x y)                           ; Lambda with parameters `l`, `x`, `y`
    (dolist
        (i                               ; For `i` in the list
            (if(< y 0)(reverse l)l)      ; The reverse of `l` if `y<0` else `l`
        )
        (dotimes(j(abs y))(dotimes(n 8)(dotimes(k(abs x))
                                         ; Do `y` times, for `n` from 0 to 7, do `x` times
        (princ(if(logbitp(if(< x 0)n(- 7 n))i)"#"" "))))
                                         ; If `x<0` and the `n`th bit is 1
                                         ; or `x>0` and the `7-n`th bit is 1
                                         ; print "#", else print " "
        (princ"
")                                       ; After every `y` loop, print a newline
        )
    )
)

```
> 2 votes

# Answer
# Tcl, 192 bytes

```
proc f {l x y} {lmap i [if $y<0 {lreverse $l} {lindex $l}] {time {lmap n {0 1 2 3 4 5 6 7} {time {puts -nonewline [expr $i&1<<($x<0?$n:7-$n)?{#}:{ }]} [expr abs($x)]};puts {}} [expr abs($y)]}}

```

Try it online!

```
proc f {l x y}                           Define a function `f` with arguments `l`, `x`, `y`
{lmap i                                  For each `i` in
    [if $y<0 {lreverse $l} {lindex $l}]  The reverse of `l` if `y<0` else `l`
    {
        time {                           Do `abs(y)` times
            lmap n {0 1 2 3 4 5 6 7} {   For `n` from 0 to 7
                time {                   Do `abs(x)` times
                    puts -nonewline      Print without newline
                         [expr $i&1<<($x<0?$n:7-$n)?{#}:{ }]
                                         If `x<0` and the `n`th bit is 1 or
                                         `x>0` and the `7-n`th bit is 1
                                         then return "#" else return " "
                } [expr abs($x)]
            };
            puts {}                      Print a newline
        } [expr abs($y)]
    }
}

```
> 2 votes

# Answer
# 8088 machine code, IBM PC DOS, ~~77~~ 71 bytes

**Assembled:**

```
B402 84FF 7906 FD03 F14E F6DF 518A CFAC 5051 B108 8AF3 84F6 7902 F6DE
518A CEB2 2384 DB79 04D0 C8EB 02D0 C072 02B2 2050 CD21 58E2 FA59 E2E4
B20D CD21 B20A CD21 5958 E2CC 59E2 C5

```

**Listing:**

```
    PR_BMP  MACRO BMP, SZBMP, ZX, ZY
            LOCAL LOOP_Y, LOOP_Y2, LOOP_X, LOOP_X2, X_POS, X_NEG
B4 02   MOV  AH, 2          ; DOS display char function
84 FF   TEST ZY, ZY         ; is Y scale negative?
79 06   JNS  LOOP_Y         ; if positive, start Y LOOP
FD      STD                 ; direction flag start from end
03 F1   ADD  BMP, CX        ; advance input byte array to end
4E      DEC  BMP            ; zero adjust index
F6 DF   NEG  ZY             ; make counter positive
     LOOP_Y:
51      PUSH CX             ; save outer byte loop counter
8A CF   MOV  CL, ZY         ; set up repeat counter (Y scale factor)
AC      LODSB               ; load byte into AL
     LOOP_Y2:
50      PUSH AX             ; save original AL
51      PUSH CX             ; save outer loop
B1 08   MOV  CL, 8          ; loop 8 bits
8A F3   MOV  DH, ZX         ; DH is positive X scale used as counter
84 F6   TEST ZX, ZX         ; is X scale negative?
79 02   JNS  LOOP_X         ; if so, make counter positive
F6 DE   NEG  DH             ; compliment X counter
    LOOP_X:
51      PUSH CX             ; save bit counter
8A CE   MOV  CL, DH         ; set repeat counter (X scale factor)
B2 23   MOV  DL, '#'        ; by default, display a #
84 DB   TEST ZX, ZX         ; is X scale negative?
79 04   JNS  X_POS          ; if so, rotate left 1 bit
D0 C8   ROR  AL, 1          ; else rotate right LSB into CF
EB 02   JMP  X_NEG          ; jump to examine CF
    X_POS:
D0 C0   ROL  AL, 1          ; rotate left MSB into CF
    X_NEG:
72 02   JC   LOOP_X2        ; is a 1?
B2 20   MOV  DL, ' '        ; if not, display a space
    LOOP_X2:
50      PUSH AX             ; save AL (since silly DOS overwrites it)
CD 21   INT  21H            ; display char
58      POP  AX             ; restore AL
E2 FA   LOOP LOOP_X2        ; loop repeat counter
59      POP  CX             ; restore bit counter
E2 E4   LOOP LOOP_X         ; loop bit counter
B2 0D   MOV  DL, 0DH        ; display CRLF
CD 21   INT  21H
B2 0A   MOV  DL, 0AH
CD 21   INT  21H
59      POP  CX             ; restore outer loop
58      POP  AX             ; restore original AL
E2 CC   LOOP LOOP_Y2        ; loop row display
59      POP  CX             ; restore byte counter
E2 C5   LOOP LOOP_Y         ; loop byte counter
    ENDM

```

This turned out to be more of a doozy in ASM than I originally thought. Multiple concurrent loops and lots of if/else branching can certainly give you headaches.

This is implemented as a MACRO since it allows function-like parameter passing for testing.

**Output**

Here is a test program for DOS that prompts for the X and Y scaling factor and draws to the screen. Note, scaling the dragon too much will scroll past the top since default DOS window is only 24 rows.

And here's our little dragon (duck):

**Try it Online!**

You can test in a DOS VM using DOSBox or VirtualConsoles.com with the following steps:

1. Download VCS.ZIP (contains all four executables)
2. Go to https://virtualconsoles.com/online-emulators/DOS/
3. Upload the ZIP file you just downloaded, click Start
4. Type `PLANE`, `KEY`, `TANK` or `DRAGON`.
> 2 votes

# Answer
# PowerShell, ~~146~~ 132 bytes

```
param($x,$y,$b)&($t={$b|%({$r+=,$_*$y},{$r=,$_*-$y+$r})[$y-lt0]
$r-ne$e})|%{$b=,$_*8|%{''+' X'[($_-shr$i++%8)%2]}
$y=-$x;-join(&$t)}

```

Try it online!

Unrolled:

```
param($x,$y,$bitmap)

$transform={
    $bitmap|%({$r+=,$_*$y},{$r=,$_*-$y+$r})[$y-lt0]
    $r -ne $empty
}

&$transform|%{                                  # $bitmap is an array of lines
    $bitmap=,$_*8|%{''+' X'[($_-shr$i++%8)%2]}  # $bitmap is an array of line pixels now
    $y=-$x                                      # reuse $y
    -join(&$transform)
}

```
> 2 votes

# Answer
# Perl 5, 105 bytes

```
($_,$h,$v)=@F;say for map{$_=reverse if$h<0;y/0/ /;s/./$&x abs$h/eg;($_)x abs$v}$v<0?reverse/\d+/g:/\d+/g

```

TIO

If input must be hex

126 bytes
> 1 votes

# Answer
# Jelly, 21 bytes

```
⁴²+BḊ€⁸m€Ṡ}¥xA}ZʋƒYo⁶

```

Try it online!

Assumes there is at most one command-line argument.
> 1 votes

# Answer
# APL (Dyalog Extended), 23 bytesSBCS

dzaima's method

Anonymous tacit prefix function. Takes \\$(v,h,B)\\$ as argument, where \\$v\\$ is the vertical scaling factor, \\$h\\$ is the horizontal scaling factor, and \\$B\\$ is the byte array as an 8-column packed bit-Boolean matrix (this is the normal and most compact way to represent raw bytes in APL). Requires `⎕IO←0` (zero based indexing).

```
' x'⊇⍨∘⊃{⊖⍣(>⍺)⍉⍵/⍨|⍺}/

```

Try it online!

`{``}/` reduce right-to-left using the following anonymous lambda:

`|⍺` the magnitude of the left argument (the scaling factor)

`⍵/⍨` use that to replicate the right argument horizontally

transpose

`⊖⍣(``)` flip if:

`>⍺` the scaling factor is less than zero

disclose (since reduction enclosed to reduce tensor rank from 1 to 0)

`' x'⊇⍨` select elements from the string " x" using that matrix
> 1 votes

# Answer
# T-SQL, 216 bytes

Before executing this MS-SQL Studio Management, press CRTL-t to show data as text. The height cannot be adjusted to exceed the number of elements in the input.

Because of the horrible implementation of STRING\_AGG, the height variable will only work in MSSM. MS should have made a third optional parameter to include the order of the elements being concatenated.

The online version can only support adjustment of the width. Height will result in a funky result with multiple stacking shapes.

```
USE master
DECLARE @ table(v int,i int identity)
INSERT @ values
(0x06),(0x0F),(0xF3),(0xFE),(0x0E),(0x04),
(0x04),(0x1E),(0x3F),(0x7F),(0xE3),(0xC3),
(0xC3),(0xC7),(0xFF),(0x3C),(0x08),(0x8F),
(0xE1),(0x3F)
-- @  = width
-- @h = height
DECLARE @s INT=1,@h INT=1

SELECT iif(@s>0,reverse(x),x)FROM(SELECT
string_agg(replicate(iif(v&n=0,' ','X'),abs(@s)),'')x,i,j
FROM(values(1),(2),(4),(8),(16),(32),(64),(128))x(n)
,@,(SELECT top(abs(@h))i j FROM @)g GROUP BY i,j)f
ORDER BY i*@h

```

This script will not show the correct shapes in the online version, so I made some minor adjustments to compensate. **Try it online**
> 1 votes

# Answer
# Ruby, 89 bytes

```
->b,w,h{y=h>0?-1:0;(b*h.abs).map{y+=1;[*1+8*w..0,*0...8*w].map{|x|' X'[b[y/h][x/w]]}*''}}

```

Try it online!
> 1 votes

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


# Question
Title: Compress 8 bits to 6 when certain bit patterns will never occur
Consider an eight bit number in which an even position bit will never be 1 if one of its neighbors is 0 (considering MSB and LSB as neighbors). There are fewer than 64 such numbers, so there is at least some reversible mapping of them to 6 bit numbers.

Your task is to write a pair of functions (or code blocks or your language equivalent), one of which takes an 8-bit number and returns a 6-bit number, the other which reverses the process. "Numbers" here can be literal numbers or a list of booleans or even a string of Xs and Os.

Put another way, the following bit patterns will never occur:

```
......01
.....10.
....01..
...10...
..01....
.10.....
01......
0......1

```

PS: I'd really love to see an answer in Lua :)

PPS: Bonus imaginary internet points if you can pack the 47 valid values into a 6-bit number with a maximum of value of 47

# Answer
> 20 votes
# Python, 60 bytes

```
l=[n^170for n in range(256)if n&n*2<1]
l.index,l.__getitem__

```

Try it online!

`l.index` compresses and `l.__getitem__` decompresses. We just make a list `l` of all valid patterns as 8-bit numbers, except we ignore wrapping around, which still leaves 55 options which fits in 6 bits.

A useful idea is that if we flip the bits at even positions, which `^170` does, then the condition just becomes "no two 1's are (cyclically) adjacent". This is easy to check without wrapping around using the bit condition `n&(n*2)==0`, or shorter, `n&n*2<1`.

**Fibonacci numbers**

Binary strings with no adjacent ones have interesting connections to Fibonacci numbers. The number of such 8-bit numbers is 55, a Fibonacci number, following the general result. Moreover, Zeckendorf's Theorem tell us that each number can be uniquely expressed in the Fibonacci base without using a pair of adjacent ones, that is as a sum of distinct Fibonacci numbers without two consecutive ones, as these can be merged into the next Fibonacci number.

Perhaps a base conversion to the Zeckendorf Representation can be used for a less brute-force answer than the one here. We've had challenges to convert from and to the Zeckendorf representation, which could be used as the basis of a decoder-encoder pair.

**Bonus: 64 bytes**

For imaginary internet points, we can tweak the algorithm to accounts for cyclically adjacent ones, so as to limit the compression to 48 valid bit patterns from 55. We do this by modifying the bit check to `n&n*2%255<1`, at the cost of 4 extra bytes.

*64 bytes*

```
l=[n^170for n in range(256)if n&n*2%255<1]
l.index,l.__getitem__

```

Try it online!

The modulo 255 changes the bit-shift `n*2` to a cyclic shift

```
abcdefgh -> bcdefgha

```

by moving the post-doubling place value of `256*a` to just `a`. This is, except for `n=255`, which where `n*2%255` is zero, giving a false positive at `255^170=85`. But, since the bonus for imaginary internet points gives use one spare slot, with 48 slots for 47 values, we can just live with this hole.

# Answer
> 6 votes
# K (ngn/k), 25 bytes (or 23 without imaginary internet points)

```
a:&&/1_|':9#2!(!8)+!8#2
a?

```

Try it online!

`8#2` is the list `2 2 2 2 2 2 2 2`

`!8#2` generates an 8x256 matrix whose columns represent the bits of 0,1,..,255

`!8` is `0 1 2 3 4 5 6 7`

`(!8)+` we add these to the corresponding rows in the matrix

`2!` mod 2

`9#` reshape to 9 rows, i.e. copy the first row after the last to ensure wrap-around (for internet points!)

`|':` boolean or each row with the row above it; with implicit 0 before the first

`1_` drop the first

`&/` boolean and-reduce over the rows - the result is a boolean mask of the encodable numbers

`&` where are the 1s in this mask - return list of ints

`a:` assign to `a`. the k language makes no distinction between function calls and list indexing, so `a` can act as the decompress function like this: `a 26` -\> `171`

`a?` is a function that looks up the position of its argument in `a`. this is our compress function: `a?171` -\> `26`

# Answer
> 4 votes
# Ruby, ~~131~~ 68 bytes

The most trivial answer, which generates all valid numbers (and a few extra values that aren't used) and finding the correct index.

Huge bytesaves thanks to GB, and also realizing I'm allowed to store the numbers list as a separate variable (?)

```
a=(0..255).select{|i|i.to_s(4)!~/1|30/}
d=->n{a[n]}
c=->n{a.index n}

```

Try it online!

### Imaginary bonus points, 72 bytes

```
a=(0..255).select{|i|"%08b"%(i^85)*2!~/00/}
d=->n{a[n]}
c=->n{a.index n}

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~25~~ 17 bytes

```
⁹Ḷ&Ḥ$Ðḟ^170
ị¢
Ñi

```

Try it online!

A set of links. The first link is shared and builds the list of possible valid 8-bit integers. The second link is the decompression link and the third handles compression. The footer compresses all the valid integers and then decompresses all the possible compressed values.

Saved 8 bytes by porting xnor’s Python answer with thanks!

# Answer
> 2 votes
# Ruby, ~~89 85~~ 74 bytes

```
a,b='14-7',"8abef"
f=->n{("%o"%n).tr(a,b).hex}
g=->n{("%x"%n).tr(b,a).oct}

```

Try it online!

Not going for the bonus points.

### How:

Encode and decode using an octal-hexadecimal conversion: since some patterns cannot occur, the only allowed hex digits are `[0,2,3,8,a,b,e,f]`. So, if we take the hex digits and translate them to their index in the array, we get a 1- or 2-digits octal number, that is in the range 0-63. We can invert the process to decode the number.

# Answer
> 2 votes
# 05AB1E (legacy), 16 bytes

### 05AB1E, 17 bytes

Port of xnor's Python answer. -1 byte on legacy thanks to Kevin Cruijssen.

Compression:

```
ÝƵζ^x&ć¢

```

Decompression:

```
µNƵζ^x&_

```

Modern 05AB1E uses the same compression code, but needs an additional `D` in the decompression:

```
µNDƵζ^x&_

```

TIO links:

# Answer
> 1 votes
# C++ (gcc), <sup>~~187~~ \\$\cdots\\$ ~~138~~</sup> 128 bytes

Saved 22 bytes thanks to S.S.Anne!!!
Saved 5 bytes thanks to ceilingcat!!!

```
struct F{int i,j,v[55];F(){for(i=j=0;j<55;++i)i&i*2?:v[j++]=i^170;}int c(int n){for(i=55;v[--i]-n;);n=i;}int d(int n){n=v[n];}};

```

Try it online!

Is a `class` `F` with member functions `c` and `d` for compression and decompression.
Uses xnor's algorithm.

# Answer
> 1 votes
# JavaScript (ES6), 58 bytes (with bonus: 65 bytes)

I couldn't find anything shorter than a port of xnor's answer with recursive functions.

### Encoder (30 bytes)

```
E=n=>n&&E(n-1)+!((n^=170)&2*n)

```

### Decoder (28 bytes)

```
D=(n,k=n)=>E(k)^n?D(n,k+1):k

```

Try it online!

### Bonus-compliant version, 65 bytes

With 7 more bytes in the encoder, we can output a value in \\$\[0..46\]\\$:

```
E=n=>n&&E(n-1)+!((n^=170)&2*n|n&n>>7)

```

Try it online!

---

# JavaScript (ES6), 68 bytes

Another version with recursive functions. The encoder is just as long, but the decoder is 10 bytes longer.

### Encoder (30 bytes)

```
E=n=>n&&n%16*17%61%9+8*E(n>>4)

```

### Decoder (38 bytes)

```
D=n=>n&&596357088>>n%8*4&15|16*D(n>>3)

```

Try it online!

### How?

As already pointed out by G B, there are only 8 valid nibbles for the input. We apply the following formula to map each of them to a unique value in \\$\[0..7\]\\$:

$$f(n)=((n\times17)\bmod61)\bmod9$$

Which gives:

```
 bin  | hex | dec | *17 | mod 61 | mod 9
------+-----+-----+-----+--------+-------
 0000 |  0  |   0 |   0 |    0   |   0
 0010 |  2  |   2 |  34 |   34   |   7
 0011 |  3  |   3 |  51 |   51   |   6
 1000 |  8  |   8 | 136 |   14   |   5
 1010 |  A  |  10 | 170 |   48   |   3
 1011 |  B  |  11 | 187 |    4   |   4
 1110 |  E  |  14 | 238 |   55   |   1
 1111 |  F  |  15 | 255 |   11   |   2

```

Therefore, the input \\$N\\$ can be encoded as:

$$f(N\bmod 16) + 8\times f(\lfloor N/16\rfloor)$$

which gives a unique value in \\$\[0..63\]\\$.

The decoder retrieves the original nibbles by using the number `0x238BAFE0` (in decimal: \\$596357088\\$) as a lookup table.

The conversion could also be done with this code:

```
(n&&n<3?n+9:44/n|4)^4

```

Try it online!

But this is even longer.

# Answer
> 1 votes
# Lua 5.3, ~~124~~ ~~122~~ 121 bytes

```
s,l=string,""for n=0,255 do l=n&n*2<1 and l..s.char(n~170)or l end
f=function(n)return l:find(s.char(n),1,1),l:byte(n)end

```

Try it online!

Algorithm from xnor, ported to the requested language of Lua. This will only work on 5.3+, but you can get 5.2 compatibility for 24 extra bytes:

```
s,l=string,""for n=0,255 do l=bit32.band(n,n*2)<1 and l..s.char(bit32.bxor(n,170))or l end
f=function(n)return l:find(s.char(n),1,1),l:byte(n)end

```

`f()` does both encoding and decoding; the first return value is for encoding and the second is for decoding. If you want separate functions for both, you can use this instead of the second line (+23 bytes):

```
e,d=function(n)return l:find(s.char(n),1,1)end,function(n)return l:byte(n)end

```

This version of the algorithm varies slightly from the original by using a string to store the map rather than a list, which allows using `string.find` to search for the item. `string.char`/`string.byte` also make it easy to switch between number and string formats.

# Answer
> 1 votes
**Haskell** (85 bytes)

The silly version that maps to at most 54:

```
import Foreign
p y=2*y.&.y<1
d=filter(p.xor 170)[0..255]
f x=sum[1|y<-d,y<x]
g=(d!!)

```

`f` encodes a byte and `g` decodes.

The next version should be much faster, consists of a bit of bit manipulation, but covers the range from 0 to 63 and requires 92 bytes:

```
(#)=div
(&)=mod
(k%j)e x=k*e(x#j)&k+e(x&j)&k
f=8%16$(#128).(453*)
g=16%8$(737715168#).(16^)

```

Here is the expanded, hopefully more comprehensible version:

```
module Compress8to6Bit where

import Data.Bits (xor, shiftL, shiftR, (.|.), (.&.))
import Data.Word (Word8)

import qualified Test.QuickCheck as QC

{-
> map compressNibble [0,2,3,8,10,11,14,15]
[0,7,2,4,3,6,1,5]
-}
compressNibble :: Int -> Int
compressNibble x = shiftR (453*x) 7 .&. 7

compress :: Int -> Int
compress x =
   shiftL (compressNibble (shiftR x 4)) 3  .|.  compressNibble (x .&. 15)

decompressNibble :: Int -> Int
decompressNibble x = shiftR 0x2BF8A3E0 (x*4) .&. 15

decompress :: Int -> Int
decompress x =
   shiftL (decompressNibble (shiftR x 3)) 4  .|.  decompressNibble (x .&. 7)

inverseProp :: Word8 -> QC.Property
inverseProp byte =
   let k = fromIntegral byte
       kx = xor 0xAA k
   in kx .&. shiftL kx 1 == 0
      QC.==>
      k == decompress (compress k)

```

**How?**

I found the multiplication trick of Arnauld interesting and found that you can do without modulo but simple shift and masking when using the factor 453.

But after all you could also encode dictionaries for compression and decompression (on a 32-bit machine you need to use Int64 instead of Int):

```
compressNibble :: Int -> Int
compressNibble x = shiftR 0o7600540300002100 (x*3) .&. 7

decompressNibble :: Int -> Int
decompressNibble x = shiftR 0xFEBA8320 (x*4) .&. 15

```

This one only needs 16 bit for the dictionary but requires `popCount`:

```
compressNibble :: Int -> Int
compressNibble x = popCount (0x6686 .&. (shiftL 1 x - 1) :: Int)

```

# Answer
> 1 votes
# Ruby, 88 bytes

**(with imaginary bonus points)**

```
a=[170]+(6..51).map{|i|"UJEBA@D"[i/8].ord*257>>i%8&255^170}
f=->n{a[n]}
g=->n{a.index n}

```

76 bytes if it is OK to check the array `a` directly instead of using `f` to do it.

Try it online!

I can't beat GB's excellent answer, but this is the shortest Ruby answer claiming the imaginary bonus points so far.

The question asks for all bytes where the even bits are less or equal to than the adjacent odd bits. An equivalent definition is all bytes where the odd bits are greater than or equal to the adjacent even bits, so overall the set is symmetrical.

There is only one possible byte where all even bits are strictly less than the adjacent odd bits, this is `10101010`, decimal 170. The other 46 bytes where the even bits are less than or equal to the adjacent odd bits can be found by `XOR`ing this number with all possible bytes with no adjacent `1`'s. These comprise 7 distinct patterns and their bitwise rotations as listed below.

We build an array of the 47 bytes by `XOR`ing `10101010` with the patterns below, then use lookup and index functions to carry out the conversion.

```
Pattern  ASCII number of rotations
01010101  U    2
01001010  J    8
01000101  E    8
01000010  B    8
01000001  A    8
01000000  @    8
01000100  D    4

Total 46 (plus 00000000)

```

# Answer
> 0 votes
# Charcoal, 54 bytes

```
Ｆ²⁵⁶Ｆ¬＆ι⊗ι⊞υ⁻｜ι¹⁷⁰＆ι¹⁷⁰Ｉ⌕υＮ

```

Try the encoder online! Link is to verbose version of code.

```
Ｆ²⁵⁶Ｆ¬＆ι⊗ι⊞υ⁻｜ι¹⁷⁰＆ι¹⁷⁰Ｉ§υＮ

```

Try the decoder online! Link is to verbose version of code.

Just the usual table-driven lookup approach. Explanation:

```
Ｆ²⁵⁶

```

Loop over the 256 binary values.

```
Ｆ¬＆ι⊗ι

```

Check that no two adjacent bits are set.

```
⊞υ⁻｜ι¹⁷⁰＆ι¹⁷⁰

```

Flip the odd bits and save the result to the lookup table.

```
Ｉ⌕υＮ

```

Look up the index of the input in the table.

```
Ｉ§υＮ

```

Look up the input index in the table.

Rather than create a table of Fibbinary numbers by filtering out invalid numbers, I attempted a mathematical approach which calculates successive Fibbinary numbers, but the encoder was 48 bytes and the decoder was 40 bytes:

```
≔⁰η≔⁰ζＷ⁻⁻｜η¹⁷⁰＆η¹⁷⁰θ«≦⊕ζ≔⊕｜η÷η²ι≧＆±ιι≔×ι⊕÷ηιη»Ｉζ
≔⁰ηＦＮ«≔⊕｜η÷η²ι≧＆±ιι≔×ι⊕÷ηιη»Ｉ⁻｜η¹⁷⁰＆η¹⁷⁰

```

Explanation:

```
≔⁰η

```

Initialise the Fibbinary number `h` to `0`.

```
≔⁰ζＷ⁻⁻｜η¹⁷⁰＆η¹⁷⁰θ«≦⊕ζ

```

(Encoder) Initialise the encoding index to `0`. Repeat until the desired Fibbinary number is found. Increment the encoding index...

```
ＦＮ«

```

(Decoder) Repeat the desired number of times.

```
≔⊕｜η÷η²ι≧＆±ιι≔×ι⊕÷ηιη»

```

Find the lowest value of `k` where `h&3<<k` is zero. Clear the bottom `k` bits of `h` and increment the next bit, which gives the next Fibbinary number.

```
Ｉζ

```

(Encoder) Output the number of loops taken.

```
Ｉ⁻｜η¹⁷⁰＆η¹⁷⁰

```

(Decoder) Output the XOR of the Fibbinary number with 170.

---
Tags: code-golf, bitwise, lua
---


title: Computational Parity Party!

text:
# Question
Title: Computational Parity Party!
The computational parity of an integer is defined as 1 if the integer has an odd number of set bits, and 0 otherwise. (src).

## Input

* You will receive one nonnegative integer that you will take the parity of. Optionally, you may take the size of the integer in bytes or bits as an argument, but you must specify this in your answer.

## Output

* You will output the computational parity of the input integer.

## Rules

## Test cases

You may omit any input that cannot be represented with your language's built-in integer type.

```
0: 0
1: 1
3: 0
8: 1
13: 1
17: 0
40: 0
52: 1
100: 1
127: 1
365: 0
787: 1
2898: 0
6345: 0
9038: 1
10921: 1
16067: 1
4105748: 1
40766838: 0
1336441507: 1
4294967295: 0

```

Generated using this program.

The answer with the least amount of bytes in each language wins, which means that I will not be accepting an answer.

Bonus imaginary Internet points for an explanation.

Sandbox link (10k+)

# Answer
# JavaScript (ES6),  ~~18~~  17 bytes

Similar to my answer to Is this number evil? except that the last iteration returns \\$0\\$, which saves a byte.

```
f=n=>n&&!f(n&~-n)

```

Try it online!

---

# JavaScript (ES6), 30 bytes

Converts to binary, parses as base-3 and returns the parity.

```
n=>parseInt(n.toString(2),3)&1

```

Try it online!
> 3 votes

# Answer
# Jelly, 3 bytes

```
BSḂ

```

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

### How?

```
BSḂ - Link: non-negative integer
B   - to binary
 S  - sum
  Ḃ - least-significant-bit

```
> 2 votes

# Answer
# Python, 27 bytes

```
f=lambda n:n and 1-f(n&~-n)

```

**Try it online!**

This is quite nice because if we just want to *identify* the parity we can reduce it to **25 bytes** returning `0` or `-1`:

```
f=lambda n:n and~f(n&~-n)

```
> 2 votes

# Answer
# Python 2, 27 bytes

```
f=lambda n:n and n&1^f(n/2)

```

Try it online!
> 1 votes

# Answer
# Fortran (GFortran), 28 bytes

```
read*,i
print*,poppar(i)
end

```

Try it online!

Fortran has this as an in-built since F2008
> 1 votes

# Answer
# 05AB1E, 5 4 bytes

```
bSOÉ

```

Try it online!

## Explanation

```
bSOÉ

b    # convert (implicit) input to base 2
  O  # the sum of...
 S   # the digits...
   É # is odd?

```
> 1 votes

# Answer
# Oasis, 4 bytes

```
ES2%

```

Try it online!

## Explanation

```
ES2%

 S    # the sum of...
E     # the binary digits...
  2%  # mod 2

```
> 1 votes

# Answer
# Ruby, 19 bytes

```
->n{("%b"%n).sum%2}

```

Try it online!
> 1 votes

# Answer
# C (gcc), <sup>~~34~~</sup> 21 bytes

Saved 13 bytes thanks to Arnauld!!!

```
f(n){n=n&&!f(n&n-1);}

```

Try it online!
> 0 votes

# Answer
# Python 3, 28 bytes

```
lambda n:bin(n).count('1')%2

```

Try it online!
> 0 votes

# Answer
# Japt `-h!`, 3 bytes

```
¤ä^

```

Try it here
> 0 votes

# Answer
# JavaScript, 18 bytes

Port of ovs' Python solution \- be sure to `+1` that if you're `+1`ing this.

```
f=n=>n&&n&1^f(n/2)

```

Try it online!
> 0 votes

# Answer
# PHP, 39 bytes

```
for(;$n=&$argn;$n/=2)$p+=$n|0;echo$p%2;

```

Try it online!
> 0 votes

---
Tags: code-golf, bitwise
---