title: Hexadecimal -> Binary Art

text:
# Question
Title: Hexadecimal -> Binary Art
*Take a list of 2-digit hexadecimal numbers as input, and output the binary value, replacing each 1 with an 'X', and each 0 with a space.*

**For example**

Input = `FF, 81, 47, 99`.

* `FF` = `11111111` in binary, so print `XXXXXXXX`
* `81` = `10000001` in binary, so print `X X`
* `47` = `01000111` in binary, so print  `X XXX`
* `99` = `10011001` in binary, so print `X XX X`

Full output:

```
XXXXXXXX
X      X
 X   XXX
X  XX  X

```

**Clarifications**

* The hexadecimal numbers will always be 2-digits.
* There can be any number of hexadecimal numbers.
* You can choose to input in whatever format you want (separated by a space, comma, newline, etc.)
* The character to output for a `1` is `X`, and for `0` it is a . This will not change.
* The outputs must be padded to length 8

Also, apparently I wasn't clear enough: **the input is in Hexadecimal (Base 16) *not denary (Base 10)***

**This is , so the shortest answer in bytes wins!**

# Answer
> 9 votes
# Python, 58 bytes

```
while 1:print(f"{int(input(),16):08b}".translate(" X"*99))

```

Attempt This Online!

Takes each hex code on a new line from input, prints to standard out. Terminates on error (is that allowed?)

---

# Python, 67 bytes

```
lambda n:"\n".join(f"{int(x,16):08b}".translate(" X"*99)for x in n)

```

Attempt This Online!

Takes input as a list of hex strings and returns a string with newlines separating lines.

# Answer
> 13 votes
# Excel (ms365), ~~74~~, ~~72~~, ~~59~~, 58 bytes

-14 Byte thanks to @jdt

```
=SUBSTITUTE(SUBSTITUTE(HEX2BIN(+A1:A4,8),"0"," "),"1","X")

```

---

Original answer using `BYROW()` for 71 bytes:

```
=BYROW(A:A,LAMBDA(a,CONCAT(IF(-MID(HEX2BIN(a,8),ROW(1:8),1),"X"," "))))

```

# Answer
> 10 votes
# Ruby `-p`, ~~40~~ 31 bytes

Takes input on stdin separated by newlines.

```
$_=("%08b
"%$_.hex).tr"01"," X"

```

Attempt This Online!

# Answer
> 5 votes
# Japt `-mR`, 9 bytes

```
nG" X" ù8

```

Try it

```
nG" X" ù8    :Implicit map of input array
n            :Convert from base
 G           :16
  " X"       :To base " X"
        ù8   :Left pad with spaces to length 8
             :Implicit output joined with newlines

```

# Answer
> 5 votes
# JavaScript (ES6), 60 bytes

*-1 thanks to @MatthewJensen*

Expects a list of 2-character hexadecimal strings.

```
a=>a.map(s=>(g=k=>k--?" X"['0x'+s>>k&1]+g(k):'')(8)).join`
`

```

Try it online!

### Commented

```
a =>             // a[] = input array
a.map(s =>       // for each string s in a[]:
  ( g = k =>     //   g is recursive function taking a counter k
    k-- ?        //   if k is not equal to 0 (decrement it afterwards):
      " X"[      //     append either ' ' or 'X':
        '0x' + s //       parse s as a hexadecimal string
        >> k     //       right-shift it by k position
        & 1      //       and isolate the least significant bit
      ]          //     end of lookup
      + g(k)     //     append the result of a recursive call
    :            //   else:
      ''         //     stop the recursion
  )(8)           //   initial call to g with k = 8
).join`\n`       // end of map(); join with line-feeds

```

# Answer
> 5 votes
# Retina 0.8.2, ~~61~~ 57 bytes

```
.
   $&
 (?=..[89A-F]|.[4-7C-F]|[2367ABEF])
X
+T`dA-F` Xo

```

Try it online! Explanation:

```
.
   $&

```

Precede each digit with three spaces.

```
 (?=..[89A-F]|.[4-7C-F]|[2367ABEF])
X

```

Replace the spaces with `X`s where appropriate.

```
+T`dA-F` Xo

```

Reduce the remaining digit modulo 2 and replace with space or `X` as appropriate.

# Answer
> 5 votes
# Perl 5, `-p` 30 bytes

```
$_=sprintf"%08b
",hex;y/01/ X/

```

Pretty much identical to Jordan's Ruby answer

Try it online!

# Answer
> 5 votes
# sed 4.2.2, `-E` ~~178~~ 141 bytes

```
s/./&FEDCBA9876543210:/g
s/(\w)\w*\1//g
s/\w/ /g
s/ +/&&&&/
s/ +/&&&&/
s/://
:
s/^(.+)\1:/\1: /
s/^ (.*)\1:/\1:X/
t
s/://
:z
s/^.{,7}$/ &/
tz

```

Takes newline-separated input

-35 thanks to DLosc

### Explanation

```
s/./&FEDCBA9876543210:/g  add hex digits to each input char
s/(\w)\w*\1//g            find index of input char in hex string
s/\w/ /g                  left is 2 strings which lengths corresponds to the input
s/ +/&&&&/
s/ +/&&&&/                multiply first strings' length by 16
s/://                     add the 2 strings, left is a unary number
:
s/^(.+)\1:/\1: /          convert to base 2, one bit at a time
s/^ (.*)\1:/\1:X/
t
s/://
:z
s/^.{,7}$/ &/             pad with spaces until length > 7
tz

```

# Answer
> 5 votes
# Brainfuck, 442 bytes

```
++++++++++>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<<+>+>-]<----------------------------<++++++++++++++++++++++++++++>>,[------------------------------------------------[-[-[-[-[-[-[-[-[-[--------[-[-[-[-[-[<<<.>>>[-]>]<[<....>>]>]<[<...>.>]>]<[<..>.<.>>]>]<[<..>..>]>]<[<.>.<..>>]>]<[<.>.<.>.>]>]<[<.>..<.>>]>]<[<.>...>]>]<[.<...>>]>]<[.<..>.>]>]<[.<.>.<.>>]>]<[.<.>..>]>]<[..<..>>]>]<[..<.>.>]>]<[...<.>>]>]<[....>],]

```

Attempt This Online!

The input can be separated by every character with a value bigger than 'F'.

```
The working section looks like this:
| '\n' | 'X' | ' ' | {input character} | 0 (used for stopping loops) |

prepare the initial state
++++++++++ newline

prepare space and X
>>> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [<<+>+>-]
< ---------------------------- space
< ++++++++++++++++++++++++++++ X

Go to start position and read char
>>,
[
  subtract '0'
  ------------------------------------------------
  [ if !0
    -[ if !1
      -[ if !2
        -[ if !3
          -[ if !4
            -[ if !5
              -[ if !6
                -[ if !7
                  -[ if !8
                    -[ if !9
                      subtract difference between 'A' and '9'
                      -------
                      -[ if !A
                        -[ if !B
                          -[ if !C
                            -[ if !D
                              -[ if !E
                                -[ if !F
                                  print newline
                                  <<<.>>>
                                  clear input character
                                  [-]>
                                ]
                                <[ print 'F' <....>> ]>
                              ]
                              <[ print 'E' <...>.> ]>
                            ]
                            <[ print 'D' <..>.<.>> ]>
                          ]
                          <[ print 'C' <..>..> ]>
                        ]
                        <[ print 'B' <.>.<..>> ]>
                      ]
                      <[ print 'A' <.>.<.>.> ]>
                    ]
                    <[ print '9' <.>..<.>> ]>
                  ]
                  <[ print '8' <.>...> ]>
                ]
                <[ print '7' .<...>> ]>
              ]
              <[ print '6' .<..>.> ]>
            ]
            <[ print '5' .<.>.<.>> ]>
          ]
          <[ print '4' .<.>..> ]>
        ]
        <[ print '3' ..<..>> ]>
      ]
      <[ print '2' ..<.>.> ]>
    ]
    <[ print '1' ...<.>> ]>
  ]
  <[ print '0' ....> ]
  read next input
  ,
]

```

# Answer
> 4 votes
# Vyxal, ~~10~~ 8 bytes

```
H‛ Xτ8↳⁋

```

Try it Online!

-2 thanks to Steffan

Port of Japt.

# Answer
> 4 votes
# C (clang), ~~80~~ 74 bytes

```
i;f(**b){for(i=8;*b;)putchar(i--?strtol(*b,0,16)&1<<i?88:32:(b++,i=8)+2);}

```

-3 bytes thanks to Arnauld!!

Try it online!

### Alternative method proposed by Arnauld:

# C (clang), 73 bytes

```
i;f(**b){while(*b)putchar(++i%9?strtol(*b,0,16)&1<<8-i%9?88:32:!++b+10);}

```

Try it online!

This will only work correctly for the first 477,218,588 lines.

# Answer
> 4 votes
# Husk, ~~34~~ ~~31~~ 28 bytes

```
mȯötm!"X "ḋ+256B16m€f□…"1F"w

```

Try it online!

Takes input as a space-separated argument
Husk is missing some useful functions such as pad and hex which makes this answer so long, or maybe I'm just bad.
-3 DLosc
-3 Razetime

### Explanation

```
mȯötm!"X "ḋ+256B16m€f□…"1F"w
                           w  split on spaces
mȯö                           map the following ultra composed penta-function
                  m€f□…"1F"   map input to indices the generated string "1-9A-F"
               B16            convert from digits in base 16
           +256               add 256 to make the binary string 9 chars long
          ḋ                   convert to digits in base 2
    m!"X "                    index into "X ", one-indexed modular
   t                          chop of first bit
                              implicit output joined on newlines

```

# Answer
> 3 votes
# Python, 89 bytes

```
lambda n:[print(bin(int(i,16))[2:].zfill(8).replace("1","X").replace("0"," "))for i in n]

```

Function which takes in a list of hexadecimal strings.

Try it online!

# Python, 98 bytes

```
[print(*('X'if int(b)else' 'for b in bin(int(a,16))[2:].zfill(8)),sep='')for a in input().split()]

```

Takes input itself, no header/footer code.

Try it online!

# Answer
> 3 votes
# Factor, 60 bytes

```
[ [ hex> "%08b"sprintf "10""X "zip substitute print ] each ]

```

Try it online!

* `[ ... ] each` Call `[ ... ]` on each hex string in the input sequence
* `hex>` convert from hex to decimal
* `"%08b"sprintf` format as a binary number string left-padded with spaces 8 wide
* `"10""X "zip` create the following associative mapping: `{ { 49 88 } { 48 32 } }`
* `substitute` substitute characters in the binary string according to the mapping
* `print` print to stdout with a newline

# Answer
> 3 votes
# MATL, 10 bytes

```
1ZA8&B88*c

```

Try it online!

### How it works

```
      % Implicit input: cell array of char vectors.
1ZA   % Convert each char vector to number. Gives a numeric vector
8&B   % Convert each number to 8-digit binary. Gives an 8-column binary matrix
88*   % Multiply each element by 88 (ASCII code of 'X')
c     % Convert to char
      % Implicit display. char(0) is displayed as space

```

# Answer
> 3 votes
# Charcoal, 13 bytes

