title: The n-th Ternary

text:
# Question
Title: The n-th Ternary
I define the n-th ternary as a ternary that returns n and has the form:

```
1 ? 2 ? 3 ? n - 1 ? n : 0 : 0 : 0  # n - 1 zeroes

```

Write a function or complete program that given an input n will output or return the n-th ternary. Code-Golf.

**Testcases**

```
0 #=> undefined behaviour
1 #=> 1
2 #=> 1 ? 2 : 0
3 #=> 1 ? 2 ? 3 : 0 : 0
10 #=> 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0

```

The 1000-th ternary I think there is some kind of zen harmony to it.

# Answer
# Pyth - 19 18 17 bytes

The spaces are killing me, thinking of a better way to handle them.

```
+j" ? "SQ*tQ" : 0

```

It just joins the numbers by a `" ? "` and then concatenates the second part on.

```
+              String concatenation
 j" ? "        Join by the string
  SQ           1-indexed inclusive range to input
 *             String repetition
  tQ           Input - 1
  " : 0        String implicitly closed by end of program

```

Try it online here.
> 9 votes

# Answer
# CJam, 18 18 bytes

```
ri,:)":?0"*2/ze_S*

```

Try it online.

### Explanation

```
ri,:)          e# Generate the list 1..n.
":?0"*         e# Insert ":?0" between every two numbers.
2/             e# Split into pairs, e.g. 1:, ?0, 2:, ?0, ..., ?0, n.
z              e# First items in every pair before second items in every pair.
e_             e# Concatenate the two parts.
S*             e# Insert spaces.

```
> 10 votes

# Answer
# Ruby, 31 bytes

```
f=->n{[*1..n]*' ? '+' : 0'*~-n}

```

Test:

```
> f[1]
=> "1"
> f[7]
=> "1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0"

```
> 9 votes

# Answer
# CJam, 19 bytes

Just a start...

```
ri_,:)'?*\(":0"*+S*

```

**How it works**

```
ri_                       e# Read the number as integer and make a copy of it on stack
   ,:)                    e# Convert the copy to array [1 .. n]
      '?*                 e# Join the numbers with a '?'. So we have [1 '? 2 '? ... '? n]
         \(               e# Swap the stack to get original integer on top. Decrement it by 1
           ":0"*          e# Get n-1 repeated ":0" string
                +S*       e# Join the two strings and fill it with spaces.

```

Try it online here
> 8 votes

# Answer
# Brainfuck, 305

(Without input number from STDIN, see edit at the bottom)

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

```

I used this lovely algorithm to print a number, which takes up 155 bytes of the whole program.

It works for inputs up to 32768 (16-bit limitation of the algorithm). It doesn't produce trailing spaces and works for input `1` as well:

```
input    output
0        [infinite loop (til underflow)]
1        "1"
2        "1 ? 2 : 0"
4        "1 ? 2 ? 3 ? 4 : 0 : 0 : 0"
etc.

```

## Quick walk-through:

### Setup (97 bytes)

```
-                                 Decrease input (position 0)
[->+>+<<]  >>>                    Copy input twice to the right and
                                      shift 3 positions to the right
++++[>++++++++<-]>   [<+>-]       Precalculate number 32 (=" ") at position 3
+++++++[>+++++++++<-]>  [<+>-]    Precalculate number 63 (="?") at position 4
++++++[>++++++++<-]>    [<+>-]    Precalculate number 48 (="0") at position 5
++<<<<                            Precalculate number 2 for later use. This number
                                      will be printed in each iteration. (position 6)

```

### First part (181 bytes)

```
>>>+.-<<<                Go to the char "0" we saved, increase it, print it,
                             decrease it and go back (this prints "1" everytime)
[                        While our second copy of the number isn't zero
    >.>.<.>>>                Move to " ", print, move to "?", print,
                                 move to " " again, print, move to our
                                 number at the end which is initially 2

    [>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
        ++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<
        [.[-]<]<             Algorithm to print the number at current position

    +<<<<                    Increase our number at the end and return to the beginning
-]                       Decrease the loop variable

```

### Second part (27 bytes)

```
>>-----<<<        Move to our "?" char and decrease it by 5 to get ":"
[-                While our first copy of the number isn't zero decrease it
   >>.>.<.>>.<<<<     Print " ", print ":", print " ", print "0"
]

```

If it would be allowed to map the 8 Brainfuck commands to 3 bits, then this program would take up **114** bytes and another 3 bits

# Unary, ~4.08\*10^275 bytes

It would be too long for here, but it's just 408452257862560239329948606295286361112603208650130608525040044700379331457759667646985586658469601803889628246410788572492437928714867190270708935427798983714797786123292750743771225096145575210320040188155473030775033228313350778616384531426430459309802833775612506568528463 zeros and works the same as the Brainfuck program.

**EDIT**: I messed up, this program doesn't take user input really, it just uses the current pointer value as input. For being able to parse a number a whole lot more would be required and I can't be bothered to do that.

So it works with a value directly entered into the program (by appending n times "+" before the program) but not with STDIN
> 6 votes

# Answer
# JavaScript (ES6), ~~42~~ 39 bytes

```
f=m=>(g=k=>k-m?k+` ? ${g(k+1)} : 0`:m)(1)

```

The outer function `f` takes the input value and then calls the inner function `g` recursively to build the string from the middle out, using the input value as a maximum to test for the base case.

Ungolfed:

```
function f(max) {
    function g(count) {
        if(count==max) {
            // base case: return max for the center
            return max;
        } else {
            // recursive case: build outer shell around center
            return count + " ? " + g(count+1) + " : 0";
        }
    }

    return g(1);
}

```
> 5 votes

# Answer
# Python 56 55

```
t=lambda n:' ? '.join(map(str,range(1,n+1)))+' : 0'*~-n

```
> 4 votes

# Answer
# C# - 76

```
Func<int,string>F=k=>{var r="";for(;k>1;)r=" ? "+k--+r+" : 0";return"1"+r;};

```
> 4 votes

# Answer
# Julia, ~~44~~ 31 bytes

```
n->join(1:n," ? ")*" : 0"^(n-1)

```

This creates an unnamed function that accepts an integer as input and returns a string. To call it, give it a name, e.g. `f=n->...`.

First we join together the integers 1 to *n*, separating each with `?` and spaces into a single string. Then we append to this the string `" : 0"` repeated *n*-1 times.

Examples:

```
julia> f(1)
"1"

julia> f(3)
"1 ? 2 ? 3 : 0 : 0"

julia> f(0)
can't repeat a string -1 times

```
> 3 votes

# Answer
# Haskell, 53 bytes

```
g n='1':foldr(\x s->" ? "++show x++s++" : 0")""[2..n]

```

How it works: build the string from inside out by starting with an empty string and looping from `n` down to `2` with prepending the current number and a `?` and appending a `: 0`. Finally put a `1` in front of all.

A different approach (thanks to @Mauris now 9 bytes shorter):

# Haskell, ~~60~~ 51 bytes

```
 f n='1':((=<<[2..n])=<<[(" ? "++).show,\x->" : 0"])

```

How it works: a literal `1` followed by `? <x>` for each `<x>` in `[2..n]` followed by a constant `: 0` for each `<x>` in `[2..n]`.
> 3 votes

# Answer
# Pyth, 17 bytes

```
jd.iSQs*RtQ,\?":0

```

Demonstration.
> 3 votes

# Answer
# Perl, 36 bytes

```
say join(" ? ",1..$_)." : 0"x($_-1)

```

`35` characters `+1` for `-n`.

Run with:

```
echo 10 | perl -nE'say join(" ? ",1..$_)." : 0"x($_-1)'

```
> 3 votes

# Answer
# JavaScript ES7, 62 bytes

```
n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1)

```

I don't know if I can golf this more. But it's a pretty straightforward solution

Firefox only:

```
var f=n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1)

alert(f(+prompt('Input: ')));
```

ES5 equivalent:

```
// Most browsers now support .repeat
String.prototype.repeat = String.prototype.repeat || function(n){var _n = '', i = 0; for (;i < n; i += 1){_n+=this};return _n}
                                                             //Function
function f(n){a=[];for(i of Array(n).keys()){a.push(i+1)};return a.join(' ? ')+' : 0'.repeat(n-1)}

alert(f(+prompt('Input: ')))
```
> 2 votes

# Answer
## CoffeeScript, 52 bytes

```
f=(n)->s='';s=' ? '+n--+s+' : 0'while n;s.slice 3,-4

```

### Explanation

```
f=(n)->
 s = ''                                # initialize string
 s = ' ? ' + n-- + s + ' : 0' while n  # prepend and append in decrementing loop
 s.slice 3,-4                          # chop off leading ?, trailing 0 and whitespace

```
> 2 votes

# Answer
# SWI-Prolog, 90 bytes

```
a(X):-Y is X-1,\+ (between(1,Y,L),\+writef('%w ? ',[L])),write(X),writef('%r',[' : 0',Y]).

```

Definitely not going to win, but the `\+ (between(1,TopBound,N),\+do_something(N))` construction is pretty interesting to repeat something on a sequence of integers.
> 2 votes

# Answer
# Swift 145 (135 w/o whitespace)

```
func t(n:Int) -> String {
    let a = (1..<n).reverse().reduce("") {" ? \($1)\($0) : 0"}
    return a.substringFromIndex(advance(a.startIndex, 3))
}

```

Can you believe the part to substring is actually longer than the part to produce the expression.
> 2 votes

# Answer
## Java, ~~125~~ 88 bytes

**Original**

```
String f(int n){if(n==1)return"1";String s="",e="";for(int i=1;i<n;i++){s+=i+" ? ";e+=i==n-1?": 0":": 0 ";}return s+n+" "+e;}

```

With nicer formatting and variable names:

```
String nAry(int n) {
    if (n == 1) {
        return "1";
    }
    String start = "", end = "";
    for (int i = 1; i < n; i++) {
        start += i + " ? ";
        end += (i == n - 1) ? ": 0" : ": 0 ";
    }
    return start + n + " " + end;
}

```

**Improved -** Thanks to Jack Ammo's comments below:

```
String f(int n){String s="",e=s;for(int i=1;i<n;){s+=i+++" ? ";e+=" : 0";}return s+n+e;}

```
> 2 votes

# Answer
# Java, 71

I couldn't help myself after commenting on RCB's answer. So here's another Java (71 like wow when is Java not the longest!)

```
String t(int n){String s=""+n;for(;--n>0;)s=n+" ? "+s+" : 0";return s;}

```
> 2 votes

# Answer
## JavaScript (ES6), 59 bytes

Same approach as my CoffeeScript answer, using template strings help. `String.prototype.repeat` costs too many characters.

```
f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)}

```

### Demo

Firefox only for now, as it is ES6.

```
f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)}

// DEMO
console.log = x => document.body.innerHTML += '<p>' + x

console.log(f(1));
console.log(f(3));
console.log(f(10));
```
> 1 votes

# Answer
# Python 2, ~~63~~ ~~60~~ ~~58~~ 56

**Try it here**

Easy solution: (63)

```
n=input()
for i in range(n-1):print-~i,'?',
print`n`+' : 0'*~-n

```

**Edit**: I really wanted to try a recursive function. Here it is: (56)

```
f=lambda n,c=1:`c`+(' ? '+f(n,c+1)if c<n else~-n*' : 0')

```

**Edit**: Anyone know why this isn't working? I tried a list with an index of `c<n`, but that didn't work because of a stack overflow error. Same with this:

```
f=lambda n,c=1:`c`+((c<n)*(' ? '+f(n,c+1))or~-n*' : 0')