```
ＷＳ⟦◧⍘⍘↧ι¹⁶ X⁸

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
ＷＳ              Loop over all lines of input
  ⟦             Output each result on its own line
       ι        Current line
      ↧         Lowercased
     ⍘  ¹⁶      Converted from base `16`
    ⍘      X    Converted to custom base ` X`
   ◧        ⁸   Left padded to length `8`

```

# Answer
> 3 votes
# APL(Dyalog Unicode), 29 bytes SBCS

```
⍉' X'⌷⍨∘⊂2⊥⍣¯1(16⊥(⎕D,⎕A)∘⍳)¨

```

Try it on APLgolf!

# Answer
> 3 votes
# K (ngn/k), 45 bytes

```
{"\n"/|'8$|'" X"@+2\16/+"0123456789ABCDEF"?x}

```

Try it online!

This is way too long...

# Answer
> 3 votes
# Bash \+ coreutils + dc, ~~68~~ ~~58~~ 51 bytes

Takes input as arguments.

-10 bytes thanks to Steffan
-7 bytes thanks to manatwork

```
for a;{
printf "%08s
" `dc<<<2o16i$a?n`|tr 01 \ X
}

```

Try it online!

# Answer
> 2 votes
# Pip `-l`, 17 bytes

```
" X"@S*TDgFB16+E8

```

Takes the hex pairs as command-line arguments. Try It Online!

### Explanation

```
" X"@S*TDgFB16+E8
         g         ;; List of command-line arguments
          FB16     ;; Converted (each) from base 16
              +    ;; Add (to each):
               E8  ;; 2 to the 8th power (256)
       TD          ;; Convert (each) to binary as a list of digits
     S*            ;; Get all but the first element of each
" X"@              ;; Use those 0's and 1's to index into this string

```

The result is a depth-2 nested list of spaces and X's. The `-l` flag concatenates each sublist together and outputs it on a separate line. (For a flagless version, add `P*` to the beginning of the code and `u` to the end.)

# Answer
> 2 votes
# simply, 88 bytes

It's a long mess, but *works*!
(I've used `\n` for style, but an actual newline works as well, and that is reflected in the size of the answer.)

```
fn($L){$T=" X\n"&array_map($L,fn($V)each$x in run&format("%'08s2"&cb($V,16,2))out$T[$x])}

```

Creates an anonymous function that **outputs** the result.

This works by left-padding all binary values to 8 characters, then ends with "2".
For each character of the binary string, it outputs the *n* character in the string `" X\n"`.
For 0 outputs `" "`, for 1 outputs `"X"` and for 2 outputs `"\n"`.

## Example

```
$fn=fn($L){$T=" X\n"&array_map($L,fn($V)each$x in run&format("%'08s2"&cb($V,16,2))out$T[$x])};

run $F(["FF", "81", "47", "99"]);

```

Should output the expected result.

## Slightly more readable

Both versions do exactly the same.

```
fn($list) => {
    &array_map(
        $list, fn($line) => {
            $translation = " X\n";
            $temp = call &format("%'08s2", &convert_base($line, 16, 2));
            each $char in $temp {
                echo $translation[$char];
            }
        }
    );
}

```

For some reason, JavaScript doesn't like the original order, when I untangle the code.

# Answer
> 2 votes
# Knight, 75 bytes

```
;=fB;=n 4W+=n-nT1O I%/-aI>60a 48 55^2n 2'X\'' \'W=pP;=aAp;Cf;=aA GpT1;CfO''

```

Try it online!

Input each hexidecimal value on a separate line.

Could be a bit shorter if it isn't required to output X's and spaces:

### Knight, 72 bytes

```
;=fB;=n 4W+=n-nT1O++''%/-aI>60a 48 55^2n 2'\'W=pP;=aAp;Cf;=aA GpT1;CfO''

```

Try it online!

# Answer
> 2 votes
# PowerShell, 63 bytes

```
%{[convert]::ToString("0x1$_",2)}|% S*g 1|% *ce 1 X|% *ce 0 ' '

```

Try it online!

Input comes from the pipeline.
Pretty straightforward; converts to binary, replaces 0 and 1.

```
%{[convert]::ToString("0x1$_",2)}|% S*g 1|% *ce 1 X|% *ce 0 ' '
%{                              }                               # % is an alias for ForEach-Object, which processes the scriptblock {...} for each string coming in from the pipeline.
  [convert]::ToString("0x1$_",2)                                # converts the hexadecimal string in $_ to binary, with a leading 1 to avoid padding (saves one byte)
                                 |% S*g 1                       # pipe the binary string to ForEach-Object again, and call the MemberName method Substring(1), stripping off the leading "1"
                                         |% *ce 1 X|% *ce 0 ' ' # Pass the binary string through two more calls of the MemberName Replace(); output is implicit.

```

# Answer
> 2 votes
# C# 10 (.NET 6) and later, 184 bytes

Doesn't work in TIO as it doesn't support .NET 6.

```
foreach(var i in Console.ReadLine().Split(',')){var a=Convert.ToString(Convert.ToInt32(i,16),2).Replace("1","X").Replace("0"," ");a=new string(' ',8-a.Length)+a;Console.WriteLine(a);}

```

Asks for the hex numbers as input when started.

Output:

```
FF,81,47,99
XXXXXXXX
X      X
 X   XXX
X  XX  X

```

Ungolfed version:

```
var input = Console.ReadLine();                           // Ask for input
foreach (var i in input.Split(',')) {                     // Split with a comma, and for each part:
    var hex = Convert.ToInt32(i, 16);                     // Convert it to an integer
    var bin = Convert.ToString(hex, 2);                   // Convert it to it's binary representation
    var art = bin.Replace("1", "X").Replace("0", " ");    // Replace 1 with X, 0 with a space
    var padding = new string(' ', 8 - art.Length);        // Repeat a space as much as needed for padding
    art = padding + art;                                  // Append the padding to the start of the art string
    Console.WriteLine(art);                               // Write the final result
}

```

## Function version (155 bytes)

Thanks to Seggan for the suggestion.

```
void art(int[] n){foreach(var i in n){var a=Convert.ToString(i,2).Replace("1","X").Replace("0"," ");a=new string(' ',8-a.Length)+a;Console.WriteLine(a);}}

```

Try it online!

Usage and output:

```
art(new int[] { 0xFF, 0x81, 0x47, 0x99 });
/* gives this output:
XXXXXXXX
X      X
 X   XXX
X  XX  X*/

```

# Answer
> 2 votes
# , 26 bytes

```
' X'{~(8#2)#:[:".'16b'&,&>

```

Tacit function that expects a list of boxes using `[0-9a-f]`.

Attempt This Online!

```
' X'{~(8#2)#:[:".'16b'&,&>
                 '16b'&,&>  : prepend '16b' to each input cell and unbox
               ".           : Do, eval the list of strings
             [:             : Cap, makes do and the prepend eval as f(g(x))
      (8#2)#:               : convert to binary and pad to length 8
' X'{~                      : use result to index into ' X'

```

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
Hb8j»T„X ‡

```

Try it online.

Or alternatively:

```
H„ XÅвJ8j»

```

Try it online.

**Explanation:**

```
H          # Convert the values in the (implicit) input-list from hexadecimal to integers
 b         # Then convert those base-10 integers to binary
  8j       # Pad leading spaces so all become length 8
    »      # Join the list with newline delimiter
         ‡ # Transliterate all
     T     # 10
      „X   # to "X ", replacing all 1s with "X" and 0s with " "
           # (after which the result is output implicitly)

H          # Convert the values in the (implicit) input-list from hexadecimal to integers
 „ XÅв     # Convert each integer to custom base-" X", which basically means to
           # base-length (2 in this case) and then indexing into the string
      J    # Join the inner character-lists to strings
       8j» # Same as above
           # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Rust, 99 bytes

```
|a|a.map(|s|format!("{:>8b}",u8::from_str_radix(&s,16).unwrap()).replace('0'," ").replace('1',"X"))

```

Try it online!

Can be assigned a variable of type `fn(std::vec::IntoIter<String>)->_`

# Answer
> 1 votes
# sed `-E`, ~~131~~ 121 bytes

*-10B thanks to @Neil*

```
s/./X&/g
s/X([0-7])/ \1/g
y/89ABCDEF/01234567/
s/[4-7]/X&/g
s/[0-3]/ &/g
s/[2367]/X&/g
s/[0145]/ &/g
y/01234567/ X X X X/

```

Attempt This Online!

# Answer
> 1 votes
# Nibbles, ~~10~~ 9.5 bytes (19 nibbles)

```
>>.``@hex:1@=$"X "

```

```
>>.``@hex:1@=$"X "
                     # implicit map over lines of input:
         :1@         # prepend with 1
      hex            # get the hexadecimal value
   ``@               # convert to binary digits
  .                  # and use each of these
            =$       # to index into
              "X "   # letters of the string "X ";
>>                   # finally, remove the first element

```

# Answer
> 1 votes
# Windows Batch, 145 bytes

Length calculated by using Unix/LF as EOL, without an EOL at the end of the last line.

```
:s
@if %1.==. exit/b
@set/an=0x%1&set b=
:w
@set/ar=n%%2&set/an/=2
@set b=%r%%b%
@set b=%b:0=.%&if %b:~7,1%.==. goto w
@echo.%b:1=X%&shift&goto s

```

Input as command line parameters.

### Ungolfed

The `@` suppresses the output of the command currently processed that would otherwise be echoed; "@echo off\n" would use 10 bytes, so suppressing lines individually is cheaper.

```
:s                      &REM Start label
@if %1.==. exit/b       &REM Leave if no more parameter from the command line
@set /a n=0x%1          &REM set n to the value of the first parameter (%1) as hexadecimal ("set /a" is an arithmetic operation)
@(set b=)               &REM Clear b (the output string)
:w                      &REM Start of the loop to calculate the binary representation of n
@set /a r=n%%2          &REM Set r to the remainder of n/2; % is the modulo operator, which must be doubled inside a batch script
@set /a n/=2            &REM Divide n by 2
@set b=%r%%b%           &REM Add the remainder to the output string
@set b=%b:0= %          &REM Replace every 0 in the output string with a space
@if %b:~7,1%.==. goto w &REM If the eight character in the output string is not set yet, continue with the conversion
@echo.%b:1=X%           &REM Replace every 1 in the output string with an X, and write the string
@shift                  &REM Shift the command line parameters to the left (former %2 is now %1, etc.)
@goto s                 &REM Lather, rinse, repeat

```

```
D:\cmd>.\CGSE_252379.cmd FF 81 47 99
XXXXXXXX
X      X
 X   XXX
X  XX  X

```

# Answer
> 1 votes
# sh + coreutils, ~~82~~ 72 bytes

```
xxd -r -p|xxd -b|sed -E "s/^.{10}(.{53}).*/\1/g;s/ *$//g"|tr 01\  \ X\\n

```

Try it online!

# Answer
> 1 votes
# Red, 82 bytes

```
func[b][forall b[parse s: enbase/base b/1 2[8[change"1""X"| change"0"sp]]print s]]

```

Try it online!

# Answer
> 1 votes
# Thon `-el`, 16 bytes

```
C{16D" X"b8" "JO

```

**Explanation:**

```
C{16D" X"b8" "JO
C{                // Get a list of strings as input, and loop through the list
  16D             // Convert from base 16 to base 10
     " X"b        // Convert from base 10 to base " X"
          8" "J   // Fill with " " up to 8 characters
               O  // Output

```

(`-el` flag is needed to prevent the last line being output twice)

# Answer
> 1 votes
# Ohm v2, 11 bytes

```
ôb€τ‥X r8Ü,

```

Try it online!

A neat little answer, in my opinion.

## Explained

```
ôb€τ‥X r8Ü,
ôb          # Convert each hex number to decimal then to binary
  €         # To each now-binary number:
   τ‥X r    #    Replace all 0s with spaces and 1s with Xs
        8Ü  #    Right-pad with spaces until the string is length 8
          , #    Print with a newline

```

# Answer
> 1 votes
# \>\<\>, 83 bytes

```
2:?!^i:0(?;" "\ao
-:07@@af+)?$~-\
:?!v:2%@2,:1%->
00.>~$~1-
oa4.>~}}}}rl?!v" X"{?$~

```

Try it online!

**Explanation**

1. Subtract 32 from input. If the result is larger than 25, subtract 7.
This gives us the decimal value of the input+16.
2. Repeat mod by 2, divide by 2 / mod by 1 to get the binary digits.
Drop the first digit of the binary value.
Since we added 16 to input this gives us the leading zeroes.
3. Do steps 1 and 2 one more time for the 2nd hex digit.
4. Reorder values, replace with "X" or " " and print each.
5. When done, print a newline and go back to 1.

# Answer
> 1 votes
# Raku, 67 bytes (62 characters)

```
' X'.comb[words».parse-base(16)».fmt('%08b')».comb]».join».say

```

Expects one picture per line, hex values space-separated on each line. Written to operate on standard input; change `words` to `.words` to operate on the topic instead at the cost of another byte.

Try it online!

# Answer
> 1 votes
# Stax, ~~11~~ 8 bytes

```
╨÷◘Jè∞╩:

```

Run and debug it

Unpacks to:

# Stax, 10 bytes

```
m|H. X:B8)

```

Run and debug it

```
m          # map the following over the input array:
 |H        # convert from hex to decimal
      :B   # and then to base
   . X     # " X"
        8) # and pad to length 8

```

# Answer
> 1 votes
# Scala, 140 bytes

Golfed vesrion. Attempt this online!

```
def f(a:String):String=String.format("%08d",Integer.parseInt(Integer.toBinaryString(Integer.parseInt(a,16)))).map(c=>if(c=='0')' ' else 'X')

```

Ungolfed version. Attempt this online!

```
import scala.io.StdIn.readLine
import scala.jdk.CollectionConverters._

object Main {
  def f(input: String): String = {
    val decimal = Integer.parseInt(input, 16)
    val binary =
      String.format("%08d", Integer.parseInt(Integer.toBinaryString(decimal)))
    val translated = binary.map(c => if (c == '0') ' ' else 'X')
    return translated;
  }
  def main(args: Array[String]): Unit = {
    Array("FF", "00", "81", "47", "99").map(f).foreach(println);
  }
}

```

# Answer
> 0 votes
# Thunno 2 `N`, 8 bytes

```
H` XBð8ṙ

```

Try it online!

#### Explanation

```
H` XBð8ṙ  # Implicit input
H         # From hexadecimal
 ` XB     # To base " X"
     ð8ṙ  # Pad to length 8
          # Implicit output

```

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


title: Alphabet Position Finder

text:
# Question
Title: Alphabet Position Finder
*Inspired by the Codewars Kata.*

Your goal is to take an input string such as this one:

```
"'Twas a dark and stormy night..."

```

and return a string containing the position of each character in the alphabet, separated by spaces and ignoring non-alphabetical characters, like this:

```
"20 23 1 19 1 4 1 18 11 1 14 4 19 20 15 18 13 25 14 9 7 8 20"

```

For an additional challenge, you can replace any numerical characters in the original string with themselves + 27. For example, `"25"` would become `"29, 32"`. This is completely optional.

You must use 1-indexing (`'a'==1`, `'b'==2`, etc)

Additional rules:

* You must return a string, not an array.
* Trailing whitespace is OK.

The winner has the lowest byte count.

Good luck!

# Answer
# 05AB1E, (5?) 7 bytes

Rightmost two bytes are output formatting

```
áÇ32%ðý

```

A port of my Jelly answer, but O5AB1E is more terse for the alphabet filtering.

**Try it online!**

### How?

```
áÇ32%ðý - take input implicitly
á       - filter keep alphabetical characters
 Ç      - to ordinals
  32    - thirty-two
    %   - modulo (vectorises)
     ð  - push a space character
      ý - join

```
> 5 votes

# Answer
# Java 8, ~~82~~ ~~78~~ ~~72~~ ~~69~~ 62 bytes

```
s->{for(int c:s)System.out.print(c>64&~-c%32<26?c%32+" ":"");}

```

-13 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
s->                    // Method with character-array parameter and no return-type
  for(int c:s)         //  Loop over its characters as integers
    System.out.print(  //   Print:
     c>64&~-c%32<26?   //    If the current character is a letter:
      c%32+" "         //     Print the position in the alphabet with a trailing space
     :                 //    Else:
      "");}            //     Print nothing

```
> 5 votes

# Answer
# , ~~55~~ 50 bytes

```
cat(utf8ToInt(gsub("[^A-Za-z]","",scan(,"")))%%32)

```

Try it online!

Reads input from stdin, ~~converts to uppercase,~~ removes non-~~uppercase~~ alphabetic letters, converts to code points, ~~subtracts to 64~~ mods by 32, and prints to stdout, separated by spaces.

*Thanks to Kevin Cruijssen for the golf!*
> 4 votes

# Answer
# Python 3, ~~62~~ ~~60~~ 49 bytes

-5 bytes thanks to Jo King.
-8 bytes thanks to pLOPeGG.

After these improvements, this answer is now similar to Jonathan Allan's answer.

```
print(*[ord(c)%32for c in input()if c.isalpha()])

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog Unicode), 24, 20, 14 13 bytes

-4 bytes thanks to Zacharý (and Mr. Xcoder)!

-6 bytes thanks to Adám!

-1 byte thanks to ngn!

```
⎕A⍳⎕A∩⍨≡819⌶⊢

```

Try it online!

## Explanation:

```
        ≡819⌶⊢  - to uppercase
   ⎕A∩⍨         - intersect with the letters A-Z (args swapped to preserve the order)
   ⍳              - index in
⎕A               - the A-Z letters list

```

## My initial solution:

# APL (Dyalog Unicode), 24 20 bytes

```
{⍵/⍨27>⍵}⎕A⍳1(819⌶)⊢

```

Try it online!

## Explanation:

```
             ⍳           indices of
              1(819⌶)⊢  the right argument (⊢) changed to uppercase
          ⎕A            in the list of uppercase letters
{⍵/⍨     }              copy (filter) those items from the list of indeces
     27>⍵               which are smaller than 27 (all non A-Z chars will have index 27)

```

Don't laugh at me, I'm new to APL :)
> 4 votes

# Answer
# JavaScript (Node.js), ~~69~~ ~~55~~ 54 bytes

```
t=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join` `

```

Try it online!

# Explanation :

```
t =>                       // lambda function accepting a string as input
    t.match(/a-z/gi).      // returns all parts of string that match as an array
        map(i=>            // map over that array with argument i
            parseInt(i,36) // convert to base 36
                - 9        // and subtract 9 from it
        ).                 // end map
        join` `            // convert to space separated string

```

---

11 bytes saved thanks to @Kevin

1 more bytes thanks to @Neil

---

You can add support for numericals for some additional bytes (thanks to @neil)

# JavaScript (Node.js), 62 bytes

```
t=>t.match(/[^_\W]/g).map(i=>(parseInt(i,36)+26)%36+1).join` `

```

Try it online!
> 3 votes

# Answer
# Python 2, (45?) 55 bytes

11 bytes added to format the output, which also makes this incompatible with Python 3)

```
lambda s:' '.join(`ord(c)%32`for c in s if c.isalpha())

```

Another port of my Jelly answer.

**Try it online!**

---

Non-formatted version (returning a list of integers):

```
lambda s:[ord(c)%32for c in s if c.isalpha()]

```
> 3 votes

# Answer
# Japt v2.0a0 `-S`, ~~12~~ 10 bytes

```
r\L ¬®c uH

```

Try it

---

## Explanation

```
r              :Remove
 \L            :  Non-letter characters
    ¬          :Split to array
     ®         :Map
      c        :  Character code
        u      :  Modulo
         H     :  32
               :Implicitly join with spaces and output

```
> 2 votes

# Answer
# Jelly, (7?) 8 bytes

Rightmost byte is output formatting

```
fØẠO%32K

```

A full program accepting a string in Python format which prints the result to STDOUT

**Try it online!**

### How?

```
fØẠO%32K - Main Link: list of characters (created from the string input)
 ØẠ      - yield the alphabet = ['A','B',...,'Z','a','b',...,'z']
f        - filter keep (discard non alphabet characters)
   O     - ordinals          ('A':65, 'Z':90, 'a':97, 'z':122, etc.)
     32  - literal thirty-two
    %    - modulo            (65:1,   90':26,  97:1,  122:26,  etc.)
       K - join with spaces (makes a list of characters and integers)
         - implicit print

```
> 2 votes

# Answer
# Whitespace, ~~152~~ 117 bytes

-35 bytes thanks to *@Lynn*.

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate_input][S S S T S S S S S N
_Push_32][T S T T   _Modulo][S N
T   _Swap_top_two][S S S T  T   T   T   T   T   N
_Push_63][T S T S _Integer_divide][T    S S N
_Multiply][S N
S _Duplicate][S S S T   T   S T T   N
_Push_27][S T   S S T   N
_Copy_1st][S S S T  N
_Push_1][T  S S S _Add][T   S T S _Integer_divide][T    S S N
_Mulitply][N
T   S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_number][S S S T   S S S S S N
_Push_32_space][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

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

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

**Explanation in pseudo-code:**

```
Start LOOP:
  Character c = STDIN as character
  Integer n = (c modulo-32) * (c integer-divided by 63)
  Integer m = 27 integer-divided by (n + 1) * n;
  If(m == 0):
    Go to next iteration of LOOP
  Else:
    Print n as integer to STDOUT
    Print a space to STDOUT
    Go to next iteration of LOOP

```
> 2 votes

# Answer
# Stax, ~~9~~ ~~10~~ 9 bytes

```
üpÉÿ%}},√