```
> 1 votes

# Answer
# K, 36 bytes

```
{(3_,/(" ? ",)'$!x),(4*-1+x)#" : 0"}

```
> 1 votes

# Answer
# Swift, 79 75 bytes

```
let f={{$0+$1}((1..<$0).reduce(("1","")){($0.0+" ? \($1+1)",$0.1+" : 0")})}

```

`f` is implicitly declared as a function with one `Int` parameter which returns a `String`

Works with `n >= 1` and crashes at runtime when `n == 0`. There are no trailing whitespaces

Edit: Managed to remove 2\*2 characters, because string interpolation isn't always the shortest

Note to edit: This code takes forever (it doesn't stop) to compile, but it definitely would if the compiler would be able to handle it. Take a look at the version before this edit to get one that compiles
> 1 votes

# Answer
# rs, 77 bytes

```
(\d+)/(_)^^(\1)
+^_(_+)/\1 _\1
_(_+)$/_\1( : 0)^^((^^\1))
(__+)/? (^^\1)
^./1

```

Live demo and test cases.

## Explanation:

```
(\d+)/(_)^^(\1)

```

Expand the number into a series of N underscores.

```
+^_(_+)/\1 _\1

```

Repeatedly create a range of underscores, separated by spaces. e.g. This would turn `___` into `_ __ ___`.

```
_(_+)$/_\1( : 0)^^((^^\1))

```

Append to the last set of underscores (of length N) N-1 instances of  `: 0`.

```
(__+)/? (^^\1)

```

Replace each group of underscores by it's length, preceded by `?`, EXCEPT for the first one.

```
^./1

```

Replace the first one with the number 1.

Because of the format, this also handles `0` well: it just prints the empty string.
> 1 votes

# Answer
# \>\<\>, 32 + 3 = 35 bytes

```
:l(?vln" ? "ooo0$
"ooo>nl?!;" :

```

Note that there is a trailing space on the second line. The +3 is for the `-v` flag, e.g. run like

```
$ py -3 fish.py ternary.py -v 2
1 ? 2 : 0

```

Taking input as a code point like

```
i:l(?vln" ? "ooo0$!
 "ooo>nl?!;" :

```

is 34 bytes, but I prefer the above version since it's easier to test and it won't win anyway.

## Explanation

There's quite a bit of pseudo-recursion and abuse going on, so let's take a look.

The first line prints the `"1 ? 2 ? ... n-1 ? "` part. The stack starts off with just the input `n`, thanks to the `-v` flag, and we do the following:

```
:l(?v           If (length of stack + 1 > n), go to the second line
ln              Print the length of the stack
" ? "ooo        Print the reverse of " ? " (but hey, palindromes)
0$              Push 0 and swap, keeping n on top and increasing the
                length of the stack by 1

```

\>\<\> is toroidal, so the above executes in a loop until the stack consists of `n` at the top with `n-1` zeroes below, at which point it moves to the second line.

The first time the second line is executed, the `n` instruction is run, printing the `n` at the top of the stack. This leaves just the `n-1` zeroes, and we do the following, also in a loop:

```
l?!;            If the stack is empty, terminate
" : "ooo        Print the reverse of " : " (but hey, palin...)
n               Print one of the 0s, decreasing the stack's length by 1
                This reuses the same n instruction from before

```
> 1 votes

# Answer
## Scala, ~~78~~ ~~71~~ ~~52~~ 50 bytes

```
def f(n:Int)=(1 to n).mkString(" ? ")+" : 0"*(n-1)

```
> 1 votes

# Answer
# Objective-C, 346 bytes

```
-(void)printTernaryOfInt:(int)ternary{NSMutableString *outString=@"".mutableCopy; for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];}[outString deleteCharactersInRange:NSMakeRange(0, 2)];for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];}NSLog(@"%@",outString);}

```

Putting in `0` for the `int` or anything negative raises an `NSRangeException` due to `outString` containing `nil`. This should run on iOS 2.0 and later and many of the latest versions of Mac OS X.

### A breakdown of the code:

```
-(void)printTernaryOfInt:(int)ternary{ ... }

```

Standard function declaration in Objective-C.

```
NSMutableString *outString=@"".mutableCopy;

```

Makes a string for output to go to, `outString`, and makes it mutable. (In other words, it can be read and written to.

```
for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];}

```

Adds the first part of the string to output.

```
[outString deleteCharactersInRange:NSMakeRange(0, 2)];

```

Cleans up the beginning of the string to make sure `? 1` is replaced with `1`. Note: if `0` was given, this is where the `NSRangeException` would occur, due to there not being an index `1`.

```
for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];}

```

Adds the second part of the string to the string.

```
NSLog(@"%@",outString);}

```

Spits the string back out using `NSLog` and closes off the function.

### Output:

Inputting `0` gives this crash log:

```
    2015-07-11 05:15:28.036 Example App[41665:2134488] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString deleteCharactersInRange:]: Range or index out of bounds'
*** First throw call stack:
(
    0   CoreFoundation                      0x009b5746 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x0063ea97 objc_exception_throw + 44
    2   CoreFoundation                      0x009b566d +[NSException raise:format:] + 141
    3   CoreFoundation                      0x00981813 mutateError + 259
    4   CoreFoundation                      0x009818c1 -[__NSCFString deleteCharactersInRange:] + 65
    5   Example App                         0x000e3785 -[ViewController printTernaryOfInt:] + 277
    6   Example App                         0x000e3645 -[ViewController placeOrder:] + 133
    7   libobjc.A.dylib                     0x006547cd -[NSObject performSelector:withObject:withObject:] + 84
    8   UIKit                               0x00d75a40 -[UIApplication sendAction:to:from:forEvent:] + 99
    9   UIKit                               0x00d759d2 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64
    10  UIKit                               0x00eb613a -[UIControl sendAction:to:forEvent:] + 69
    11  UIKit                               0x00eb6557 -[UIControl _sendActionsForEvents:withEvent:] + 598
    12  UIKit                               0x00eb57c1 -[UIControl touchesEnded:withEvent:] + 660
    13  UIKit                               0x00dcdcaa -[UIWindow _sendTouchesForEvent:] + 874
    14  UIKit                               0x00dce786 -[UIWindow sendEvent:] + 792
    15  UIKit                               0x00d8c681 -[UIApplication sendEvent:] + 242
    16  UIKit                               0x00d9cab8 _UIApplicationHandleEventFromQueueEvent + 21484
    17  UIKit                               0x00d702e7 _UIApplicationHandleEventQueue + 2300
    18  CoreFoundation                      0x008d706f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    19  CoreFoundation                      0x008ccb7d __CFRunLoopDoSources0 + 253
    20  CoreFoundation                      0x008cc0d8 __CFRunLoopRun + 952
    21  CoreFoundation                      0x008cba5b CFRunLoopRunSpecific + 443
    22  CoreFoundation                      0x008cb88b CFRunLoopRunInMode + 123
    23  GraphicsServices                    0x029e42c9 GSEventRunModal + 192
    24  GraphicsServices                    0x029e4106 GSEventRun + 104
    25  UIKit                               0x00d740b6 UIApplicationMain + 1526
    26  Example App                         0x000e3cfa main + 138
    27  libdyld.dylib                       0x02d76ac9 start + 1
    28  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

```

`1` gives this:

```
2015-07-11 05:06:02.360 Example App[41665:2134488]  1

```

`2` gives this:

```
2015-07-11 05:06:07.613 Example App[41665:2134488]  1 ? 2 : 0

```

`7` gives this:

```
2015-07-11 05:06:12.147 Example App[41665:2134488]  1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0

```

`200` gives this:

```
2015-07-11 05:06:35.552 Example App[41665:2134488]  1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 ? 11 ? 12 ? 13 ? 14 ? 15 ? 16 ? 17 ? 18 ? 19 ? 20 ? 21 ? 22 ? 23 ? 24 ? 25 ? 26 ? 27 ? 28 ? 29 ? 30 ? 31 ? 32 ? 33 ? 34 ? 35 ? 36 ? 37 ? 38 ? 39 ? 40 ? 41 ? 42 ? 43 ? 44 ? 45 ? 46 ? 47 ? 48 ? 49 ? 50 ? 51 ? 52 ? 53 ? 54 ? 55 ? 56 ? 57 ? 58 ? 59 ? 60 ? 61 ? 62 ? 63 ? 64 ? 65 ? 66 ? 67 ? 68 ? 69 ? 70 ? 71 ? 72 ? 73 ? 74 ? 75 ? 76 ? 77 ? 78 ? 79 ? 80 ? 81 ? 82 ? 83 ? 84 ? 85 ? 86 ? 87 ? 88 ? 89 ? 90 ? 91 ? 92 ? 93 ? 94 ? 95 ? 96 ? 97 ? 98 ? 99 ? 100 ? 101 ? 102 ? 103 ? 104 ? 105 ? 106 ? 107 ? 108 ? 109 ? 110 ? 111 ? 112 ? 113 ? 114 ? 115 ? 116 ? 117 ? 118 ? 119 ? 120 ? 121 ? 122 ? 123 ? 124 ? 125 ? 126 ? 127 ? 128 ? 129 ? 130 ? 131 ? 132 ? 133 ? 134 ? 135 ? 136 ? 137 ? 138 ? 139 ? 140 ? 141 ? 142 ? 143 ? 144 ? 145 ? 146 ? 147 ? 148 ? 149 ? 150 ? 151 ? 152 ? 153 ? 154 ? 155 ? 156 ? 157 ? 158 ? 159 ? 160 ? 161 ? 162 ? 163 ? 164 ? 165 ? 166 ? 167 ? 168 ? 169 ? 170 ? 171 ? 172 ? 173 ? 174 ? 175 ? 176 ? 177 ? 178 ? 179 ? 180 ? 181 ? 182 ? 183 ? 184 ? 185 ? 186 ? 187 ? 188 ? 189 ? 190 ? 191 ? 192 ? 193 ? 194 ? 195 ? 196 ? 197 ? 198 ? 199 ? 200 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0

```
> 1 votes

# Answer
# C, ~~84~~ 78 bytes

C, even though it is not the shortest, as a function:

```
i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");}

```

In the name of golfing, the `int` type specifier is left off of `i`, `f`, and `n` because it is the default. `i` can be uninitialized because it is a global variable and defaults to zero. `f` does not return a value, but that only causes a warning. `printf` is not `#include`'d. To run, here is a full program version:

```
#include <stdio.h>

i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");}

int main(int argc, char *argv[]){
    if(argc != 2){
        return 1;
    }
    f(atoi(argv[1]));
    puts("");
}

```
> 1 votes

# Answer
# C, 63 bytes

Reusable function, takes n as an argument.

```
i;f(n){for(i=1;i<2*n;i++)printf(i-1?n/i?" ? %d":" : 0":"1",i);}

```

Ungolfed and commented (pretty straightforward):

```
int f(int n) {
    int i;

    // 1 ... n, n+1 ... 2n-1
    for(i = 1; i < 2*n; i++) {
        // If i == 1, prints "1"
        // If i <= n, prints " ? %d", i (i = 2 ... n)
        // Else, prints " : 0" (i = n+1 ... 2n-1)
        printf(
            i-1 ?
                n/i ?
                    " ? %d" :
                    " : 0" :
                "1",
        i);
    }
}

```
> 1 votes

# Answer
# Common Lisp, 84

```
(format t "~{~A ? ~}~@*~{~[~;~:;0~^ ? ~]~}" (loop for i from 1 to (read) collect i))

```

First, `(loop for i from 1 to (read) collect i)` generates a list of integers from 1 to whatever is put in, which is used as the only argument to the function. But the real magic of it is in the control string that looks like line noise. `"~{~A ? ~}"` iterates over the entire list stored within the first argument, outputting each number with the `?` for the first half. `~@*` resets the argument list to the first argument. `~{~[~;~:;0~^ ? ~]~}` reiterates over the list, outputting `0 ?` for each argument consumed, but outputting nothing if the argument is 0 or 1.
> 1 votes

# Answer
# PowerShell Core, ~~52~~ 38 bytes

```
param($a)(1..$a-join' ? ')+' : 0'*--$a

```

Try it online!

Save 14 bytes thanks to *mazzy*!
> 1 votes

# Answer
# Jelly, 12 bytes

```
Rj“:?0”s2ZFK

```

Try it online!

## How it works

```
Rj“:?0”s2ZFK - Main link. Takes n on the left
R            - Yield the range [1, 2, ..., n]
 j“:?0”      - Join by “:?0”; [1, ":", "?", "0", 2, ..., ":", "?", "0", n]
       s2    - Split into pairs; [[1, ":"], ["?", "0"], ..., ["?", "0"], [n]]
         Z   - Transpose; [[1, "?", ..., "?", n], [":", "0", ..., ":", "0"]]
          F  - Flatten; [1, "?", 2, ..., "?", n, ":", "0", ..., ":", "0"]
           K - Join by spaces; "1 ? 2 ... ? n : 0 ... : 0"

```
> 0 votes

# Answer
# Stax, 12 bytes

```
å■Åxb◄34Γφ¥r

```

Run and debug it
> 0 votes

# Answer
# Zsh, 50 bytes

```
s=${(j: ? :)$(seq $1)}
repeat $1-1 s+=' : 0'
<<<$s

```

Try it online!
> 0 votes

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


title: Draw an ASCIIrisk

text:
# Question
Title: Draw an ASCIIrisk
There are an abundance of questions involving drawing shapes using asterisks - so I thought, with so many asterisks out there, we should draw one, using the ASCII table.

## Challenge

Your task is to write a program or function which takes no input, and outputs this exact text:

```
          !
         "#
         $%
         &'
         ()
         *+
         ,-
         ./
         01
23456789:;<=>?@ABCDEF
GHIJKLMNOPQRSTUVWXYZ[
        \]^_
       `a  bc
      de    fg
     hi      jk
    lm        no
   pq          rs
  tu            vw
 xy              z{
|}                ~

```

For reference, this site lists the complete ASCII table.

# Rules

* The output should be the exact text, as shown above. Leading/trailing whitespace is allowed.
* Standard golfing loopholes apply - no reading this ASCIIrisk from the internet, etc.
* This is , so the shortest solution (in bytes) wins.

# Answer
# 05AB1E, ~~40~~ ~~38~~ ~~37~~ ~~36~~ 35 bytes

```
žQ2ô376S3*£`2ôvyN·ð×ýð«}rsJ2äsr)˜.c

```

Try it online!

**Explanation**

```
žQ                                   # push the printable ascii chars
  2ô                                 # split into pairs
    376S                             # split the number 376 into a list of digits
        3*                           # multiply each by 3 to get [9,21,18]
          £                          # divide the pairs of ascii chars into
                                     # pieces of these sizes
           `                         # flatten list to stack
            2ô                       # split the "legs" of the asterisk into pairs of pairs
              v                      # loop over the pairs of pairs
               yN·ð×ý                # join the pairs by index*2 spaces
                     ð«              # append a space
                       }             # end loop
                        rs           # move the middle section to top of stack
                          J2ä        # convert to a string split into 2 pieces
                             sr      # rearrange the stack in the correct order
                               )˜    # wrap in a flattened list
                                 .c  # pad each element with spaces on either side