```

Run and debug it

*-1 byte thanks to @recursive*

Explanation:

```
v{VaIvm0-J Full program, unpacked, implicit input
v          Lowercase
 {    m    Map:
  VaI        Index in lowercase alphabet (0-based, -1 for not found)
     ^       Increment
       0-  Remove zeroes
         J Join by space
           Implicit output

```

### Stax, 7 bytes

```
É▌Xl»↔"

```

Run and debug it

This one outputs newline-separated. Unpacked: `vmVaI^|c`. Similar, but with map, which implicitly outputs with trailing newline.
> 2 votes

# Answer
# x86 opcode, 35 bytes

```
0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 D4
0090h: 0A 0D 30 30 86 E0 3C 30 74 01 AA 86 E0 AA B0 20
00a0h: AA EB DD

f:  lodsb
    cmp al, '$'
    jnz @f
        mov [di-1], al
        ret
    @@:
    or al, 32
    sub al, 96
    jbe f
    aam
    or ax, 3030H
    xchg ah, al
    cmp al, 48
    jz @f
        stosb
    @@:
    xchg ah, al
    stosb
    mov al, 32
    stosb
    jmp f

```

Assuming the result contain at least one letter, and no `{|}~`

40 bytes, allowing all ASCII chars

```
0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 3C
0090h: 1A 77 ED D4 0A 0D 30 30 86 E0 3C 30 74 01 AA 86
00a0h: E0 AA B0 20 AA EB D9

```
> 2 votes

# Answer
# 05AB1E, 14 bytes

Handles numbers as well

```
žKÃlvžKlÙyk>ðJ

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 8 bytes

```
láÇ96-ðý

```

Try it online!

or, if we can return an array:

# 05AB1E, 6 bytes

```
láÇ96-

```

Explanation:

```
l         Lowercase
 á        Only letters
  Ç       Codepoints
   96-    Subtract 96.

```

Try it online!

or if you want it to count numbers:

# 05AB1E, 13 bytes

```
lAžh«DŠÃSk>ðý

```

Try it online!
> 1 votes

# Answer
# Charcoal, 21 bytes

```
≔⁺β⭆χιβＦ↧Ｓ¿№βι«Ｉ⊕⌕βι→

```

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

```
≔⁺β⭆χιβ

```

Append the digits to the predefined lowercase letters variable.

```
Ｆ↧Ｓ

```

Loop over the lowercased input.

```
¿№βι«

```

If the current character is a letter or digit,

```
Ｉ⊕⌕βι

```

print its 1-indexed index,

and leave a space for the next value.
> 1 votes

# Answer
# PHP, 70 bytes

```
for(;$c=$argv[1][$i++];)if(($c=ord($c))>64&($c%=32)>0&$c<27)echo"$c ";

```

Try it online!

-5 bytes thanks to Kevin
> 1 votes

# Answer
# Red, 93 bytes

```
func[s][a: charset[#"a"-#"z"]parse lowercase s[any[copy c a(prin[-96 + to-char c""])| skip]]]

```

Try it online!
> 1 votes

# Answer
# Perl 5, 47 bytes

With additional challenge of parsing digits:

```
print map{(ord(uc)-64)%43," "}<>=~/([A-Z\d])/gi

```

Try it online!

Reduced to 38 bytes by ignoring digits

```
print map{ord()%32," "}<>=~/([A-Z])/gi

```
> 1 votes

# Answer
# Japt 2.0 `-S`, 9 bytes

```
f\l ®c %H

```

Run it online

## Explanation:

```
f\l ®c %H                                    Input: "Hello..."
f            Match:
 \l             [A-Za-z]                     ["H","e","l","l","o"]
    ®        Map Z over the results:
     c         char-code of Z                [72,101,108,108,111]
       %H      mod 32                        [8,5,12,12,15]
-S           Join the chars with a space     8 5 12 12 15

```
> 1 votes

# Answer
# Perl 5 `-p`, 35 bytes

```
$_="@{[map{(-64+ord uc)%43}/\w/g]}"

```

Try it online!

Includes the extra portion about the digits.
> 1 votes

# Answer
## PHP 108 105 Bytes

Try it online (108 Bytes)

Tri it online (105 Bytes)

-3 Bytes, thanks to @manassehkatz (Change the level of strtolower and remove A-Z from regex)

**Code, tried to avoid any loop**

```
<?=strtr(implode(" ",str_split(preg_replace(
"/[^a-z]/",'',strtolower($argv)))),array_flip(range("`",z)));

```

**Explanation**

```
$string = preg_replace("/[^a-z]/",'',strtolower($argv))
//the string only contains letters

$string = implode(" ",str_split($string));
//the string has a space after every letter

$string = strtr($string, array_flip(range("`",z)));
//replace every letter   acording to the array

$replacementArray = array_flip(range("`",z));
//this array contains the ansi characters from "`" to the "z"
//array_flip to change the keys with the values
//final array ["`"=>0,"a"=>1, "b"=>2...."z"=>26]

```
> 1 votes

# Answer
# Perl 6, 32 bytes (alpha), 41 bytes (alpha+digit)

```
{~(.uc.comb(/<:L>/)».ord X-64)}

```

Try it (32 bytes alpha)

```
{~((.uc.comb(/<:L+:N>/)».ord X-64)X%43)}

```

Try it (41 bytes alpha + digit)

## Expanded:

### 32 bytes alpha

```
{  # bare block lambda with implicit parameter $_

  ~( # coerce to string (space separated)

      .uc                      # uppercase
      .comb( / <:L > / )\      # get letters as a sequence
      ».ord                    # get the ordinal of each
      X- 64                    # subtract 64 from each
  )
}

```

### 41 bytes alpha + digit

```
{  # bare block lambda with implicit parameter $_

  ~( # coerce to string (space separated)
    (
      .uc                      # uppercase
      .comb( / <:L + :N > / )\ # get letters and numbers as a sequence
      ».ord                    # get the ordinal of each
      X- 64                    # subtract 64 from each
    ) X% 43                    # modulus 43 for each
  )
}

```
> 1 votes

# Answer
# Tcl, 93 bytes

```
puts [lmap c [split $argv ""] {if [string is alp $c] {expr ([scan $c %c]-64)%32} {continue}}]

```

Try it online!
> 1 votes

# Answer
# Python 2, 110 bytes 104 bytes, with user input

```
a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(input().lower())if l in a)

```

Try it Online!

---

# Python 2, 105 bytes 104 bytes 96 bytes, where `t` is predefined:

```
a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(t.lower())if l in a)

```

Try it Online!

Let's break it down with a more readable version:

```
alphabet = "abcdefghijklmnopqrstuvwxyz"
foo = [str(alphabet.index(letter) + 1) for letter in list(t.lower()) if letter in alphabet]
print " ".join(foo)

```

First, we define `alphabet` as being, well, the alphabet.

Next, we use list comprehension to:

1. Make a list where each item is a lowercase character from `t`
2. For each letter, if it is not in the alphabet, discard it.
3. If it is, find its index in the alphabet,
4. add one to it (because we start counting at 1)
5. and make it a string.

Finally, we join it all together and print it.

---

**Edit:** Changed to `print` (and lost portability) to save bytes and make it work outside a function

**Edit 2:** Added a version with `input()` instead of predefined variables

**Edit 3:** Removed 8 bytes in Solutions 1 and 2 thanks to Jo King
> 0 votes

# Answer
# Python 3, 84 bytes

```
print(*filter(int,['abcdefghijklmnopqrstuvwxyz'.find(c)+1for c in input().lower()]))

```

Try it online!
> 0 votes

# Answer
# PowerShell, 63 bytes

```
"$(([char[]]"$args".ToUpper()|%{$_-($_,64)[$_-in65..90]})-ne0)"

```

Try it online!

*(Seems long ...)*

Takes input `$args`, converts it `.ToUpper`case, casts it as a `char`-array, feeds that into a `for each` loop. Inside the loop, we subtract either itself or 64 from the (ASCII int) value, based on whether or not the current value is `-in` the range `65` to `90` (i.e., it's an ASCII capital letter). Those values are left on the pipeline, and we use a `-n`ot`e`qual to eliminate the non-letter values (because they're all zero). Those numbers are encapsulated in a string as the default stringification of an array is to space-separate it, so we get that pretty cheaply. That string is left on the pipeline and output is implicit.
> 0 votes

# Answer
# MS-SQL, 133 bytes

```
SELECT STRING_AGG(ASCII(substring(upper(s),number+1,1))-64,' ')FROM
spt_values,t WHERE type='P'AND substring(s,number+1,1)LIKE'[a-z]'

```

Per our IO rules, input is taken via a pre-existing table **t** with varchar field **s**.

SQL 2017 or later is required. Must also be run in the `master` database, because I'm taking advantage of a system table called `spt_values`, which (when filtered by `type='P'`) contains counting numbers from 0 to 2047.

Basically I'm joining a number table with the input string using `SUBSTRING()`, which returns a separate row for each individual character. This is filtered for only letters using `LIKE'[a-z]'`, then we get their ASCII value and subtract 64. These numbers are joined back into a string using the (new to SQL 2017) function `STRING_AGG`.
> 0 votes

# Answer
# Pyth, 10 bytes

```
jdfTmhxGr0

```

I'm pretty sure this can be golfed a little bit... -2 bytes if I can output as a list, some answers seem to but it's not in the spec

Try it online!
> 0 votes

# Answer
# Ruby, 41 bytes

```
->s{s.scan(/\p{L}/).map{|i|i.ord%32}*' '}

```

Try it online!
> 0 votes

# Answer
# C (gcc), 67 bytes

```
c;f(char*s){for(;*s;)(c=tolower(*s++)-96)>0&c<27&&printf("%d ",c);}

```

Try it online!

Converts each char to lowercase, offsets its code by -96 and, if it falls in the range of the 1-indexed alphabet, prints the offset code
> 0 votes

# Answer
# jq, 45 bytes

```
[gsub("\\W";"")|explode[]%32|@text]|join(" ")

```

---

```
 gsub("\\W";"")                                # remove non-alpha characters
               |explode[]                      # get decimal values of characters
                         %32                   # get positions in alphabet
                            |@text             # convert back to string
[                                 ]|join(" ")  # join with a space

```

**Try it online**
> 0 votes

# Answer
# \[C (gcc)\], 57 56 bytes (printing), 70 69 bytes (printing w/optional), 146 bytes (string)

Thanks to ceilingcat for the `&&` optimization.

```
f(char*s){for(;*s;s++)isalpha(*s)&&printf("%d ",*s&31);}

```

Try it online!

This version takes alphanumeric text per the additional challenge:

```
f(char*s){for(;*s;s++)isalnum(*s)&&printf("%d ",(*s<65)*10+(*s&31));}

```

Try it online!

If returning a string is required for this challenge:

```
char*f(s,t,u,i)char*s,*t,*u;{for(i=strlen(s)*4,t=calloc(i,2),u=t+i;*s;s++)isalnum(*s)?sprintf(u,"%d ",(*s<65)*10+(*s&31)),strcat(t,u):0;return t;}

```

Try it online!
> 0 votes

# Answer
# CJam, ~~23~~ 15 bytes

```
qel_eu-{i32%S}/

```

Try it online!

Saved 8 bytes thanks to Esolanging Fruit
> 0 votes

# Answer
# PHP, 61 bytes

works in any PHP version from 4.0.4 to 7.2 (but might cease to work in 7.3)

```
while(~$c=$argn[$i++])ctype_alpha($c)&&print(ord($c)&31)." ";

```

Run as pipe with `-nr` or try it online.
> 0 votes

# Answer
## ABAP, 228 bytes, letters only

I wrote a FORM subroutine for an ABAP report. i is input, o is output.

```
FORM h USING i o.TRANSLATE i TO UPPER CASE.DO strlen( i ) TIMES.data c(2).c = sy-index - 1.FIND i+c(1) IN 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' RESULTS data(r).CHECK sy-subrc = 0.c = r-offset + 1.CONCATENATE o c ` ` INTO o.ENDDO.ENDFORM.

```

Verbose code:
Look at it on Pastebin.com for syntax highlighting. (Not that it looks much better)

```
"This stuff is used to actually run the program, call the form and output the results.
REPORT z.
PARAMETERS se_input TYPE string.
START-OF-SELECTION.
    DATA ret type string.
    PERFORM h USING se_input ret.
    WRITE ret.

"---- CODE STARTS HERE ----
FORM f USING i o.              "Two parameters: i for input, o for output.
    TRANSLATE i TO UPPER CASE. "All to uppercase
    DO strlen( i ) TIMES.      "Do for each character
        data c(2).             "A char field, length of 2
        c = sy-index - 1.      "Current loop index - 1 = index in string. Loop index starts at 1.
        FIND i+c(1)            "Find substring: input at position index, length 1...
         IN 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' RESULTS data(r). "...in the alphabet, save to "r"
        CHECK sy-subrc = 0.    "sy-subrc <> 0 => not in the alphabet, skips the rest of this loop (same as CONTINUE)
        c = r-offset + 1.      "r-offset is the index in the string, add one for alphabet position
        CONCATENATE o c ` ` INTO o. "Concatenate it all into the output chars, including the literal space.
                  "      ^- had I used ' ' here, CONCATENATE would remove blank space, but ` ` stays untouched.
    ENDDO. "Loop end
ENDFORM.   "FORM end

```

### Notes, thoughts, background stuff

First of all, no, I did not miss spaces in my code. ABAP wants them and will not run without them...

The USING parameters i and o are of unknown type, so the program calling the FORM must use a string (or char field with at least `length of input * 3`: 2 characters + space per letter) for o, otherwise results can be cut off or it all just dumps right away if it's a numeric value for example.

I saved a few bytes here by re-using the same character field over and over again, abusing the fact that ABAP implicitly converts numbers to chars and vice versa without any issues. This is especially better than using the `CONDENSE <var>` statement, which was initially necessary to not have my integers padded to 26 characters width.

Getting substrings in ABAP is super quick and easy once you get used to it:
`substring = string+offset(length).`
Thanks to the implicit conversion, `offset` can be even a character field. Nasty, but great for us in this case. But be careful: While `string+5` gives you the substring starting from index 5, `string + 5` will try to cast your string to a number and add 5. Spaces matter!

There's also an easy way to convert the character to a byte value, giving me the ASCII code and removing the need to do the lengthy `FIND IN ...` stuff, but on a *Unicode* SAP system there's no quick and dirty way to convert that byte value into a "readable" number that I know of, so it's kind of a red herring.

By the way: `TRANSLATE i TO UPPER CASE.` is exactly 26 bytes long, so at first glance it looks like we don't even need it and can just add the lowercase letters to the alphabet string instead. But you probably realized right away why we *can't* do that. ;-)

---

### Bonus:

## ABAP, 238 bytes, alphanumeric

For the alphanumeric version we just add 0123456789 to the alphabet string, hence increasing the length of the code by 10 bytes. Not very interesting, but any other approach would just be longer thanks to the very, uhm, *verbose* language that ABAP is.

```
FORM h USING i o.TRANSLATE i TO UPPER CASE.DO strlen( i ) TIMES.data c(2).c = sy-index - 1.FIND i+c(1) IN 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' RESULTS data(r).CHECK sy-subrc = 0.c = r-offset + 1.CONCATENATE o c ` ` INTO o.ENDDO.ENDFORM.

```

---

I hope my explanation is somewhat interesting. Thanks for the challenge!
> 0 votes

# Answer
# Haskell, 63 bytes

```
import Data.Char
unwords.map(show.(`mod`32).ord).filter isAlpha

```

Try it online!
> 0 votes

# Answer
# Ruby, 97 bytes

```
n=[];gets.chomp.gsub(/[^a-zA-Z]/,'').upcase.bytes.each{|i|n.push i-64};puts n.map(&:to_i).join" "

```

Try it online!
> 0 votes

# Answer
# Lua (5.3), 94 bytes

`x=...y=""for i=1,#x do z=x:sub(i,i)y=y..(z:find"%a"and(z:byte()&~32)-64 .." "or"")end print(y)`

Try it online!
> 0 votes

# Answer
# Thunno 2 , 2 bytes

```
ỊÄ

```

Try it online!

#### Explanation

```
    # Implicit input
Ị   # Keep only alphabetic characters
 Ä  # And get the 1-based indices in the alphabet
    # Implicit output, joined by spaces

```
> 0 votes

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


title: Duck, Duck, Josephus

text:
# Question
Title: Duck, Duck, Josephus
Given an Integer array:

1. Start from the first number
2. Jump forward n positions where n is the value of the current position
3. Delete the current position, making what was the next position the current position.
4. Goto step 2 until there is one number remaining
5. Print that number

**Rules**

The array wraps-around (the next number after the last number in the array is the first number).

A zero removes itself (Obviously).

Negative numbers are not allowed as input.

**Test Cases**

```
[1] => 1
[1,2] => 1
[1,2,3] => 3
[1,2,2] => 1
[1,2,3,4] => 1
[6,2,3,4] => 4
[1,2,3,4,5] => 5
[0,1] => 1
[0,0,2,0,0] => 0

```

---

**Step-by-step example**

```
[1,4,2,3,5]
 ^          start from the first position
   ^        jump 1 position (value of the position)
[1,  2,3,5] remove number in that position
     ^      take next position of the removed number (the 'new' 'current' position)
         ^  jump 2 positions
[1,  2,3  ] remove number in that position
 ^          take next position (looping on the end of the array)
     ^      jump 1 position
[1,    3  ] remove number in that position
       ^    take next position (looping)
 ^          jump 3 positions (looping on the end of the array)
[      3  ] remove number in that position
print 3

```

**Example #2**

```
[4,3,2,1,6,3]
 ^            start from the first position
         ^    jump 4 positions
[4,3,2,1,  3] remove number in that position
           ^  take next position
     ^        jump 3 positions
[4,3,  1,  3] remove number in that position
       ^      take next position
           ^  jump 1 positions
[4,3,  1    ] remove number in that position
 ^            take next position
   ^          jump 4 positions
[4,    1    ] remove number in that position
       ^      take next position
 ^            jump 1 position
[      1    ] remove number in that position
print 1

```

This is , the shortest answer in bytes wins!

# Answer
> 11 votes
# Husk, 7 bytes

This returns the result as a singleton list

```
ΩεSotṙ←

```

Try it online!

### Explanation

```
Ω               Until
 ε              the result is a singleton list
     ṙ          Rotate left by
  S   ←         the first element
   ot           Then remove the first element

```

# Answer
> 7 votes
# Haskell, ~~54~~ ~~50~~ 48 bytes

```
f[x]=x
f(x:r)=f$snd<$>zip r(drop(x+1)$cycle$x:r)

```

Try it online!

**Explanation:**

* `f[x]=x`: If the given list is a singleton list, return its element.
* `f(x:r)=f$ ...`: Otherwise recursively apply `f` to the following list:
    + The elements of the current list cycled infinitely (`cycle$x:r`),
    + with the first `x+1` elements removed (`drop(x+1)$`),
    + and truncated to length of `r`. (`snd<$>zip r` is a shorter alternative to `take(length r)`).

---

### Previous 54 byte version:

```
f=(%)=<<head
_%[x]=x
n%(x:r)|n<1=f r|s<-r++[x]=(n-1)%s

```

Try it online!

# Answer
> 7 votes
# Ruby, 37 bytes

```
->r{r.rotate!(r[0]).shift while r[1]}

```

Modifies the array in-place, which appears to be acceptable as output. Try it online!

# Answer
> 6 votes
# Python 3, ~~54~~ 51 bytes

```
f=lambda x:x and f((x+x*x[0])[x[0]:][1:len(x)])or x

```

Output is a singleton list.

Try it online!

# Answer
> 5 votes
# MATL, 21 bytes

```
1`yy)+ynX\[]w(5Mynq]x

```

Try it online! Or verify all test cases.

### Explanation

```
1        % Push 1: current position in the array
`        % Do...while
  yy     %   Duplicate top two elements in the stack. Takes input implicitly
         %   in the first iteration.
         %   STACK: array, position, array, position
  )      %   Get specified entry in the array
         %   STACK: array, position, selected entry
  +      %   Add
         %   STACK: array, position (updated)
  y      %   Duplicate from below
         %   STACK: array, position, array
  n      %   Number of elements of array
         %   STACK: array, position, number of elements or array
  X\     %   1-based modulus
         %   STACK: array, position (wrapped around)
  []     %   Push empty array
         %   STACK: array, position, []
  w      %   Swap
         %   STACK: array, [], position
  (      %   Write value into specified entry in array. Writing [] removes
         %   the entry
         %   STACK: array (with one entry removed)
  5M     %   Push latest used position. Because of the removal, this now
         %   points to the entry that was after the removed one
         %   STACK: array, position
  y      %   Duplicate from below
         %   STACK: array, position, array
  n      %   Number of elements of array
         %   STACK: array, position, number of elements of array
  q      %   Subtract 1
         %   STACK: array, position, number of elements of array minus 1
]        % End. If top of the stack is nonzero, proceed with next iteration
         % STACK: array (containing 1 entry), position
x        % Delete. Implicitly display
         % STACK: array (containing 1 entry)

```

# Answer
> 5 votes
## CJam, 15 bytes

```
l~_,({_0=m<1>}*

```

Try it online!

### Explanation

Instead of keeping track of a pointer, I just shift the array cyclically so that the current element is always at the front.

```
l~     e# Read and evaluate input.
_,(    e# Get its length L and decrement to L-1.
{      e# Run this block L-1 times...
  _0=  e#   Get the first element X.
  m<   e#   Rotate the array left by X positions.
  1>   e#   Discard the first element.
}*
       e# The final element remains on the stack and gets printed implicitly.

```

A fun alternative which unfortunately doesn't save any bytes:

```
l~_{;m<1>_0=}*;

```

# Answer
> 5 votes
# Jelly, 9 bytes

```
ṙḷ/ḊµL’$¡

```

Try it online!

-2 bytes thanks to user202729

# Explanation

```
ṙḷ/ḊµL’$¡  Main Link
     L’$¡  Repeat <length - 1> times
ṙ          Rotate left by
 ḷ/        The first element (from JHT; thanks to user202729)
   Ḋ       Take all but the first element

```

# Answer
> 5 votes
# Python 2, 55 bytes

```
def f(a):
 while a[1:]:l=a[0]%len(a);a[:]=a[-~l:]+a[:l]

```

Try it online!

Outputs as a singleton list, as allowed by default. Saved a few bytes thanks to Dennis, by reminding me that modifying the function argument is allowed.

### How it works

* `def f(a)` \- Defines a function with a parameter `a`.
* `while a[1:]:` \- While `a` with the first element removed is truthy, run the block of code to follow. A list with one element or more is truthy, and empty lists are falsy in Python, hence this will stop once `a` reaches a length of 1.
* `l=a[0]%len(a)` \- Take the first element, and get the remainder of its division by the length of `a`. Assign the result to `l`.
* `a[:]=a[-~l:]+a[:l]` \- Rotate `a` to the left by `l` elements, and remove the first one, while assigning this to `a` in place.