```
> 7 votes

# Answer
# Python 3, 110 bytes

```
s='%c';print(('\n'.join(['%10c%c']*9+[s*21]*2+[' '*(8-i)+s*2+'  '*i+s*2for i in range(9)]))%(*range(32,128),))

```

Generates the template

```
         xx
         xx
         xx
         xx
         xx
         xx
         xx
         xx
         xx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
        xxxx
       xx  xx
      xx    xx
     xx      xx
    xx        xx
   xx          xx
  xx            xx
 xx              xx
xx                xx

```

with `%c` for `x`, then uses string interpolation on `range(32,128)` to insert the ASCII values into the pattern.

Try it online!

Python 2 is one byte longer, with longer tuple unpacking but shorter `print`.

```
s='%c';print('\n'.join(['%10c%c']*9+[s*21]*2+[' '*(8-i)+s*2+'  '*i+s*2for i in range(9)]))%tuple(range(32,128))

```
> 13 votes

# Answer
# , ~~54~~, 50 bytes

```
¬ ~9ñ9É 11|á
ñ2ñ20lá
ñ$18é 9ñ^y|Ehé
Pf xxywk$hP>ñd

```

Try it online!

Unlike usual, this program does not contain any unprintable characters.

Explanation:

```
¬ ~                     " Insert the entire printable ASCII range
   9ñ           ñ       " 9 times:
     9É                 "   Insert 9 spaces at the beginning of this line
        11|             "   Move to the 11'th column on this line
           á<CR>        "   And append a newline after the 11'th column

```

Now the buffer looks like this:

```
          !
         "#
         $%
         &'
         ()
         *+
         ,-
         ./
         01
23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

Now we build up the middle:

```
2ñ        ñ             " Two times:
  20l                   "   Move 20 characters to the right (because 'l' == 'right', duh)
     á<CR>              "   Append a newline

```

Here's where it gets a little weird.

```
$                       " Move to the end of this line
 18é                    " Insert 18 spaces before the last character
     9ñ                 " Repeat the following 9 times:
       ^                "   Move to the first non-whitespace character
        y|              "   Yank all the whitespace before the current character.
                        "   We'll call this the "Leading whitespace register"
          E             "   Move to the end of the current WORD (up to before a space)
           h            "   Move back one character
            é<CR>       "   And insert a newline before the current character
P                       "   Paste the leading whitespace for indentation
 f                      "   Move forward to a space
   xx                   "   Delete two characters
                        "   (Note how we are inbetween the two bottom branches right now)
     yw                 "   Yank everything upto the next branch (all spaces)
                        "   We'll paste this on the line up so that we can yank it again later
                        "   To keep track of how far apart the branches are
       k$               "   Move up a line and to the end of that line
         hP             "   Move back a character and paste the whitespace we yanked
           >            "   Indent this line by one space
            ñ           "   End the loop

```

Here's an important note. The `>` command is actually an *operator*, which means it doesn't do anything without an argument, the text to operate on. For example,

```
>_      "Indent the current line
>>      "Indent the current line
>j      "Indent the current and next line
>G      "Indent every line

```

But since this command is in a loop, we can save a character by not giving an operator. At the end of a loop, if any operator is pending it will fill in `_` (the current line) as an argument implicitly.

Now I'll admit this loop is a little weird, and it can be hard to keep track of what all text should look like at any given moment. So you can use this simpler program to see what it will look like after **N** loops.

If you set it to 9, you can see that we have a little bit of extra text to get rid of. (Just the current line).

So we delete the current line with `dd`. But wait! You know how I said that operators have to take an argument which is sometime implicitly filled in? Arguments are also implicitly filled at the end of the program. So rather than `dd` or `d_` (which are equivalent), we can simply to `d` and let V fill in the `_` for us.
> 11 votes

# Answer
# Poetic, 899 bytes

```
ill be honest with you
i expect a big solitude
i guess i had a guilt
my own idea being:i was real alone,i was a lonely human
also,i am still
o,i guess i was expecting a shift
i figured,surely i know i am tired of silence
now i dreamed for a shift
a magical desire cant come
i am barely a man,so i guess i see why a woman i see ignores myself
i know i am awful
o,a night of passion and a moment of love
i am truly the foolish person,every time i am saying i may recapture a love
o,i think i can,i think i can
i really do know i am unfit
o,i notice a lot,i think i know i am unfit
o,a novel,or perhaps poetry in code,i do enjoy the writing
and i shudder and i wonder in a moment
i was a weirdo,i was a freak,or like,i am creepy
o,i think i was a misfit
i know i am,really
o,i ought not concern myself
and sure,i am still some joyless man
i focused and i tried
a lasting solace and joy is nearby for me

```

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

This poem is...depressing.
> 6 votes

# Answer
# Python 3 ~~170~~ ~~165~~ ~~155~~ 147 bytes

I've golfed this so much, I've forgotten how it works...

```
i=b=0
for x in range(32,127):a=x%2<1;c=x>90;d=x<50;print(end=[' '*9*d,['\n'+' '*(8-i),'  '*~-i][b]][c]*a+chr(x)+'\n'*(x==70or d*x%2));b^=a;i+=b*c*a

```

**Try it online!**
> 5 votes

# Answer
## JavaScript (ES6), ~~156~~~~115~~ 114 bytes

Sadly, the infamous `String.fromCharCode()` costs 19 bytes.

```
f=(x=y=k=1)=>k<96?String.fromCharCode(x-22?y/2^5&&(y>9?x-y+1>>1&&22-y-x>>1:x/2^5)?32:31+k++:(x=!++y,10))+f(x+1):''

console.log(f())
```

### Formatted and commented

```
f = (                         // given:
  x =                         //   - x = current column
  y =                         //   - y = current row
  k = 1                       //   - k = current ASCII character code, minus 31
) =>                          //
  k < 96 ?                    // if we havent't reached character #127 (96 + 31):
    String.fromCharCode(      //   let's compute the next character
      x - 22 ?                //   if x is not equal to 22 (end of line):
        y / 2 ^ 5 && (        //     if y doesn't equal 10 or 11 (horizontal bar):
          y > 9 ?             //       and either y is greater than 9:
            x - y + 1 >> 1 && //         and we are not located on one of the
            22 - y - x >> 1   //         bottom diagonals
          :                   //       or y is less or equal to 9:
            x / 2 ^ 5         //         and x doesn't equal 10 or 11 (vertical bar)
        ) ?                   //     then:
          32                  //       append a space
        :                     //     else:
          31 + k++            //       append the next ASCII character
      :                       //   else:
        (x = !++y, 10)        //     increment y, reset x and append a LineFeed
    ) + f(x + 1)              //   do a recursive call with x + 1
  :                           // else:
    ''                        //   stop recursion

```
> 5 votes

# Answer
## QBIC, ~~153~~ 151 bytes

```
[32,49,2|?space$(9)+chr$(a)+chr$(a+1)][2|X=Y[a,a+20|X=X+chr$(c)]a=a+21?X][0,8|X=space$(8-d)[0,1|X=X+chr$(a+e)]X=X+space$(d*2)[2,3|X=X+chr$(a+f)]a=a+f?X

```

It's really just a series of FOR-loops and casting an int to a character (`chr$()`).

Sample output:

```
          !
         "#
         $%
         &'
         ()
         *+
         ,-
         ./
         01
23456789:;<=>?@ABCDEF
GHIJKLMNOPQRSTUVWXYZ[
        \]^_
       `a  bc
      de    fg
     hi      jk
    lm        no
   pq          rs
  tu            vw
 xy              z{
|}                ~

```
> 3 votes

# Answer
# Perl, 113 bytes

112 bytes of code + `-l` flag.

```
sub g{chr$c+++32}print$"x9,&g,&g for 0..8;print map&g,0..20for 0,1;print$"x-$_,&g,&g,$"x(16+2*$_),&g,&g for-8..0

```

Try it online!
> 3 votes

# Answer
# PHP, ~~110~~ ~~105~~ ~~103~~ ~~93~~ 91 bytes

```
for(;$c<95;$y+=!$x%=21)echo"
"[$x],chr(31+($y%11<9&(max($y,10)-abs(9.5-$x++))%11<9?:++$c));

```

prints a leading newline. Run with `-nr` or test it online.

The basic principle is adopted from Arnauld, but this iterates.
And it takes good advantage from PHP´s implicit typecasts:
NULL to int for string index, float to int for `%`, boolean to int for `&` and for `+=`.

**explanation with pseudo code**

```
If $x is 0, print a newline. ("\n"[$x] is newline for $x=0; empty for every larger $x)
if $y is neither 9 nor 10 (not middle part: $y<9|$y>10 <=> $y%11<9)
AND distance to center == abs(9.5-$x) (in [0.5,1.5,..,10.5]) ->
    lower part:     abs($y-10-distance)>1                   => ($y-distance)%11<9
                (this works because $y is always <20)
    upper part: $x<9|$x>10 <=> distance>1 <=> 10-distance<9 => (10-distance)%11<9
                (this works because % has negative results for negative first operands)
    both parts: $y>9?$y:10 <=> max($y,10)
// $a?:$b evaluates to $a if $a is truthy, to $b else
// and the ternary condition evaluates to 1 if the coords are not in the shape
then print chr(31+1) = space
else print chr(31+incremented $c)

```
> 3 votes

# Answer
# Pyth, 53 bytes

```
js.e@[+L*9;cb2c2b.e+*-8Ydj*yYdZcL2cb4)kcsrdC127,18 60

```

A program that prints the result.

Try it online!

**How it works**

`srdC127` creates a list of the printable ASCII characters and concatenates this to a string.

`c....,18 60` splits this string at indices `18` and `60`, giving a list of three strings corresponding to the different parts of the output: the top, the middle and the bottom.

`.e` begins an enumerated map over the strings with the strings as `b` and their indices as `k`.

`[...)` creates a list containing the desired action for each part of the diagram. The correct action is chosen by indexing into the list with the current index, using `@...k`.

* *Top*

`cb2` splits the string into pairs of characters, and `+L*9;` prepends `9` spaces to each pair.
* *Middle*

`c2b` splits the string into two equal-length strings.
* *Bottom*

`cL2cb4` splits the string into groups of four characters, and each group into pairs.

`.e` begins an enumerated map, with the string pairs as `Z` and their indices as `Y`.

`j*yYdZ` joins the pairs on `2*Y` spaces, and `+*-8Yd` prepends `8-Y` spaces.

`js` merges all the results and joins the resulting list on newlines. This is then implicitly printed.
> 2 votes

# Answer
# Haskell, 144 bytes

```
b!n=[1..n]>>b
('*':r)#(a:s)=a:r#s
(a:r)#s=a:r#s
r#s=r
p="**"
f=unlines([" "!9++p]!9++["*"!21]!2++[" "!(8-n)++p++" "!(2*n)++p|n<-[0..8]])#[' '..]

```

Try it online!

**Explanation:**

`b!n=[1..n]>>b` defines a function `!` which repeats a list or string `b` `n`-times.

`unlines([" "!9++p]!9++["*"!21]!2++[" "!(8-n)++p++" "!(2*n)++p|n<-[0..8]])` uses this function to draw an asterisk of asterisks (Oh, the irony!):

```
         **
         **
         **
         **
         **
         **
         **
         **
         **
*********************
*********************
        ****
       **  **
      **    **
     **      **
    **        **
   **          **
  **            **
 **              **
**                **

```

`#` is defined as a function which consecutively replaces `*` in a string with chars from a given list. It's called with the above asterisk of asterisks and `[' '..]` which is an infinite list of all characters starting with the space `' '`.
> 2 votes

# Answer
# Charcoal, 39 bytes (noncompeting)

```
ＧＨ↑χ→⁴↓χ→¹¹↓⁴←χ↘χ←⁴↖⁹←²↙⁹←⁴↗χ←⁹↑⁴→⁹ ↓¤γ

```

Try it online! AST provided for explanation, `χ` being the preinitialized variable for `10`.
> 2 votes

# Answer
# J, 63

~~(not competing)~~

```
a.{~32>.31+20 21$(* +/\),(9 21&$@{.,1:,1:,}.)(+.1&|."1)|.=|i:10

```

the expression evaluates right to left thus:

* `i: 10` counts from -10 to +10
* `|` take abs to get +10 to 0 back to +10
* `=` self classify to get V shape of 1's in a block of 0's
* `|.` reverse row order to get /\ shape
* `( +. 1&|."1 )` hook expression shifts each row right by one and OR's with original
* `( 9 21&$@{. , 1: , 1: , }. )` nested forks to put in horizontals and stretch top
* `,` to raze the block into a linear sequence for cumulation
* `( * +/\ )` cumulate and multiply with self
* `20 21 $` revert shape to a block 20 rows of 21 elements
* `31 +` add 31 because first 1 should be a space char code 32
* `32 >.` floor at 32
* `a. {~` pick chars from ascii built-in
> 2 votes

# Answer
# Tcl, 209 bytes

```
proc I {} {incr ::i}
proc A {} {time {append a [$::F %c [I]]} 21;puts $a}
set i 31
time {puts [[set F format] %10c%c [I] [I]]} 9
A
A
time {puts [$F %[expr 32-[I]/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```

Try it online!

---