---

**Python 2, 63 bytes**

```
f=lambda a,i=0:a[1:]and f(a,a.pop(((a*-~i)[i]+i)%len(a))+1)or a

```

Try it online!

Although longer, this seems much more elegant. Also thanks to ovs for helping in chat.

# Answer
> 5 votes
# Jelly, 7 bytes

```
ṙḷ/ḊµḊ¿

```

Try it online!

Full program.

# Answer
> 5 votes
# Brain-Flak, 88 bytes

```
([[]]()){({}<(({})){({}<({}<([]){({}{}<>)<>([])}{}>)<>{({}[<>[]])<>}<>>[()])}{}{}>())}{}

```

Try it online!

### Explanation

```
([[]]())                      Push negative N: the stack height - 1
{({}< … >())}{}               Do N times
     (({}))                     Duplicate M: the top of the stack
     {({}< … >[()])}{}          Do M times
                                  Rotate the stack by 1:
          ({}< … >)               Pop the top of the stack and put it back down after
          ([]){({}{}<>)<>([])}{}  Pushing the rest of the stack on to the other one, in reverse, with the stack height added to each element (to ensure that all are positive)
          <>{({}[<>[]])<>}<>      Push the rest of the stack back, unreversing, and subtracting the stack height from each element
                      {}        Pop the top of stack

```

# Answer
> 3 votes
# Python 3, 60 bytes

```
def f(a):b=a[0]%len(a);return f(a[-~b:]+a[:b])if a[1:]else a

```

Try it online!

-3 bytes thanks to ovs

# Answer
> 3 votes
# JavaScript (ES6), ~~54~~ 60 bytes

*Saved 1 byte thanks to @Shaggy*
*Fixed version (+6 bytes)*

Modifies the input array, which is reduced to a singleton.

```
f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1))

```

### Test cases

```
f=(a,p=0)=>1/a||f(a,p=(p+a[p%(l=a.length)])%l,a.splice(p,1))

;[
  [1],         // [1]
  [1,2],       // [1]
  [1,2,3],     // [3]
  [1,2,2],     // [1]
  [1,2,3,4],   // [1]
  [6,2,3,4],   // [4]
  [1,2,3,4,5], // [5]
  [0,1],       // [1]
  [0,0,2,0,0], // [0]
  [3,5,7,9]    // [5]
].forEach(a => f(a) && console.log(JSON.stringify(a)))
```

### How?

We recursively apply the algorithm described in the challenge. Only the stop condition `1/a` may seem a bit weird. When applying an arithmetic operator:

* Arrays of more than one element are coerced to `NaN` and `1/NaN` is also `NaN` (falsy).
* Arrays of exactly one integer are coerced to that integer, leading to either `1/0 = +Infinity` or `1/N = positive float` for **N \> 0** (both truthy).

```
f = (a, p = 0) =>                 // a = input array, p = pointer into this array
  1 / a ||                        // if a is not yet a singleton:
    f(                            //   do a recursive call with:
      a,                          //     a
      p = (                       //     the updated pointer
        p + a[p % (l = a.length)] //
      ) % l,                      //
      a.splice(p, 1)              //     the element at the new position removed
    )                             //   end of recursive call

```

# Answer
> 3 votes
# APL (Dyalog), ~~20~~ 18 bytes

```
{1<≢⍵:∇1↓⊖∘⍵⊃⍵⋄⊃⍵}

```

Try it online!

# Answer
> 3 votes
# Java 8, 79 bytes

This lambda accepts a `Stack<Integer>` and returns an `int` or `Integer`.

```
l->{for(int i=0,s=l.size();s>1;)l.remove(i=(i+l.get(i%s))%s--);return l.pop();}

```

Try It Online

## Ungolfed

```
l -> {
    for (
        int i = 0, s = l.size()
        ; s > 1
        ;
    )
        l.remove(
            i = (i + l.get(i % s)) % s--
        );
    return l.pop();
}

```

## Acknowledgments

* -2 bytes thanks to Nahuel Fouilleul

# Answer
> 3 votes
# , 21 17 bytes

-4 bytes thanks to FrownyFrog

```
((1<#)}.{.|.])^:_

```

Try it online!

Original:

`([:}.{.|.])^:(1<#)^:_`

# How it works:

`^:_` repeat until the result stops changing

`^:(1<#)` if the length of the list is greater than 1

`{.|.]` rotate the list to the left its first item times

`[:}.` drop the first element and cap the fork

Try it online!

# Answer
> 3 votes
# Julia 0.6, 46 42 bytes

```
!x=length(x)>1?!circshift(x,-x[])[2:end]:x

```

Try it online!

Straightforward recursive Julia version. `x[]` accesses the first element of x.

# Answer
> 2 votes
# Mathematica, 36 bytes

uses Martin's algorithm

```
#//.l:{x_,__}:>Rest@RotateLeft[l,x]&

```

-5 bytes from Misha Lavrov && Martin Ender

Try it online!

# Answer
> 2 votes
# Pyth, 9 bytes

```
.WtHt.<Zh

```

**Try it here!**

This outputs the result as a singleton list, as allowed by default.

### How it works

```
.WtHt.<Zh ~ Full program.

.W        ~ Functional while. It takes three arguments, two functions: A and B
            and a starting value, which in this case is automatically assigned
            to the input. While A(value) is truthy, value is set to B(value).
            Returns the ending value. A's argument is H and B's is Z.
  tH      ~ A (argument H): Remove the first element of H. A singleton list
            turns into [], which is falsy and thus breaks the loop. Otherwise,
            it is truthy and the loops goes on until the list reaches length 1.
     .<Zh ~ B (argument Z): Cyclically rotate Z by Z[0] places, whereas Z[0]
            represents the first element of Z.
    t     ~ And remove the first element.

```

**Note:** If you don't want to see those brackets, just add `h` or `e` in front of the whole code.

# Answer
> 2 votes
# Brain-Flak, 104 bytes

*H.PWiz has a shorter answer here that I helped to make, you should check it out.*

```
([[]]()){({}()<(({})){({}[()]<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}{}>)}{}

```

Try it online!

## Explanation

```
([[]]())   #Push 1 minus stackheight
{({}()<    #N times
 (({}))    #Get a copy of the top
 {({}[()]< #N times
  ({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>
           #Roll the top to the bottom (From the wiki)
 >)}{}     #End loop
 {}        #Remove one value
>)}{}      #End loop

```

# Answer
> 2 votes
# Swift, 87 bytes

```
func f(a:inout[Int]){var i=0,c=0;while(c=a.count,c>1).1{i=(i+a[i%c])%c;a.remove(at:i)}}

```

Returns as a singleton list by modifying the input. Try it online!

## Explanation

```
func f(a:inout[Int]){
  var i=0,c=0;            // Set the index i to 0
  while(c=a.count,c>1).1{ // While the length of the list > 0:
    i=(i+a[i%c])%c;       //  Add a[i] to i and loop back using modulo
    a.remove(at:i)        //  Remove a[i]
  }
}

```

# Answer
> 2 votes
# Perl 6, ~~46~~ 45 bytes

(-1 byte thanks to Brad Gilbert)

```
{($_,{(|$_ xx*)[.[0]+(1..^$_)]}...1)[*-1][0]}

```

Try it online!

`($_, { ... } ... 1)` generates a sequence of lists, starting with the input list `$_`, each successive element being generated by the brace expression, and terminating when the list smart-matches `1`--ie, has a length of 1. The trailing `[* - 1]` obtains the final element, and the final `[0]` takes the sole element out of that singleton list.

`(|$_ xx *)` generates a flat, infinitely replicated copy of the current element. This list is indexed with the range `.[0] + (1 ..^ $_)` to extract the next finite list in the series.

# Answer
> 1 votes
# Perl 5, ~~47~~ ~~43~~ 41 + 2 (`-ap`) = 43 bytes

```
$\=splice@F,($_+=$F[$_%@F])%@F,1while@F}{

```

Try it online!

Takes input as space separated numbers.

# Answer
> 1 votes
# Haskell, 56 bytes

```
f[x]=x
f l|m<-head l`mod`length l=f$drop(m+1)l++take m l

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~57~~ 56 bytes

```
f=lambda a,*b:f(*([a,*b]*-~a)[a+1:a-~len(b)])if b else a

```

Try it online!

# Answer
> 1 votes
# Java 8, 325 Bytes

Golfed:

```
static void n(Integer[]j){Integer[]h;int a=0;h=j;for(int i=0;i<j.length-1;i++){if(h.length==a){a=0;}a=(a+h[a])%h.length;h[a]=null;h=m(h);}System.out.print(h[0]);}static Integer[] m(Integer[]array){Integer[]x=new Integer[array.length-1];int z=0;for(int i=0;i<array.length;i++){if(array[i]!=null){x[z]=array[i];z++;}}return x;}

```

Ungolfed:

```
 interface ArrayLeapFrog {
static void main(String[] z) throws Exception {
    Integer[] j = {6, 2, 3, 4};
    n(j);
}

static void n(Integer[] j) {
    Integer[] h;
    int a = 0;
    h = j;
    for (int i = 0; i < j.length - 1; i++) {
        if (h.length == a) {
            a = 0;
        }
        a = (a + h[a]) % h.length;
        h[a] = null;
        h = m(h);
    }
    System.out.print(h[0]);
}

static Integer[] m(Integer[] array) {
    Integer[] x = new Integer[array.length - 1];
    int z = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] != null) {
            x[z] = array[i];
            z++;
        }
    }
    return x;
  }
}

```

# Answer
> 1 votes
# APL+WIN, 36 bytes

```
¯1↑⍎¨(1⌈¯1+⍴v←,⎕)⍴⊂'v←(1<⍴v)↓v[1]⌽v'

```

Explanation:

Prompts for screen input.

```
'v←(1<⍴v)↓v[1]⌽v' Loop logic as a string

 (1<⍴v)↓ only drop the first when number of elements n>1

 (1⌈¯1+⍴v←,⎕)⍴⊂ create a nested vector of logic of length 1 max n-1

 ⍎¨ execute each element of the nested vector in turn

¯1↑ take answer from executing final element

```

# Answer
> 1 votes
# JavaScript, ~~58~~ ~~56~~ 59 bytes

```
let f =

a=>{for(i=0,k=a.length;k>1;)i+=a[i%=k],a.splice(i%=k--,1)}
```

```
<h2>Test</h2>
Enter or paste a valid array literal within square brackets and click Run.
<blockquote>
   <input id = "array" type="text" length="20">
   <button type="button" onclick="run()">Run</button>
</blockquote>
Result: <pre id="o"></pre>

<script>
    function run() {
       let a = JSON.parse(array.value);
       f(a);
       o.textContent = a;
    }
</script>
```

Returns the result as the only element remaining in the input array which is updated in place.

Two bytes saved by using a comma separated statement instead of a block statement in the for loop body! Three bytes lost to skip from an element deleted at end of array (:

**Less golfed:**

```
a => {
    for(i=0,k=a.length;k>1;) // once less than array length
        i+=a[i%=k],          // the new index
        a.splice(            // delete an element
           i%=k--,           // ensuring index is within array,
                             // and post decrement loop count
           1
        )
}