~~Tcl, 212 bytes
```
proc I {} {incr ::i}
proc A {} {time {append a [$::F %c [I]]} 21;puts $a}
set i 31
time {puts [[set F format] %10c%c [I] [I]]} 9
A
A
time {puts [$F %[expr (129-[I])/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
Try it online!
~~

##

~~tcl, 213
```
proc I {} {incr ::i}
set F format
proc A {} {time {append a [$::F %c [I]]} 21;puts $a}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
A
A
time {puts [$F %[expr (129-[I])/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```~~

~~demo~~

---

~~tcl, 214
```
proc I {} {incr ::i}
set F format
proc A {} {time {append a [$::F %c [I]]} 21;puts $a}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
A
A
time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
demo~~

---

~~tcl, 227
```
proc I {} {incr ::i}
set F format
proc A {} {time {append ::a [$::F %c [I]]} 21}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
A
set a $a\n
A
puts $a
time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
demo~~

##

~~tcl, 236
```
proc I {} {incr ::i}
set F format
proc A {} {time {append ::a [$::F %c [I]]} 21}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
set a ""
A
set a $a\n
A
puts $a
time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
demo~~

---

~~tcl, 237
```
proc I {} {incr ::i}
set F format
proc A {} {time {set ::a $::a[$::F %c [I]]} 21}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
set a ""
A
set a $a\n
A
puts $a
time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
demo

---

Alternative approach with same size:
```
proc I {} {incr ::i}
set F format
proc A b {time {upvar $b c;set c $c[$::F %c [I]]} 21}
set i 31
time {puts [$F %10c%c [I] [I]]} 9
set a ""
A a
set a $a\n
A a
puts $a
time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9

```
demo~~

##

~~Tcl, 288
```
lassign {set while puts format incr expr} S W P F I E
$S i 31
$W \$i<48 {$P [$F %10c%c [$I i] [$I i]]}
$S a ""
$W {[$I i]<71} {$S a $a[$F %c $i]}
$S a $a\n
$W \$i<92 {$S a $a[$F %c $i];$I i}
$P $a
$W \$i<128 {$P [$F %[$E (129-$i)/4]c%c $i [$I i]][$F %[$E $i/2-45]c%c [$I i] [$I i]]; $I i}

```~~

~~demo~~

---

~~tcl, 297 bytes (naïve attempt)
```
set i 31
while \$i<48 {puts [format %10c%c [incr i] [incr i]]}
set a ""
while {[incr i]<71} {set a $a[format %c $i]}
set a $a\n
while \$i<92 {set a $a[format %c $i];incr i}
puts $a
while \$i<128 {puts [format %[expr (129-$i)/4]c%c $i [incr i]][format %[expr $i/2-45]c%c [incr i] [incr i]]; incr i}

```
demo
~~
> 1 votes

# Answer
# Ruby, 91 bytes

```
->{(-11..8).map{|i|["%s"*21,"%#{9-i}s%s%#{i*2+1}s%s","%10s%s"][i/2<=>-1]}*$/%[*' '..?~,$/]}

```

**Ungolfed**

```
->{(-11..8).map{|i|            #For each line
  ["%s"*21,                    #If i/2==-1 make a format string of 21 %s
   "%#{9-i}s%s%#{i*2+1}s%s",   #If i/2>-1 make a format string %{9-i}s%s%{i*2+1}s%s
   "%10s%s"][i/2<=>-1]         #If i/2<-1 make a format string %10s%s
  }*$/%                        #Join the format strings with newlines $/ then use sprintf operator %
  [*' '..?~,$/]                #to replace the %s with *' '..'~' and a newline for last corner.
}

```
> 1 votes

# Answer
I missed an answer in C# so...

# C# (.NET Core), 175 174 bytes

```
_=>{var r="";for(int i=0,j,d=32,s=1;i<54;i++)for(j=0;j++<"*#4#4#4#4#4#4#4#4#+K)%1###/#%#-#'#+#)#)#+#'#-#%#/###1#"[i]-33;)r+=(char)(i%2<1?32:d++)+(s++%21<1?"\n":"");return r;}

```

Try it online!

* 1 byte saved thanks to Kevin Cruijssen!
> 1 votes

# Answer
# Stax, 33 bytes

```
¬♣╘╣Ye╗}Ω╩Ñ╬↓ï|§≈b↕£♠╨z▐₧3→ÿ≡Δ:╔♫

```

Run and debug it

Uses a similar idea to the 05AB1E answer.
> 1 votes

# Answer
# C (gcc), ~~119~~ 117 bytes

-2 bytes thanks to ceilingcat

```
f(c){for(c=0;c<95;c++)printf("%*c%s",c&1?:c<18?10:c<60?:c&2?c/2-30:24-c/4,c+32,c&c<18|c==38|c>58&!(c-63&3)?"\n":"");}

```

Try it online!
> 1 votes

# Answer
# Python 2.7, ~~194~~ 188 bytes

```
k,l,c,s,r=8,0,chr,' ',range;o=''.join(map(chr,r(32,127)))
for i in r(0,18,2):print s*9+o[i:i+2]
print o[18:39]+'\n'+o[39:60]
for i in r(60,95,4):print s*k+o[i:i+2]+s*l+o[i+2:i+4];k-=1;l+=2

```
> 0 votes

# Answer
# Jq 1.5, 180 bytes

```
foreach((range(9)|[9,2]),(range(2)|[0,21]),(range(9)|[8-.,2,.+.,2]))as$r({s:[range(32;127)]|implode};.r=$r|.p=""|until(.r==[];.p+=" "*.r[0]+.s[:.r[1]]|.s =.s[.r[1]:]|.r=.r[2:]);.p)

```

Expanded

```
foreach (                              # instruction sequence: [indent, count]
    (range(9)|[9,2]),                  # 9 rows of 2 characters indented 9 spaces
    (range(2)|[0,21]),                 # 2 rows of 21 characters
    (range(9)|[8-.,2,.+.,2])           # 9 rows of 4 characters with varying indent
) as $r (
    {s:[range(32;127)]|implode}        # state = ascii string
  ; .r = $r                            # current instruction
  | .p = ""                            # print string for this row
  | until(.r==[];                      # until current instruction is exhausted
        .p += " "*.r[0] + .s[:.r[1]]   # add to print string
      | .s = .s[.r[1]:]                # remove from state
      | .r = .r[2:]                    # remove from instruction
    )
  ; .p                                 # emit print string
 )

```

Try it online!
> 0 votes

# Answer
# Java 8, ~~176~~ ~~173~~ 172 bytes

```
v->{for(char i=54,j,d=32,s=1;i-->0;)for(j=0;j++<"#1###/#%#-#'#+#)#)#+#'#-#%#/###1%)K+#4#4#4#4#4#4#4#4#*".charAt(i)-33;)System.out.print((i%2<1?d++:32)+(s++%21<1?"\n":""));}

```

Port of *@Charlie*'s C# .NET answer, so make sure to upvote him.
-4 bytes thanks to *@ceilingcat*.

Try it online.
> 0 votes

# Answer
# Slashes (///), 324 bytes

```
          !
         "#
         $%
         &'
         ()
         *+
         ,-
         .\/
         01
23456789:;<=>?@ABCDEF
GHIJKLMNOPQRSTUVWXYZ[
        \\]^_
       `a  bc
      de    fg
     hi      jk
    lm        no
   pq          rs
  tu            vw
 xy              z{
|}                ~

```

The first (default) action in Slashes is 'print', so the string is printed. The `/` and `\` must be escaped by proceeding `\`s.
> 0 votes

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


title: Appended Numbers Game

text:
# Question
Title: Appended Numbers Game
# Appended Numbers Game

Write a function/program that takes 2 integer parameters *integer parameters or integer variables*, a start number, and a max iterations count. The code should perform the following game example to construct a new number, and repeat until the number is a single digit left. eg.

```
3 7 2 = (3 + 7) & (7 + 2) = 10 9
1 0 9 = (1 + 0) & (0 + 9) = 1 9
1 9 = (1 + 9) = 10
1 0 = (1 + 0) = 1

```

Basically, taking each individual digit and adding it to its neighbour, then appending the result of the next addition as well.

Max iteration count is to safeguard infinite loops, and when the max is hit, code should dump the last 5 number steps. The same output should occur when finishing by reaching a single digit. If less than 5 steps occurred, only output the valid numbers.

Output should appear like (`Step: Number`) including the last 5 steps of the finished or terminated steps:

`func(3541, 50)` would produce this exact output format:

```
6: 1411
7: 552
8: 107
9: 17
10: 8

```

`func(3541, 5)` would produce:

```
1: 895
2: 1714
3: 885
4: 1613
5: 774

```

The entire calculation being:

```
1: 895
2: 1714
3: 885
4: 1613
5: 774
6: 1411
7: 552
8: 107
9: 17
10: 8

```

If there are less than 5 steps, just print those steps taken.

Only use built-in libs, parameters can be from anywhere (whatever's easiest for your language of choice). No limit on maximum integer size, and if there are overflows, let it crash.

Given this isn't too difficult from a puzzle point of view, I will give until Sunday 25th, 8PM (UTC+8) for submissions to be considered for the accepted answer, at which point the shortest of any language will be the winner.

**EDIT:**

Congratulations to Howard, winning with a 48 GolfScript answer.

Special mention to 2nd place marinus with a 66 APL answer.

My personal favourite (being biased towards JavaScript) was core1024's answer.

# Answer
> 4 votes
### GolfScript, 48 46 characters

```
{.`n*[~]n\{:s++s}*;~}*].,,\]zip{': '*}%1>-5>n*

```

Thank you to Peter Taylor for a two-character improvement.

Expects both numbers on the stack. Try online.

Examples:

```
> 4 50

> 141 50
1: 55
2: 10
3: 1

> 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8

> 3541 5
1: 895
2: 1714
3: 885
4: 1613
5: 774

```

# Answer
> 10 votes
## APL (66)

```
{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}

```

The left argument is the maximum iteration count and the right argument is the start number.

Explanation:

* `∆←⍺{`...`}⍕⍵`: pass the left argument as a number and the right argument as a string to the function that calculates the list of numbers, and store it in :
    + `(1<⍴⍵)∧⍺>0:`: if the amount of digits is more than 1 and the amount of iterations left is more than `0`:
        - `⍎¨⍵`: evaluate each digit
        - `2+/`: sum each pair
        - `⍕¨`: format each number as a string
        - `∆←,/`: concatenate the strings and store in
        - `∆,(⍺-1)∇⊃∆`: return , followed by the result of applying this function to  with one less iteration allowed
    + `⋄⍬`: if not, return the empty list
* `∆,⍪⍳⍴∆`: pair each element of  with its index in
* `{`...`}/`: for each pair:
    + `(⍕⍵),': ',⍺`: return a string with the index, followed by `:`, followed by the number
* `↑¯5↑`: turn the list of strings into a matrix so they display on separate lines, and take the last 5 items

Test:

```
      5{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
1: 895
2: 1714
3: 885
4: 1613
5: 774
      50{↑¯5↑{(⍕⍵),': ',⍺}/∆,⍪⍳⍴∆←⍺{(1<⍴⍵)∧⍺>0:∆,(⍺-1)∇⊃∆←,/⍕¨2+/⍎¨⍵⋄⍬}⍕⍵}3541
6: 1411
7: 552
8: 107
9: 17
10: 8

```

# Answer
> 5 votes
## Mathematica, 172 characters

This is way too long, thanks to Mathematica's function names and ugly string handling (the actual "game" is only 76 of those characters), but here it is anyway:

```
""<>ToString/@(f=Flatten)@Take[Thread@{r=Range@Length[s=Rest@Cases[NestList[FromDigits[f@(d=IntegerDigits)[Tr/@Partition[d@#,2,1]]]&,n,m],i_/;i>0]],": "&/@r,s,"\n"&/@r},-5]

```

It expects the input number in variable `n` and the maximum number of iterations in `m`.

With less golf:

```
"" <> ToString /@
  (f = Flatten)@
   Take[
    Thread@{
      r = Range@Length[
         s = Rest@Cases[
            NestList[
             FromDigits[
               f@(d = IntegerDigits)[Tr /@ Partition[d@#, 2, 1]]] &,
             n,
             m
             ],
            i_ /; i > 0
            ]
         ],
      ": " & /@ r,
      s,
      "\n" & /@ r
      },
    -5
    ]

```

# Answer
> 5 votes
## Ruby, 106 characters

```
f=->n,m{s=0
$*<<"#{s}: #{n=n.to_s.gsub(/.\B/){eval$&+?++$'[0]}.chop}"until n.to_i<10||m<s+=1
puts$*.pop 5}

```

I'm not 100% clear on the input rules, but if I can take `n` as a string I can save 5 characters, and if I can use predefined variables and write a program instead of a function, I can save another 9.

Creates a function `f` which can be called as follows:

`f[3541, 6]`

```
2: 1714
3: 885
4: 1613
5: 774
6: 1411

```

`f[372, 50]`

```
1: 109
2: 19
3: 10
4: 1

```

`f[9999, 10]`

```
6: 99999999999
7: 18181818181818181818
8: 9999999999999999999
9: 181818181818181818181818181818181818
10: 99999999999999999999999999999999999

```

# Answer
> 4 votes
# J - 96 92 char

I'd first solved this assuming that all games terminated, and this came back to bite me in the ass during testing. Left argument is the number of steps, right argument is the starting position, which can be given as a number or a string.

```
([(-@(<.5<.#){.])(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".@(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":))

```

This is a little too golfed and convoluted to degolf satisfyingly, so I'll say this:

* `(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":)` This part runs the game for the specified number of steps. `2+/\` is responsible for adding each pair of digits, and `<@>:@[` in tandem with `^:` controls capturing the intermediate steps of the game.
* `(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".` This part formats all the results as `step: result`. `({.~,i.0:)` is making sure we don't take too many steps, `#\` is the step numbers, and the `(,': '&,)&":"0` bit adds the colon and space.
* `(-@(<.5<.#){.])` This portion cuts the relevant five-or-less steps out of the full list. `<.` means 'minimum of'.

It works, but if you start with a large enough number, the game's results quickly start growing in size, which makes J switch from integers to the imprecise doubles. Here are some examples:

```
   f =: ([(-@(<.5<.#){.])(#\(,': '&,)&":"0,)@}.@({.~,i.0:)@:".@(<@>:@[(' '-.~[:,@":2+/\"."0@]^:)":))
   5 f 3541
1: 895
2: 1714
3: 885
4: 1613
5: 774
   50 f 3541
6: 1411
7: 552
8: 107
9: 17
10: 8
   100 f 372
1: 109
2: 19
3: 10
4: 1

```

# Answer
> 3 votes
# Javascript 139 ~~144 150~~

```
function f(a,n){for(r=[a+=''];n--&&a[1];r.push(a=t))for(t='',i=0;a[++i];)t+=a[i-1]- -a[i];for(i=0;r[++i];)r[i+5]||console.log(i+': '+r[i])}

```

**Ungolfed**

```
function f(a,n)
{
  for (r=[a+='']; n-- && a[1]; r.push(a=t))
  {
    for (t = '', i = 0; a[++i]; )
    {
      t += a[i-1]- -a[i]; /* -char force conversion to number */
    }
  }
  for (i = 0; r[++i];) r[i+5]||console.log(i+': '+r[i])
}

```

# Answer
> 3 votes
## Perl, ~~86~~ 84

With newlines for readability:

```
$s+=$_=<>;
print+(map$s=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $s$/":(),/ /..$')[-5..-1]

```

**\+ Edit:** No excuse for not using `-n` command line switch, and then score is **82=81+1**:

```
$s+=$_;
print+(map$s=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $s$/":(),/ /..$')[-5..-1]

```

And, possible integer overflow being OK, it's **81=80+1**

```
$.=$_;
print+(map$.=~s/.(?=(.|))/~$1?$&+$1:''/eg>1?"$_: $.$/":(),/ /..$')[-5..-1]

```

# Answer
> 2 votes
## Javascript, 247 ~~278~~ ~~288~~ ~~307~~ Characters

```
 var t=[],q=1;function f(a,c){var x=a.toString().split(''),r='',p=parseInt;for(y in x){var i=p(y);if(i){r+=(p(x[i])+p(x[i-1])).toString();}}if(c!=0&&a>10){t.push(q+++':'+r+'\n');if(q>6){t.shift()}f(r,c-1);}console.log(t.join(',').replace(/,/g,''))}

```

**Formatted**

```
var t = [],
q = 1;

function f(a, c) {
 var x = a.toString().split(''),
    r = '',
    p = parseInt;
 for (y in x) {
    var i = p(y);
    if (i) {
        r += (p(x[i]) + p(x[i - 1])).toString();
    }
 }
 if (c != 0 && a > 10) {
    t.push(q+++':' + r + '\n');
    if (q > 6) {
        t.shift()
    }
    f(r, c - 1);
 }
 console.log(t.join(',').replace(/,/g, ''))
}

```

**Edit 1**: Removed ternary

**Edit 2**: Flipped logic for "skipping" 0 index

**Edit 3**: Reworked recursive calling.

Fiddle

# Answer
> 2 votes
# Bash + coreutils, 115 bytes

```
for((a=$1;++i<=$2&a>9;)){
a=`paste -d+ <(fold -1<<<${a%?}) <(fold -1<<<${a#?})|bc|tr -d '
'`
echo $i: $a
}|tail -n5

```

Output:

```
$ ./appended-number.sh 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8
$ ./appended-number.sh 3541 5
1: 895
2: 1714
3: 885
4: 1613
5: 774
$

```

# Answer
> 2 votes
# JavaScript (ECMAScript 6 Draft) - 134 Characters

```
f=(x,y,i=0,j=[])=>([m=''].map.call(m+x,(z,p,n)=>m+=p?+z+1*n[p-1]:m),j[i++]=i+': '+m,m.length>1&&i<y?f(m,y,i,j):j.slice(-5).join('\n'))

```

**Examples:**

```
f(372,5)
"1: 109
2: 19
3: 10
4: 1"

f(3541,50)
"6: 1411
7: 552
8: 107
9: 17
10: 8"

f(3541,5)
"1: 895
2: 1714
3: 885
4: 1613
5: 774"

```

# Answer
> 2 votes
# Husk, 32 bytes

```
↑_5Ṡz+(mo`+": "sŀ)mṁs↑htU¡oṁdẊ+d

```

Try it online!

Output format was cumbersome, but I had to answer this in Husk.

## Explanation

```
↑_5Ṡz+(mo`+": "sŀ)mṁs↑htU¡oṁdẊ+d
                               d convert first input to digits
                         ¡       and iterate:
                             Ẋ+  sum overlapping pairs
                           ṁd    convert to digits and flatten
                        U        truncate till fixed point
                      ht         remove first and last element
                     ↑           take second input number of values from that
                  mṁs            convert all the arrays to strings
   Ṡz+(          )               zip and concat that with:
                ŀ                range 1..length(seq)
       mo`+": "s                 convert each to string, append a colon
↑_5                              take the last 5 elements

```

# Answer
> 1 votes
# Java 524 405 365 chars \[414 bytes\]

Golfed version: `class A{static int n=0;List<String> s=new ArrayList<>();void c(int b,int r){String d=b+"";if(r==0||b <= 9){int m=s.size();for(int i= m>=5?m-5:0;i<m;i++)System.out.println(s.get(i));return;}String l="";for(int i=0;i<d.length()-1;i++)l+=d.charAt(i)+d.charAt(i+1)-96;s.add(++n+":"+l);c(Integer.valueOf(l),--r);}public static void main(String[] a){new A().c(3541,50);}}`

Readable version:

```
class AddDigits {
static int n = 0;
List<String> steps = new ArrayList<>();

void count(int num, int count) {
    String digits = num + "";
    if (count == 0 || num <= 9) {
        int stepsSize = steps.size();
        for (int i = stepsSize >= 5 ? stepsSize - 5 : 0; i < stepsSize; i++) {
            System.out.println(steps.get(i));
        }
        return;
    }
    String line = "";
    for (int i = 0; i < digits.length() - 1; i++) {
        line += digits.charAt(i) + digits.charAt(i + 1) - 96;
    }
    steps.add(++n + ":" + line);
    count(Integer.valueOf(line), --count);
}

public static void main(String[] args) {
    new AddDigits().count(3541, 50);
}
}

```

# Answer
> 1 votes
# Javascript, 182 bytes

```
function f(I,T){s=[],x=1;for(;;){d=(""+I).split("");l=d.length;if(l==1||x>T)break;for(I="",i=1;i<l;)I+=+d[i-1]+ +d[i++];s.push(x+++": "+I)}s=s.slice(-5);for(i in s)console.log(s[i])}

```

# Answer
> 1 votes
# Perl, ~~166~~ ~~147~~ ~~138~~ 129 bytes

```
<>=~/ /;for$i(1..$'){@n=split'',$s||$`;$s=join'',map{$n[$_]+$n[$_+1]}0..@n-2;@o=(@o,"$i: $s");$s<10&&last}print join$/,@o[-5..-1]

```

Ungolfed:

```
<> =~ / /;
for $i (1..$') {
    @n = split'', $s||$`;
    $s = join'',map {$n[$_]+$n[$_+1]} 0..@n-2;
    @o = (@o, "$i: $s");
    $s<10 && last
}
print join$/,@o[-5..-1]

```

I hope it's alright that it prints some extra empty lines if the whole thing takes less than 5 steps.

# Answer
> 1 votes
# Java, 341 chars ~~371 chars~~

```
 class a{public static void main(String[] a){p(3541,50);}static void p(int n,int k){Queue<String>q=new LinkedList();int c=0;while(n>9&&c<k){c++;String r="";String p=""+n;for(int i=0;i<p.length()-1;i++)r+=((p.charAt(i)+p.charAt(i+1)-96));n=Integer.parseInt(r);q.add(c+": "+n);if(q.size()>5)q.remove();}for(String s:q){System.out.println(s);}}}

```

Formatted:

```
class a {
public static void main(String[] a) {
    p(3541, 50);
}

static void p(int n, int k) {
    Queue<String> q = new LinkedList();
    int c = 0;
    while (n > 9 && c < k) {
        c++;
        String r = "";
        String p = "" + n;
        for (int i = 0; i < p.length() - 1; i++)
            r += ((p.charAt(i) + p.charAt(i + 1) - 96));
        n = Integer.parseInt(r);
        q.add(c + ": " + n);
        if (q.size() > 5)
            q.remove();
    }
    for (String s : q) {
        System.out.println(s);
    }
}}

```

Thanks to user902383 i was able to reduce the code by 30 chars, by not splitting the String into an Array an using -96 instead of "Integer.valueOf()

# Answer
> 1 votes
## JavaScript 133 bytes

```
function f(n,g){for(c=r=[];g--;(n=s)&&(r[c++]=c+': '+s))for(i=s='',n+=s;n[++i];s+=n[i]-+-n[i-1]);console.log(r.slice(-5).join('\n'))}

```

**Ungolfed:**

```
function sums(num, guard) {
    for(count = res = [];guard--;(num = sum) && (res[count++] = count + ': ' + sum))
        for(i = sum = '',num += sum;num[++i];sum += num[i] -+- num[i-1]);
    console.log(res.slice(-5).join('\n'))
}

```

# Answer
> 0 votes
# Dart, ~~602~~ 588 bytes

Dart is probably one of the worst languages to do this in... I'll need to find a better way to do this.

Anyway, Here's my entry:

Input through console

```
var steps={};void main(a){c(a[0],int.parse(a[1]));}void c(inp,m){int i=0;int n=int.parse(inp);while(++i<=m){n=addUp(n.toString());steps[i]=n;if(n<10)break;}printSteps();}int addUp(n){var ns=[];for(int i=0;i<n.length;i++){try{ns.add(n[i]+n[i+1]);}catch(e){}}return addNumbers(ns);}int addNumbers(ns){var it=ns.iterator;var s="";while(it.moveNext()){int i=0;for(var t in it.current.split('')){i+=int.parse(t);}s=s+i.toString();}return int.parse(s);}void printSteps(){int l=steps.length;for(int i=getStart(l);i<=l;i++){print("${i}:\t${steps[i]}");}}int getStart(l){int m=l-4;return m>0?m:1;}

```

And the ungolfed, slightly unminified version:

```
var steps = {};

void main(a)
{
    c(a[0], int.parse(a[1]));
}

void c(String input, int max)
{
    int i = 0;
    int n = int.parse(input);

    while(++i <= max)
    {
        n = addUp(n.toString());

        steps[i] = n;

        if(n < 10)
            break;
    }

    printSteps();
}

int addUp(String n)
{
    List numbers = [];

    for(int i = 0; i < n.length; i++)
    {
        try
        {
            numbers.add(n[i] + n[i + 1]);
        }
        catch(e){}
    }

    return addNumbers(numbers);
}

int addNumbers(List numbers)
{
    Iterator it = numbers.iterator;

    String s = "";

    while(it.moveNext())
    {
        int i = 0;
        for(String s in it.current.split(''))
        {
            i += int.parse(s);
        }

        s = s + i.toString();
    }

    return int.parse(s);
}

void printSteps()
{
    int l = steps.length;

    for(int i = getStart(l); i <= l; i++)
    {
        print("${i}:\t${steps[i]}");
    }
}

int getStart(int l)
{
    int m = l - 4;
    return m > 0 ? m : 1;
}

```

# Answer
> 0 votes
# C# - 309 330 320 306 Bytes

## Golfed Version:

```
private static void F(int aN,int aM){var s=new List<string>();var n=aN.ToString();for(int i=1;i<=aM;i++){int z=n.Length;if(z==1){break;}var a=n;n="";for(int j=0;j<z-1;j++){int r=a[j]-'0'+a[j + 1]-'0';n=n+r;}s.Add(i+": "+n);}int l=s.Count;int p=5;if(l<5){p=l;}for(int k=l-p;k<l;k++){Debug.WriteLine(s[k]);}}

```

Usage: F(3541,50);

## Ungolfed version for readability:

```
private static void AppendNumbers(int aNum, int aMaxSteps)
    {
        var results = new List<string>();
        var numString = aNum.ToString();
        for (int i = 1; i <= aMaxSteps; i++)
        {
            int stringLength = numString.Length;
            if (stringLength == 1)
            {
                break;
            }
            var a = numString;
            numString = "";
            for (int j = 0; j < stringLength-1; j++)
            {
                int additionResult = a[j]-'0' + (a[j + 1]-'0');
                numString = numString + additionResult;
            }
            results.Add(i+": "+ numString);
        }
        int numberOfResults = results.Count;
        int p = 5;
        if (numberOfResults < 5)
        {
            p = numberOfResults;
        }
        for (int k = numberOfResults - p; k < numberOfResults; k++)
        {
            Debug.WriteLine(results[k]);
        }
    }

```

Suggestions for improvement are always welcome! ;)

**Edit:** Removed String.Empty and replaced it with "" to save 10 Bytes.

**Edit 2:** Thanks to malik for the tipp with the strings!

# Answer
> 0 votes
**PERL 135 129/125 125/121 bytes**

It has the same bug as Tal's answer

```
sub c{($e,$l)=@_;print join"\n",(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2};++$c.": ".($e=$s)}1..$l)[-5..-1]}

```

Edit 129 bytes as a function:

```
sub c{($e,$l)=@_;print join$/,(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s)}1..$l)[-5..-1]}

```

125 bytes as a function:

```
sub c{($e,$l)=@_;print+(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s).$/}1..$l)[-5..-1]}

```

125 bytes as a console script (without the hashbang):

```
($e,$l)=@ARGV;print join$/,(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s)}1..$l)[-5..-1]

```

121 bytes as a console script (without the hashbang):

```
($e,$l)=@ARGV;print+(grep/\d$/,map{$s="";{$e=~/(.)(.)/;redo if""ne($e=$2.$')and$s.=$1+$2}"$_: ".($e=$s).$/}1..$l)[-5..-1]

```

Expanded:

```
sub c
{
    ($e, $l) = @_;
    print +(grep /\d$/, map {
        $s="";
        {
            $e =~ /(.)(.)/;
            redo if "" ne ($e = $2.$') and $s .= $1 + $2
        }
        "$_: ".($e = $s).$/
    } 1 .. $l)[-5 .. -1]
}

```

Test with `c(372,4);`:

```
[blank line]
1: 109
2: 19
3: 10
4: 1

```

Test with `c(3541,50);`:

```
6: 1411
7: 552
8: 107
9: 17
10: 8

```

# Answer
> 0 votes
## Python 2.7, ~~174~~ ~~173~~ 158 characters

Using a lot of strings to do the task.

```
x,n=raw_input().split()
o,i=[],0
while int(n)>i<o>9<x:x="".join(`sum(map(int,x[j:j+2]))`for j in range(len(x)-1));i+=1;o+=[`i`+": "+x]
print"\n".join(o[-5:])

```

## Python 2.7, 155 characters

Version defining a function

```
def a(x,n):
 o,i,x=[],0,`x`
 while n>i<o>9<int(x):x="".join(`sum(map(int,x[j:j+2]))`for j in range(len(x)-1));i+=1;o+=[`i`+": "+x]
 print"\n".join(o[-5:])

```

**Slightly ungolfed version:**

```
x,n=map(int,raw_input().split())
o,i=[],1
while i<=n and x>9:
  x=int("".join(`sum(map(int,`x`[j:j+2]))` for j in range(len(`x`)-1)))
  o.append("%d: %d"%(i,x))
  i+=1
print "\n".join(o[-5:])

```

# Answer
> 0 votes
# Cobra - 363

A rather depressing result... but hey, I still beat Java.

It *should* be immune to integer overflows for practical test cases.

```
class P
    cue init(a,b)
        base.init
        l=[]
        c=.p(a.toString)
        for x in b
            l.add("")
            y=l.count
            for i in c.count-1,l[y-1]+=(c[i]+c[i+1]).toString
            if l.last.length<2,break
            c=.p(l.last)
        z=if(y>5,y-5,0)
        for x in l[z:y],print"[z+=1]:",x
    def p(n) as List<of int>
        c=List<of int>()
        for i in n,c.add(int.parse(i.toString))
        return c

```

# Answer
> 0 votes
## Groovy - 191 182 chars

Based on Thomas Rüping's solution, ported to Groovy 2.2.1:

```
f={it as int};n=args[0];s=f args[1];q=[];x=0;while(f(n)>9&&x<s){x++;d=n.split("");n="";for(i in 1..d.length-2)n+=f(d[i])+f(d[i+1]);q << "$x: $n"};q[-1..5].reverse().each{println it}

```

Execution and output:

```
bash$ groovy Numbers.groovy 3541 50
6: 1411
7: 552
8: 107
9: 17
10: 8

```

Ungolfed:

```
f = {it as int}
n = args[0]
s = f args[1]

queue = []
stepCounter = 0

while (f(n) > 9 && stepCounter < s) {
    stepCounter++
    digits=n.split("")
    n=""
    for(i in 1..digits.length-2) {
        n += f(digits[i]) + f(digits[i+1])
    }
    queue << "$stepCounter: $n"
}

queue[-1..5].reverse().each{ println it }

```

# Answer
> 0 votes
## C# - 269

```
void F(int x,int y){var o=new List<string>();var i=x+"";for(int n=1;n<y&&i.Length>1;n++){var s="";for(int z=0;z<i.Length;z++){int a=i[z]-'0';var t=a+(z+1!=i.Length?i[z+1]-'0':-a);if(t!=0)s+=t;}i=s;o.Add(n+": "+i);}foreach(var p in o.Skip(o.Count-5))Debug.WriteLine(p);}

```

Readable:

```
void F(int x,int y){
    var o=new List<string>();
    var i=x+"";
    for(int n=1;n<y&&i.Length>1;n++)
    {
        var s="";
        for(int z=0;z<i.Length;z++){
            int a=i[z]-'0';
            var t=a+(z+1!=i.Length?i[z+1]-'0':-a);
            if(t!=0)
                s+=t;
        }
        i=s;
        o.Add(n+": "+i);
    }
    //Output
    foreach(var p in o.Skip(o.Count-5))
        Debug.WriteLine(p);
}

```

Usage:

```
F(3541, 50)

```

Output:

```
6: 1411
7: 552
8: 107
9: 17
10: 8

```

# Answer
> 0 votes
# Haskell, 154

```
s=show
z=zipWith
m#n=concat.z(\a b->s a++": "++b++"\n")[1..].(\x->drop(length x-n)x).takeWhile(/="").iterate((\x->z(+)x(tail x)>>=s).map(\x->read[x]))$s m

```

example usage:

```
λ> 3541#5
"1: 1411\n2: 552\n3: 107\n4: 17\n5: 8\n"

```

To make it more readable, use `putStr`:

```
λ> putStr $ 3541#5
1: 1411
2: 552
3: 107
4: 17
5: 8

```

# Answer
> 0 votes
\**C ~~186~~ ~~179~~174 \**

```
f(int a,int z){for(int c,d,i,j=0,m[5];m[j++%5]=a,j<=z&&a/10;a=c)for(c=0,i=1;a/10;d=a%10+(a/=10)%10,c+=d*i,i*=d<10?10:100);for(i=j<5?0:j-5;i<j;printf("%d: %d\n",i,m[i++%5]));}

```

Slightly less golfed (mini-golfed?)

```
f(int a, int z)
{

for(int c,d,i,j=0,m[5];m[j++%5]=a,j<=z&&a/10;a=c)
    for(c=0,i=1;a/10;d=a%10+(a/=10)%10,c+=d*i,i*=d<10?10:100);

    for(i=j<5?0:j-5;i<j;printf("%d: %d\n",i,m[i++%5]));

}

```

Just allocate enough memory to store five results cyclically. The outer loop keeps going until we hit the limit or reach a single digit. The inner loop adds the last digit of the number to last digit of 1/10 of the number and adds this, multiplied by the relevant power of 10 to the result. Divide the number you first though of by 10 and repeat to get the total. Then print out up to the last five results.

Next challenge is to see if I can shave off enough to beat some scripting languages at golf.

Edit: Now compiles with warning but five characters shaved off by removing "void " declaration

---
Tags: code-golf
---


title: Simple markdown rendering

text:
# Question
Title: Simple markdown rendering
There are several ways to create headers on posts on the Stack Exchange network. The format that's most commonly1 used on PPCG seems to be:

```
# Level one header
## Level two header
### Level three header

```

Note the space after the hash marks. Also, note that trailing hash marks are not included.

## Challenge:

Take a (possibly multiline) string as input, and output the string on the following format:

* If the header is level 1, then output each letter 4-by-4 times
* If the header is level 2, then output each letter 3-by-3 times
* If the header is level 3, then output each letter 2-by-2 times
* If a line is not a header then output it as it is.

To illustrate:

```
--- Level 1 ---
# Hello
--- Output---
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo

--- Level 2 ---
## A B C def
--- Output ---
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff

--- Level 3 ---
### PPCG!
--- Output---
PPPPCCGG!!
PPPPCCGG!!

```

Simple as that!

---

### Rules:

* You must support input over multiple lines. Using `\n` etc. for newlines is OK.
    + There won't be lines containing only a `#` followed by a single space
* The output must be presented over multiple lines. You may not output `\n` instead of literal newlines.
    + Trailing spaces and newlines are OK.

---

### Test cases:

Input and output are separated by a line of `...`.

```
# This is a text
with two different
### headers!
........................................................
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
TTTThhhhiiiissss    iiiissss    aaaa    tttteeeexxxxtttt
with two different
hheeaaddeerrss!!
hheeaaddeerrss!!

```

---

```
This input has
## trailing hash marks ##
#and a hash mark without a space after it.
........................................................
This input has
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
tttrrraaaiiillliiinnnggg   hhhaaassshhh   mmmaaarrrkkksss   ######
#and hash marks without a space after it.

```

---

```
# This ## is ### strange
#### ###
........................................................
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
TTTThhhhiiiissss    ########    iiiissss    ############    ssssttttrrrraaaannnnggggeeee
#### ###

```

---

```
Multiple

### newlines! #
:)
........................................................
Multiple

nneewwlliinneess!!  ##
nneewwlliinneess!!  ##
:)

```

---

```
Line with only a hash mark:
#
### ^ Like that!
........................................................
Line with only a hash mark:
#
^^  LLiikkee  tthhaatt!!
^^  LLiikkee  tthhaatt!!

```

1: I haven't really checked, but I *think* it's true.

# Answer
> 7 votes
# Stacked, ~~51~~ 50 bytes

*Saved 1 byte thanks to @RickHitchcock - golfed regex*

```
['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]

```

Try it online!

Anonymous function that takes input from the stack and leaves it on the stack.

## Explanation

```
['^(##?#?) (.+)'[\#'5\-@k CS k*k rep LF#`]3/mrepl]
[                                            mrepl]   perform multiline replacement
 '^(##?#?) (.+)'                                     regex matching headers
                [                        ]3/         on each match:
                 \#'                                   count number of hashes
                    5\-                                5 - (^)
                       @k                              set k to number of repetitions
                          CS                           convert the header to a char string
                             k*                        repeat each char `k` times
                               k rep                   repeat said string `k` times
                                     LF#`              join by linefeeds

```

# Answer
> 3 votes
# JavaScript (ES6), ~~111~~ 105 bytes

*Saved 6 bytes thanks to @Shaggy*

```
s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>`
${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim())

```

Matches 1-3 hashes at the beginning of the string or preceded by a new line, then repeats each character in the match along with the match itself, based on the length of the hashes.

**Test Cases:**

```
let f=

s=>s.replace(/^(##?#?) (.+)/gm,(_,a,b)=>`
${b.replace(/./g,e=>e.repeat(l=5-a.length))}`.repeat(l).trim())

console.log(f('# This is a text\nwith two different\n### headers!'));
console.log('______________________________________________');
console.log(f('This input has\n## trailing hash marks ##\n#and a hash mark without a space after it.'));
console.log('______________________________________________');
console.log(f('# This ## is ### strange\n#### ###'));
console.log('______________________________________________');
console.log(f('Multiple\n\n\n### newlines! # \n:)'));
console.log('______________________________________________');
console.log(f('Line with only a hash mark:\n#\n### ^ Like that!'));
```

# Answer
> 2 votes
# Retina, ~~125~~ 104 bytes

```
m(`(?<=^# .*).
$0$0$0$0
(?<=^## .*).
$0$0$0
(?<=^### .*).
$0$0
^#
$%'¶$%'¶$%'¶
^##
$%'¶$%'¶
^###
$%'¶

```

**Try it online**

*Saved 21 bytes thanks to Neil.*

# Answer
> 2 votes
# MATL, ~~43~~ ~~42~~ 40 bytes

*1 byte removed thanks to Rick Hitchcock!*

```
`j[]y'^##?#? 'XXgn:(2M4:QP&mt~+t&Y"0YcDT

```

This outputs a trailing space in each line (allowed by the challenge), and exits with an error (allowed by default) after producing the ouput.

**Try it online!**

### Explanation

```
`            % Do...while loop
  j          %   Input a line as unevaluated string
  []         %   Push empty array
  y          %   Duplicate from below: push input line again
  '^##?#? '  %   Push string for regexp pattern
  XX         %   Regexp. Returns cell array with the matched substrings
  g          %   Get cell array contents: a string, possibly empty
  n          %   Length, say k. This is the title level plus 1, or 0 if no title
  :(         %   Assign the empty array to the first k entries in the input line
             %   This removing those entries from the input
  2M         %   Push k again
  4:QP       %   [1 2 3 4], add 1 , flip: pushes [5 4 3 2]
  &m         %   Push index of k in that array, or 0 if not present. This gives
             %   4 for k=2 (title level 1), 3 for k=3 (tile level 2), 2 for k=2
             %   (title level 1), and 0 for k=0 (no title). The entry 5 in the
             %   array is only used as placeholder to get the desired result.
  t~+        %   Duplicate, negate, add. This transforms 0 into 1
  t&Y"       %   Repeat each character that many times in the two dimensions
  0Yc        %   Postpend a column of char 0 (displayed as space). This is
             %   needed in case the input line was empty, as MATL doesn't
             %   display empty lines
  D          %   Display now. This is needed because the program will end with
             %   an error, and so implicit display won't apply
  T          %   True. This is used as loop condition, to make the loop infinite
             % End (implicit)

```

# Answer
> 2 votes
# Perl 5, 47 +1 (-p) bytes

```
s/^##?#? //;$.=6-("@+"||5);$_=s/./$&x$./ger x$.

```

try it online

# Answer
> 1 votes
# Charcoal, 46 bytes

```
ＦＮ«Ｓι≔⊕⌕Ｅ³…⁺×#κι⁴### θＦ⎇θ✂ι⁻⁵θＬι¹ι«Ｇ↓→↑⊕θκ→»Ｄ⎚

```

Try it online! Link is to verbose version of code. Charcoal doesn't really do string array input, so I've had to add the array length as an input. Explanation:

```
ＦＮ«Ｓι

```

Loop over the appropriate number of input strings.

```
≔⊕⌕Ｅ³…⁺×#κι⁴### θ

```

Create an array of strings by taking the input and prefixing up to 2 #s, then truncating to length 4, then try to find `###` in the array, then convert to 1-indexing. This results in a number which is one less than the letter zoom.

```
Ｆ⎇θ✂ι⁻⁵θＬι¹ι«

```

If the letter zoom is 1 then loop over the entire string otherwise loop over the appropriate suffix (which is unreasonably hard to extract in Charcoal).

```
Ｇ↓→↑⊕θκ→

```

Draw a polygon filled with the letter ending at the top right corner, and then move right ready for the next letter.

```
»Ｄ⎚

```

Print the output and reset ready for the next input string.

# Answer
> 1 votes
# SOGL V0.12, ~~31~~ 28 bytes

```
¶Θ{■^##?#? øβlF⁄κ6κ5%:GI*∑∙P

```

Try it Here! \- extra code added because the code is a function and takes input on stack (SOGL can't take multiline input otherwise :/) - `inputs.value”` \- push that string,  \- evaluate as JS, `F` \- call that function

Explanation:

```
¶Θ                            split on newlines
  {                           for each item
   ■^##?#?                      push "^##?#? "
           øβ                   replace that as regex with nothing
             l                  get the new strings length
              F⁄                get the original strings length
                κ               and subtract from the original length the new strings length
                 6κ             from 6 subtract that
                   5%           and modulo that by 5 - `6κ5%` together transforms 0;2;3;4 - the match length to 1;4;3;2 - the size
                     :          duplicate that number
                      G         and get the modified string ontop
                       I        rotate it clockwise - e.g. "hello" -> [["h"],["e"],["l"],["l"],["o"]]
                        *       multiply horizontally by one copy of the size numbers - e.g. 2: [["hh"],["ee"],["ll"],["ll"],["oo"]]
                         ∑      join that array together - "hheelllloo"
                          ∙     and multiply vertiaclly by the other copy of the size number: ["hheelllloo","hheelllloo"]
                           P    print, implicitly joining by newlines

```

# Answer
> 0 votes
# Proton, 130 bytes

```
x=>for l:x.split("\n"){L=l.find(" ")print(L>3or L+len(l.lstrip("\#"))-len(l)?l:"\n".join(["".join(c*(5-L)for c:l[L+1to])]*(5-L)))}

```

Try it online!

# Answer
> 0 votes
# Python 3, 147 bytes

```
def f(x):
	for l in x.split("\n"):L=l.find(" ");print(L>3or L+len(l.lstrip("#"))-len(l)and l or"\n".join(["".join(c*(5-L)for c in l[L+1:])]*(5-L)))

```

Try it online!

-1 byte thanks to Mr. Xcoder

# Answer
> 0 votes
# Python 3, 131 bytes

```
from re import*
print(sub("^(#+) (.*?)$",lambda x:((sub('(.)',r'\1'*(5-len(x[1])),x[2])+'\n')*(5-len(x[1])))[:-1],input(),flags=M))

```

Try it online!

I used Python 3 in order to use `[]` with regex.

# Answer
> 0 votes
# C# (.NET Core), 268 + 18 bytes

```
n=>{var r="";for(int l=0,c;l<n.Length;l++){var m=n[l];var s=m.Split(' ');var y=s[0];if(!y.All(x=>x==35)|y.Length>3|s.Length<2)r+=m+'\n';else for(int i=0,k=y.Length;i<5-k;i++){for(c=1;c<m.Length-k;)r+=new string(m.Substring(k,m.Length-k)[c++],5-k);r+='\n';}}return r;};

```

Try it online!

# Answer
> 0 votes
# JavaScript, 112 bytes

```
x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join`
`)(5-n.length))

```

```
f=

x=>x.replace(/^(##?#?) (.*)/mg,(_,n,w)=>(t=>Array(t).fill(w.replace(/./g,c=>c.repeat(t))).join`
`)(5-n.length))
```

```
<textarea id=i style=display:block oninput=o.value=f(i.value)></textarea>
<output id=o style=display:block;white-space:pre></output>
```

# Answer
> 0 votes
# PHP, 122+1 bytes

```
for($y=$z=" "==$s[$i=strspn($s=$argn,"#")]&&$i?5-$i++:1+$i=0;$y--;print"
")for($k=$i;~$c=$s[$k++];)echo str_pad($c,$z,$c);

```

Run as pipe with `-nR` (will work on one input line after another) or try it online.

# Answer
> 0 votes
# , 55 bytes

```
([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]

```

I don't know how to make TIO work with J regex, so I can't provide a working link.

Here's how to test it in the J interpreter (tested with J804)

```
   f=.([:{:@,'^##?#? 'rxmatch])((1 1 4 3 2{~[)([:|:[$"0#)}.)]
   txt=.'# Hello'; '## A B C def'; '### PPCG!'; '#and a hash mark without a space after it.'; '##### ###'
   ; f each txt

HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
HHHHeeeelllllllloooo
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff
AAA   BBB   CCC   dddeeefff
PPPPCCGG!!
PPPPCCGG!!
#and a hash mark without a space after it.
##### ###

```

I simulate a multiline string through a list of boxed strings.

# Answer
> 0 votes
# Python 2, ~~126~~ ~~124~~ 117 bytes

```
while 1:l=raw_input();i=l.find(' ');v=5-i*(l[:i]in'###');exec"print[l,''.join(c*v for c in l[i+1:])][v<5];"*(v>4or v)

```

Try it online!

or

```
while 1:l=raw_input();i=l.find(' ');t=''<l[:i]in'###';exec"print[l,''.join(c*(5-i)for c in l[i+1:])][t];"*(t<1or 5-i)

```

Try it online!

# Answer
> 0 votes
# C# 4.5 158 Bytes

Where i is the input in the form of a string.

```
int l,m,t,s=0;while(i[s]=='#'){s++;};t=s>0?4-s+1:1;for(l=0;l<t;l++){foreach(char c in i.Skip(s>0?s+1:0))for(m=0;m<t;m++)Console.Write(c);Console.WriteLine();}

```

# Answer
> 0 votes
# Stax, 27 bytes

```
é!?q╚<╙≈╣íå▒{¼Φ8ôƒ¡m↨;-◘-u♥

```

Run and debug it

This was fun.

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


title: Find the XOR Primes

text:
# Question
Title: Find the XOR Primes
In this challenge posed by xnor, we were asked to implement XOR multiplication. In this challenge the goal is to find the first `n` XOR primes. XOR primes are very similar to regular primes as you can see by the following definitions:

**Definition of Prime Number:** A positive number greater than 1 which cannot be formed through multiplication of two numbers except through the multiplication of 1 and itself.

**Definition of XOR Prime:** A positive number greater than 1 which cannot be formed through XOR multiplication of two numbers except through the XOR multiplication of 1 and itself. Note that the XOR primes compose oeis sequence A014580.

XOR multiplication is defined as binary long multiplication without carrying. You can find more information about XOR multiplication in xnor's challenge.

## Input:

An integer `n`.

## Output:

The first `n` XOR primes.

### Here are the XOR primes under 500:

```
2 3 7 11 13 19 25 31 37 41 47 55 59 61 67 73 87 91 97 103 109 115 117 131 137 143 145 157 167 171 185 191 193 203 211 213 229 239 241 247 253 283 285 299 301 313 319 333 351 355 357 361 369 375 379 391 395 397 415 419 425 433 445 451 463 471 477 487 499

```

# Answer
# Pyth, 26 bytes

```
.fq2/muxyG*Hhdjed2 0^SZ2ZQ

```

Demonstration

To test whether a number is a XOR-prime, we generate the complete multiplication table up to that number using the algorithm from here, and then count how many times that number appears. If it's exactly 2, the number is prime.

Then, `.f` returns the first n primes.
> 5 votes

# Answer
## Ceylon, 166 bytes

Of course this can't compete with Pyth & Co ...

```
{Integer*}p(Integer n)=>loop(2)(1.plus).filter((m)=>{for(i in 2:m-2)for(j in 2:m-2)if(m==[for(k in 0:64)if(j.get(k))i*2^k].fold(0)((y,z)=>y.xor(z)))i}.empty).take(n);

```

Formatted:

```
{Integer*} p(Integer n) =>
        loop(2)(1.plus).filter((m) => {
            for (i in 2 : m-2)
                for (j in 2 : m-2)
                    if (m == [
                            for (k in 0:64)
                                if (j.get(k))
                                    i * 2^k
                        ].fold(0)((y, z) => y.xor(z))) i
        }.empty).take(n);

```

This creates an infinite iterable of integers (starting with 2), filters it by checking if a number is an XOR-prime, and takes the first `n` elements of that.

This filtering works by looping over all elements from 2 to m-1 (which are m-2 ones), and checking each pair if the xor-product give `m`. If the iterable created by that is empty, `m` is an xor-prime, and therefore included.

The xor-product itself is calculated using the same algorithm (and almost the same code) as in my answer for the XOR product calculation.
> 2 votes

# Answer
# Mathematica, ~~100~~ 99 bytes

As noted by xnor, XOR multiplication is just multiplication in the polynomial ring \\$\mathbb{F}\_2\[x\]\\$.

```
For[p=i=0,i<#,If[IrreduciblePolynomialQ[++p~IntegerDigits~2~FromDigits~x,Modulus->2],Print@p;i++]]&

```
> 2 votes

# Answer
# Pari/GP, 74 bytes

Saved 4 bytes thanks to Charles.

As noted by xnor, XOR multiplication is just multiplication in the polynomial ring \\$\mathbb{F}\_2\[x\]\\$.

```
n->p=0;while(n,if(polisirreducible(Mod(Pol(binary(p++)),2)),print(p);n--))

```

Try it online!

Basically the same as my Mathematica answer, but PARI/GP has shorter function names.
> 2 votes

# Answer
# Julia, 116 bytes

```
f(a,b)=b%2*a$(b>0&&f(2a,b÷2))
n->(A=[i=2];while endof(A)<n i+=1;i∈[f(a,b)for a=2:i-1,b=2:i-1]||push!(A,i)end;A[n])

```

The primary function is the anonymous function on the second line. It calls a helper function `f` (which is incidentally my submission for xnor's challenge).

Ungolfed:

```
function xor_mult(a::Integer, b::Integer)
    return b % 2 * a $ (b > 0 && f(2a, b÷2))
end

function xor_prime(n::Integer)
    # Initialize an array to hold the generated XOR primes as well as
    # an index at which to start the search
    A = [i = 2]

    # Loop while we've generated fewer than n XOR primes
    while endof(A) < n
        # Increment the prime candidate
        i += 1

        # If the number does not appear in the XOR multiplication
        # table of all numbers from 2 to n-1, it's an XOR prime
        i ∈ [xor_mult(a, b) for a in 2:i-1, b in 2:i-1] || push!(A, i)
    end

    # Return the nth XOR prime
    return A[n]
end

```
> 1 votes

# Answer
# Jelly, 21 bytes

```
BJ’2*U×B{×^/ðþFċ=2
ÇƇ

```

Try it online!

## How it works

```
ÇƇ - Main link. Takes an integer n on the left
 Ƈ - Yield the range [1, 2, ..., n] and filter on:
Ç  -   The helper function

BJ’2*U×B{×^/ðþFċ=2 - Help function. Takes an integer k on the left
            ð      - Define a dyadic link f(i, j):
B                  -   Convert i to binary
 J                 -   Replace with their indices
  ’                -   Decrement each
   2*              -   2 to the power of each
     U             -   Reverse
       B{          -   Yield i in binary
      ×            -   Multiply the powers by the bits
         ×         -   Multiply by j
          ^/       -   Reduce by XOR
             þ     - Yield the range [1, 2, ..., k] and create a multiplication table using f(i, j)
              F    - Flatten
               ċ   - Count the occurrences of k
                =2 - Does this equal 2?

```
> 0 votes

# Answer
# , 138 bytes

```
function(n,f=function(x,y)`if`(y,bitwXor(x*y%%2,2*f(x,y%/%2)),0)){while(n)if(sum(outer(1:(T=T+1),1:T,Vectorize(f))==T)<3)F[1+(n=n-1)]=T;F}

```

Try it online!

Outputs the first `n` XOR primes in reverse order.

Sequentially tests each integer `T` (starting at 2) for XOR primality by checking whether the results of all values of 1..`T` XOR multiplied (using helper function `f`) by 1..`T` contain only 2 instances of `T`.
> 0 votes

---
Tags: code-golf, number, primes, bitwise, abstract-algebra
---