```

# Answer
> 1 votes
# Python 2, 61 bytes

```
def f(x):
 while x[1:]:y=x[0]%len(x);x=x[y+1:]+x[:y]
 print x

```

# Answer
> 1 votes
# Clean, 78 bytes

Uses the same method as Laikoni's Haskell answer.

```
import StdEnv
f[e]=e
f[x:r]=f(take(length r)(drop(x+1)(flatten(repeat[x:r]))))

```

Try it online!

# Answer
> 1 votes
# , 111 ~~117~~ ~~126~~ bytes

Thanks to @Giuseppe for golfing off 11 bytes by changing to a while loop, got another 4 by removing the function and reading user input directly.

I don't feel great about what it took to get there - I'm sure a more elegant solution exists.

```
i=scan();m=1;while((l=sum(i|1))-1){j=i[m];p=`if`(j+m>l,j%%l+!m-1,j+m);p=`if`(!p,m,p);i=i[-p];m=`if`(p-l,p,1)};i

```

Try it online!

Ungolfed code

```
i=scan()
m=1
while((l=sum(i|1))-1){
  j=i[m]
  p=`if`(j+m>l,j%%l+!m-1,j+m)
  p=`if`(!p,m,p)
  i=i[-p]
  m=`if`(p-l,p,1)
}
i

```

# Answer
> 0 votes
# Perl, 62 bytes

```
@_=@ARGV;while(@_>1){splice(@_,$i=($i+$_[$i])%@_,1)}print$_[0]

```

Requires that the numbers are added at command line. Default `$i` equivalent to 0.

```
@_=@ARGV;                         # gets the array passed on command line
while(@_>1)                       # if there is more than one element in array, loop
{
   splice(@_,$i=($i+$_[$i])%@_,1) # embedded assignment to $i, removes element.
}
print$_[0]                        # prints remaining element

```

# Answer
> 0 votes
# Perl 5, 43 + 2 (`-ap`) = 45 bytes

```
$_="@F[$`%@F+1..$#F,0..$`%@F-1]",redo if/ /

```

try it online

# Answer
> 0 votes
# Pushy, 11 bytes

```
@Lt:&:};.;#

```

**Try it online!**

This challenge is well suited to be run on a stack:

```
             \ Implicit: Input on stack
@            \ Reverse the stack
 Lt:     ;   \ len(stack)-1 times do:
    &: ;     \    (last item) times do:
      }      \      Cyclically shift the stack right
        .    \    Pop top of stack
          #  \ Print remaining value

```

# Answer
> 0 votes
# Python 2, 57 bytes

A couple bytes longer than Mr Xcoder's solution, but I thought it was worth posting this alternate approach.

```
def f(a,p=0):
 while a[1:]:p=(p+(a+a)[p])%len(a);del a[p]

```

**Try it online!**

Initially I did this recursively, but it's a few bytes longer:

```
def f(a,p=0):
 if a[1:]:p=(p+(a+a)[p])%len(a);del a[p];f(a,p)

```

**Try it online!**

# Answer
> 0 votes
# Common Lisp, 129 bytes

```
(do*((m(coerce(read)'list))(k(rplacd(last m)m)))((eq(cdr m)m)(princ(car m)))(setf k(nthcdr(1-(car m))m)m(cdr(rplacd k(cddr k)))))

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 23 + 3 = 26 bytes

```
{:l3(?\:?\~~
 1-&{&\n;\

```

Try It Online

Takes a series of integers via the -v option.

### How It Works

```
{:l3(?\   Get the first element of the stack and dupe it
 .....\n; If the length of the stack is only 2 (the first element twice), then print the number and end the program, else enter the loop

 .....\:?\.. Enter the loop with the array and a copy of the first value.
 1-&{&\..\   Exit the loop if the copy is 0, else shift the stack right and decrement the copy.

{:l3(?\..\~~ Pop the excess 0 and the current element of the array
 ...         Go back to the beginning, having one less element than before

```

# Answer
> 0 votes
# Perl, 36 bytes

Includes `+2` for `ap`

```
perl -apE '--($m||=$_+1)?$F[@F]:$\=$_ for@F}{' <<< "1 4 2 3 5"; echo

```

Nicely evil...

# Answer
> 0 votes
# Thunno 2, 7 bytes

```
(ḣ;DhỴḣ

```

Try it online!

#### Explanation

```
(ḣ;DhỴḣ  # implicit input
(        # while loop
 ḣ       # (condition)  length > 1
  ;D     # (body)  duplicate current list
    hỴ   #         rotate left by first item
      ḣ  #         then remove first item
         # implicit output

```

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


title: Ken Iverson’s Favourite APL Expression?

text:
# Question
Title: Ken Iverson’s Favourite APL Expression?
| Ken Iverson, 1920–2020 |
| --- |
|  |

Let's implement his favourite expression:

### Given a row of Pascal's triangle, compute the next row.

This can for example be computed by taking the input padded with a zero on the left, and the input padded with a zero on the right, and then adding the two element-by-element.

### Test cases

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

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

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

`[1,10,45,120,210,252,210,120,45,10,1]``[1,11,55,165,330,462,462,330,165,55,11,1]`

`[1,50,1225,19600,230300,2118760,15890700,99884400,536878650,2505433700,10272278170,37353738800,121399651100,354860518600,937845656300,2250829575120,4923689695575,9847379391150,18053528883775,30405943383200,47129212243960,67327446062800,88749815264600,108043253365600,121548660036300,126410606437752,121548660036300,108043253365600,88749815264600,67327446062800,47129212243960,30405943383200,18053528883775,9847379391150,4923689695575,2250829575120,937845656300,354860518600,121399651100,37353738800,10272278170,2505433700,536878650,99884400,15890700,2118760,230300,19600,1225,50,1]``[1,51,1275,20825,249900,2349060,18009460,115775100,636763050,3042312350,12777711870,47626016970,158753389900,476260169700,1292706174900,3188675231420,7174519270695,14771069086725,27900908274925,48459472266975,77535155627160,114456658306760,156077261327400,196793068630200,229591913401900,247959266474052,247959266474052,229591913401900,196793068630200,156077261327400,114456658306760,77535155627160,48459472266975,27900908274925,14771069086725,7174519270695,3188675231420,1292706174900,476260169700,158753389900,47626016970,12777711870,3042312350,636763050,115775100,18009460,2349060,249900,20825,1275,51,1]`

# Answer
> 9 votes
# APL (Dyalog Unicode), 7 bytes

```
+∘⌽⍨0,⊢

```

Try it online!

Prepend a zero, and add the mirrored array:

```
1 4 6 4 1
→ 0 1 4 6 4 1 + 1 4 6 4 1 0
→ 1 5 10 10 5 1

```

# APL (Dyalog Unicode), 7 bytes

```
0∘,+,∘0

```

Try it online!

Just realized that the straightforward translation of Iverson's expression is short enough.

# APL (Dyalog Extended), 5 bytes

```
…⍤≢!≢

```

Try it online!

Ignore the content, take the length (n) and evaluate all binomials from nC0 to nCn. In APL, nCk is `k!n`, and `…n` gives `0..n`.

# Answer
> 9 votes
# Python 2, 34 bytes

```
lambda l:map(sum,zip(l+[0],[0]+l))

```

Try it online!

**37 bytes**

```
lambda l:map(int.__add__,l+[0],[0]+l)

```

Try it online!

# Python 2, 38 bytes

```
p=0
for x in input()+[0]:print x+p;p=x

```

Try it online!

# Python 3.8 (pre-release), 37 bytes

```
lambda l,p=0:[p+(p:=x)for x in l]+[1]

```

Try it online!

# Answer
> 8 votes
# Jelly, 2 bytes

```
Ż+

```

A monadic Link accepting a list of integers which yields a list of integers.

**Try it online!**

### How?

Pretty simple in Jelly to go with the method given in the OP, although we do not need to right-pad with a zero since it is implicit in vectorised addition:

```
Ż+ - Link: list, R           e.g. [ 1, 4, 6, 4, 1]
Ż  - prepend a zero (to R)        [ 0, 1, 4, 6, 4, 1]
 + - addition (vectorises)        [ 1, 5,10,10, 5, 1]

```

# Answer
> 7 votes
# 05AB1E, ~~5~~ 4 bytes

```
0šÂ+

```

Try it online or verify all test cases.

Or alternatively:

```
0š+Ć

```

-1 byte thanks to *@ovs*.

Try it online or verify all test cases.

Or yet another alternative (thanks to *@ovs*):

```
gDÝc

```

Try it online or verify all test cases.

**Explanation:**

```
     # (example input: [1,2,1])

0š   # Prepend a 0 to the (implicit) input-list
     #  STACK: [0,1,2,1]
  Â  # Bifurcate the list; short for Duplicate & Reverse copy
     #  STACK: [0,1,2,1], [1,2,1,0]
   + # Add the values at the same positions in the two lists together
     #         [0+1,1+2,2+1,1+0]
     #  STACK: [1,3,3,1]
     # (after which the result is output implicitly)

0š   # Prepend a 0 to the (implicit) input-list
     #  STACK: [0,1,2,1]
  +  # Add the values at the same positions in the two lists together, where the second
     # list is the (implicit) input (because the two lists are of different lengths,
     # the trailing item is ignored)
     #         [0+1,1+2,2+1]
     #  STACK: [1,3,3]
   Ć # Enclose; append its own first item as additional trailing item
     #  STACK: [1,3,3,1]
     # (after which the result is output implicitly)

g    # Get the length of the (implicit) input-list
     #  STACK: 3
 D   # Duplicate this length
     #  STACK: 3,3
  Ý  # Push a list in the range [0,length]
     #  STACK: 3,[0,1,2,3]
   c # Calculate the binomial coefficient between the length and each value in this list
     #  STACK: [1,3,3,1]
     # (after which the result is output implicitly)

```

# Answer
> 7 votes
# Factor, 27 bytes

```
[ 0 suffix dup reverse v+ ]

```

Try it online!

# Answer
> 6 votes
# Haskell, ~~26~~ 25 bytes

```
o l=zipWith(+)(0:l)l++[1]

```

Try it online!

* Saved 1 thanks to @ovs
* New approach, it essentially do this:

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

```

Previous version 30 bytes

```
o=(0#)
x#(v:w)=x+v:v#w
x#_=[x]

```

Try it online!

# Answer
> 6 votes
# convey, ~~13~~ ~~12~~ 10 bytes

```
{,"0
0.>+}

```

Try it online!

# Answer
> 5 votes
# brainf\***, 41 bytes

```
>>>,[>>,]<<[<<]>>[[-<+>>+<]>>]<[<<]>>[.>>]

```

Takes input as character codepoints.

Unfortunately, control characters are currently cancelled on most PC's, so I cannot give a legitimate test case in TIO or any other implementation of brain. : /

# How?

```
>>,[>>,]<<[<<]                                  # Store the input on every other cell
               >>[       ]>>]                   # For every number in the input
                  -<+>>+<                       # Distribute the number to adjacent cells                                                                                Nothing here...
                             <[<<]>>[.>>]       # Output each sum

```

---

Probably my last post of 2020.

# Answer
> 5 votes
# R 4.1, 17 bytes

Only posting because because the function nicely resembles the APL expression.

```
\(x)c(x,0)+c(0,x)

```

# Answer
> 4 votes
# MATL, 4 bytes

```
TTY+

```

**Try it online!**

### How it works

This convolves the input with `[1, 1]`.

# Answer
> 4 votes
# K (oK), ~~8~~ 6 bytes

-2 bytes thanks to Adám!

```
+':|0,

```

Try it online!

# , ~~9~~ 7 bytes

-2 bytes thanks to xash!

```
0&,+,&0

```

Try it online!

Both translated from Bubbler's APL solution \- don't forget to upvote it!

# Answer
> 4 votes
# **PowerShell, 30 27 bytes**

-3 bytes thanks to mazzy

```
($x=$args+0)|%{$_+$x[--$i]}

```

Explanation:

```
 ($x=$args+0)|%{$_+$x[--$i]}
 ($x=                          #assign to $x
     $args+0)                  #the input array with a 0 appended
             |                 #pipe the result of the assignment
              %{           }   #for each item in the piped input
                $_+            #add to that item
                   $x[    ]    #the item of x
                      --$i     #with index equal to the decrement of i.
                               #negative indices in powershell index from
                               #the end of the array, so -1 is the last item
                               #in the array, -2 is second to last, etc.

                               #implicitly output

```

# Answer
> 4 votes
# Nibbles, 4 bytes (8 nibbles)

```
!:0$:@0+

```

## Verbose

```
!   # Zip
  : 0 $   # Prepend 0 to argument
  : @ 0   # Append 0 to argument
  +   # With addition

```

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

Returns a comma-separated string.

```
a=>a.map(v=>p+(p=v),p=0)+[,1]

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 29 bytes

```
Tr/@Partition[#,2,1,{2,1},0]&

```

Try it online!

-3 bytes from @att

# Answer
> 3 votes
# Jelly, 4 bytes

```
Ż+Ṛ$

```

Try it online!

~~Rip off~~ Translation of Razetime's Husk solution, so be sure to send some upvotes his way.

# Answer
> 3 votes
# , 21 bytes

```
c(0,x<-scan())+c(x,0)

```

Try it online!

# Answer
> 3 votes
# Vyxal, 3 bytes

```
0p+

```

Try it Online!

```
    # Implicit input
0p  # prepend 0
  + # (Implicit input) add (vectorised)

```

# Answer
> 3 votes
# brainfuck, 20 bytes

Character codepoints are used as input and output.

```
,[[<+>>+<-]<.>>>,]<.

```

Try it online!

Input is taken in every second cell and added to both surrounding cells. This leaves the output in every other cell.

Example run with input `[1, 2, 1]`:

```
0 0 0 0 0 0 0   The tape is initially filled with 0's
0 1 0 0 0 0 0   ,
  ^             Read the first input into this cell
1 0 1 0 0 0 0   [<+>>+<-]
^   ^           Add the value to both surrounding cells
                <.> and print the cell left to the input
1 0 1 2 0 0 0   >>,
      ^         Move right by 2 cells and take the next input
1 0 3 0 2 0 0
    ^   ^
1 0 3 0 2 1 0
          ^     ...
1 0 3 0 3 0 1
        ^   ^
1 0 3 0 3 0 1
^   ^   ^   ^   The outputs are in these cells
                The trailing <. prints the last output

```

# Answer
> 2 votes
# Husk, 4 bytes

```
Sż+Θ

```

Try it online!

## Explanation

```
Sz+Θ
S     take the input
   Θ  and itself with 0 prepended
 ż+   and zip with addition, preserving elements

```

# Answer
> 2 votes
# Ruby 2.7, 26 bytes

*A port of Arnauld's answer in Ruby.*

```
->a,i=0{a.map{i+i=_1}+[1]}

```

Try it online!

---

# Ruby, 33 bytes

```
->a{(a+[0]).zip([0]+a).map &:sum}

```

Try it online!

# Answer
> 2 votes
# Jelly, 4 bytes

```
LcŻ$

```

Try it online!

Same length as Unrelated String’s answer but uses a different method

# Answer
> 2 votes
# Red, 37 bytes

```
func[c][alter c 0 c + reverse copy c]

```

Try it online!

Takes the input as a `vector!`

Instead of inserting/appending a zero to the list, I use `alter` (for -1 byte) - it appends the value to the list if not present and removes it if present - the zero is guaranteed to not be in the list.

# Answer
> 2 votes
# Scala 3, 26 bytes

```
x=>(0::x)zip(x:+0)map(_+_)

```

Try it online!

Pretty much a literal translation of the original APL expression, albeit more verbose.

# Answer
> 2 votes
# Kakoune, 20 bytes

```
A,0<esc>x_S,
y<a-)>a+<c-r>"<esc>|bc

```

Takes the input in the default buffer, as a sequence of comma-separated list of numbers. Has a trailing newline at the end.

Explanation:

```
A  <esc>                       *A*ppend the following to the end of the line:
 ,0                            Literal ,0
        x                      Select the whole line, including the newline
         _                     Trim the selection, removing the newline
          S,<ret>              Split the selection on every comma
y                              Copy the contents of every selection to the default "-register
 <a-)>                         Rotate the contents of the selections rightwards
      a       <esc>            Append to every selection:
       +                       Literal +
        <c-r>"                 The contents of the "-register
                   |bc<ret>    Pipe every selection into bc, evaluating it

```

# Answer
> 2 votes
## Wolfram Language (Mathematica), 25 bytes (or 14, if phrased as suggested by @att in the comments below)

```
Prepend[#,0]+Append[#,0]&

```

And below is a more "Mathematica-like" solution, in that it uses a mathematical primitive most other languages lack. It requires more bytes than the solution above (which is how most Mathematica programmers would probably solve this in the real world anyway).

```
(n=Length[#];Table[Binomial[n,k],{k,0,n}])&

```

# Answer
> 2 votes
# C# (.NET Core), 98 bytes

```
IEnumerable<long> p(IEnumerable<long> l)=>l.Concat(new[]{0L}).Zip(new[]{0L}.Concat(l),(a,b)=>a+b);

```

Try it online!

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 58 bytes

```
N	J =INPUT	:F(O)
	OUTPUT =I + J
	I =J	:(N)
O	OUTPUT =I
END

```

Try it online!

I/O as numbers separated by newlines.

```
N	J =INPUT	:F(O)	;* Read input. If none exists, goto O
	OUTPUT =I + J		;* Print I (initially 0) + J
	I =J	:(N)		;* Set I to J and goto N
O	OUTPUT =I		;* print I (always 1), and terminate the program
END

```

# Answer
> 1 votes
# MathGolf, 6 bytes

```
ê0▌_x+

```

Port of my 4-bytes 05AB1E program.

Try it online.

**Explanation:**

```
ê       # Push all inputs as integer array
 0▌     # Prepend a 0
   _    # Duplicate the list
    x   # Reverse this copy
     +  # Add the values at the same positions in the two lists together
        # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 1 votes
# Charcoal, 12 bytes

```
ＩＥ⊞Ｏθ⁰⁺ι§θ⊖κ

```

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

```
    θ           Input array
  ⊞Ｏ ⁰          Append literal `0`
 Ｅ              Map over elements
       ι        Current element
      ⁺         Plus
        §θ⊖κ    Previous element (cyclic)
Ｉ               Cast to string
                Implicitly print

```

Alternative approach, relies on symmetry:

```
ＩＥ⮌⊞Ｏθ⁰⁺ι§θκ

```

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

```
     θ          Input array
   ⊞Ｏ ⁰         Append literal `0`
  ⮌             Reverse
 Ｅ              Map over elements
        ι       Current element
       ⁺        Plus
         §θκ    Element from unreversed list
Ｉ               Cast to string
                Implicitly print

```

In both of the above you can replace `⊞Ｏθ⁰` with `θ` and prefix `⊞θ⁰` to the start for the same effect.

# Answer
> 1 votes
# Retina, 32 bytes

```
^|$
¶0¶
Lv$`¶\d+¶(\d+)¶
$.(*_$1*

```

Try it online! Takes each element on a separate line but header and footer of link convert to comma separated and also run a test suite according to the input number of iterations. Explanation:

```
^|$
¶0¶

```

Prefix and suffix a `0` to the list. The extra newlines make it easier to match the pairs of numbers.

```
Lv$`¶\d+¶(\d+)¶

```

Match each overlapping pair of numbers.

```
$.(*_$1*

```

Output the sum of each pair.

# Answer
> 1 votes
# Japt, 6 bytes

```
p0 ä+0

```

Try it

```
p0      - appends 0 to input
   ä+0  - appends 0 and sums each consecutive
          pair of elements

```

# Answer
> 1 votes
# CJam, 8 bytes

```
{_0\+.+}

```

Anonymous block (equivalent to a function) that takes the input array from the stack and replaces it by the output array.

Try it online! Or verify all test cases.

### How it works

```
{      }   e# Define code block
 _         e# Duplicate
  0        e# Push 0
   \       e# Swap
    +      e# Concatenate. Gives the original array with a 0 prepended
     .+    e# Vectorize addition. Works for arrays with unequal lengths

```

# Answer
> 1 votes
# Pari/GP, 15 bytes

Since the input is guaranteed to be a row of Pascal's triangle, I can just take the length of the input and compute the binomial coefficients.

```
a->binomial(#a)

```

Try it online!

# Answer
> 1 votes
# Haskell + hgl, 7 bytes

```
zdm~<Ki

```

In the interest of transparency, this uses `Ki` which I created in response to this challenge. In fact this challenge predates hgl altogether, so do with that information what you will.

## Explanation

`zdm` takes a `SemiAlign` of `Semigroup` elements and combines them with the semigroup action defaulting to the present value if only one is present.

That's a bit of a mouthful. In this case `zdm` takes two lists of numbers and zips them together with addition. In places where there is only one number to add (i.e. the longer end of a list) it just adds zero.

`Ki` adds zero to the front of a list. So when we combine this with `zdm` using `~<` this says, to combine two copies of the input using `zdm`, one with `Ki` applied and the other unchanged.

`K0` and `Ki` both add zero onto the front of a list. But I use `Ki` here because the result is a nice function which can work on more than just lists. For example it will also combine lists or strings in the natural way.

```
ghci> zdm~<Ki$[1,2,3]
[1,3,5,3]
ghci> zdm~<Ki$["a","b","c"]
["a","ab","bc","c"]

```

## Reflections

There's not much to improve here. There's only 3 things being used here and I don't think it makes sense to combine any two of them, or to make a single built in that solves the entire challenge. None of them would get much reuse.

# Answer
> 1 votes
# tinylisp, 56 bytes

```
(load library)
(def g(q((l)(map* a(c 0 l)(insert-end 0 l

```

Try it online!

-12 from Dlosc

# Answer
> 1 votes
# Julia 1.0, ~~15~~ 14 bytes

```
x->[0;x]+[x;0]

```

Try it online!

Pretty close to the APL version.

(-1 byte thanks to @MarcMush.)

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
0Ƥ+

```

Try it online!

#### Explanation

```
0Ƥ+  # Implicit input
0Ƥ   # Prepend 0
  +  # Add to input
     # Implicit output

```

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