title: A Geometrical Challenge

text:
# Question
Title: A Geometrical Challenge
Everybody loves geometry. So why don't we try and code golf it? This challenge involves taking in letters and numbers and making shapes depending on it.

# The Input

The input will be in the form of `(shapeIdentifier)(size)(inverter)`.

*But what are shapeIdentifier, size, and inverter?*

The shape identifier is the identifier for the type of shape you will be making with `*`s. The following are the shape identifiers:

* `s` \- Square
* `t` \- Triangle

The size will be between `1-20`, and it is the size of the figure.

The inverter is whether or not the shape will be upside down, which is denoted by a `+` or a `-`. Do note: `s3-` == (equals) `s3+` because squares are symmetric. However, `t5-` != (does not equal) `t5+`.

Trailing whitespace is okay in the output but leading whitespace is not.

# Output Examples

```
Input: s3+
Output:
***
***
***

Input: t5+

Output:
  *
 ***
*****

Input: t3-
Output:
***
 *

```

# Special Notes

The triangle input will always be an odd number, so the triangles will always end with 1 `*` at the top.

> The size of the triangle is the size of the base if the inverter is `+` and is the size of the top if the inverter is `-`.

# Answer
## Pyth, ~~40~~ ~~36~~ ~~34~~ 32 bytes

*-1 byte by @isaacg*

```
JstPz_W}\+zjl#m.[J*\*-J*}\tzyd;J

```

A semicolon inside a lambda is now the lambda variable's global value, a feature that saves one byte.

```
                         Implicit: z = input
JstPz                    J = size.
_W }\+z                  Reverse if "+" in z
j l# m                J  Join the nonempty lines in map lambda d:... over range(J)
      .[J            ;   Pad the following with spaces (;) to length J
         *\*               "*", this many times:
            -J*}\tzyd        J if "t" not  in z,
                             otherwise the correct number for a triangle.

```

Try it here.

Test suite.
> 9 votes

# Answer
# Pyth, 38 bytes

```
JsPtzj?}\szm*\*JJ_W}\-zm.[J*\*hyd;/hJ2

```

Test suite

Basically as straightforward as it gets. I wish I could combine some of the logic for the two shapes, but currently it's separate.
> 5 votes

# Answer
## Python 2, 106 bytes

```
s=raw_input()
n=int(s[1:-1])
for i in[range(1,n+1,2),n*[n]][s<'t'][::2*('+'in s)-1]:print('*'*i).center(n)

```

The output is a perfect rectangle, with each line padded with trailing spaces, which I'm assuming is okay based on the comments in the OP.

Note: I'm still never sure whether `input` is allowed in Python 2 for problems like these...
> 5 votes

# Answer
# JavaScript (ES6), 142 ~~146 147~~

**Edit** 1 byte saved thx @ETHproductions **Edit** 2 bytes sve thx @user81655

```
i=>([,a,b]=i.match`.(.+)(.)`,Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a)).map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r).join`
`)

```

**Test** (run in FireFox)

```
F=i=>(
  [,a,b]=i.match`.(.+)(.)`,
  Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a))
  .map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r)
  .join`\n`
)

function test() { O.textContent=F(I.value) }

test()
```

```
Input: <input id=I oninput="test()" value="t11-"/>
<pre id=O></pre>
```
> 5 votes

# Answer
# Japt, ~~62~~ ~~60~~ ~~55~~ ~~52~~ 51 bytes

```
V=Us1 n;U<'t?Vo ç*pV):0oV2 £S²pY iY'*pV-X})·z2*!Uf-

```

Try it online!

The first thing we need to do is figure out how big our shape needs to be. This is pretty simple:

```
      // Implicit: U = input string, S = space
V=    // Set variable V to
Us1   // everything after the first char of U,
n;    // converted to a number. This turns e.g. "12+" into 12.

```

Now we organize the shape of the output:

```
U<'t?      // If U comes before "t" lexicographically (here, if the first char is "s"),
Vo         //  make a list of V items,
ç*pV)      //  and set each item to V asterisks.
:0oV2      // Otherwise, create the range [0, V) with steps of 2 (e.g. 7 -> [0,2,4,6]),
£       }) //  and map each item X and index Y to:
S²pY       //   Repeat 2 spaces Y times. This creates a string of Y*2 spaces.
iY'*pV-X   //   At position Y in this string (right in the middle), insert V-X asterisks.
·          // Join with newlines.

```

By now, we have taken care of the size and shape of the output. All that's left is the rotation. Triangles are currently pointed up, so we need to flip them if the third char is `+`:

```
!Uf-    // Take the logical not of U.match("-").
        // If U contains "-", this returns false; otherwise, returns true.
2*      // Multiply by two. This converts true to 2, false to 0.
z       // Rotate the list 90° that many times.
        // Altogether, this turns the shape by 180° if necessary.

```

And with implicit output, our work here is done. :-)
> 4 votes

# Answer
# Python 2, ~~235~~ ~~193~~ ~~167~~ 157 Bytes

**Update:**

Made some significant optimizing by using list comprehensions and str.center(). I have the feeling I can do some more tho, gonna hava a fresh look at it later.

**Update 2**

Saved 10 Bytes with the suggestions of Sherlock9. Thanks a lot! :)

```
d=raw_input()
x=int(d[1:-1])
o="\n".join("*"*x for i in range(x))if d<"t"else"\n".join(("*"*i).center(x)for i in range(x,0,-2))
print o[::-1]if"+"in d else o

```

**Old answer**

```
d=raw_input()
x=int(d[1:-1])
if "s" in d:
 for y in range(x):
    o+="*"*x+"\n"
 o=o[:-1]
else:
 b=0
 while x+1:
    o+=" "*b+"*"*x+" "*b+"\n"
    x-=2
    b+=1
 o=o[:-1]
 if d[-1]=="+":
    o=o[::-1]
print o

```

Pretty straighforward approach. Writing line per line in a string which I output in the end. Triangles are always drawn inverted and get reversed if needed. The fact that you can multiply a string with an Integer saved me a lot of bytes!

I will try to golf that down a bit more later, would appreciate suggestions in the meantime, since I am not that much exprienced with it yet.

**edit:** Golfed it down a lot with the help in the comments and stealing the size-calculation from one of the other python-answers. I think thats the most I can do with this algorithm.
> 4 votes

# Answer
# JavaScript, 220 bytes.

```
q=s=>+s.slice(1,s.length-1);f=s=>s[0]=="s"?("*".repeat(q(s))+"\n").repeat(q(s)):Array.apply(0,Array(-~(q(s)/2))).map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n:n)).map(n=>(" ".repeat(q(s)/2-n)+"*".repeat(n*2+1))).join("\n")

```

Run with `f(input here)`

Try it here!

The squares has trailing newlines, but the triangles don't. Explanation:

```
q=s=>+s.slice(1,s.length-1);                                                                                Define a function, q, that takes returns the argument, without the first and last character, casted into an integer.
                            f=s=>                                                                                Define a function, f, that takes one argument, s. (This is the main function)
                                 s[0]=="s"?                                                                                If the first character of s is "s" then...
                                           ("*".repeat(q(s))     )                                                                                Repeat the "*" character q(s) times.
                                           (                +"\n")                                                                                Append a newline to that
                                                                  .repeat(q(s))                                                                                Repeat that q(s) times.
                                                                               :                                                                                Else... (the first character of s isn't "s")
                                                                                Array.apply(0,Array(          ))                                                                                Create an array of length...
                                                                                Array.apply(0,Array(-~(q(s)/2)))                                                                                floor(q(s)/2)+1
                                                                                .map((_,n)=>                                   )                                                             Map each element, _ with index n to...
                                                                                .map((_,n)=>(s[s.length-1]=="-"?              ))                                                             If the last element of s is "-" then...
                                                                                .map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n  ))                                                             floor(q(s)/2)-n
                                                                                .map((_,n)=>(s[s.length-1]=="-"?            : ))                                                             Else...
                                                                                .map((_,n)=>(s[s.length-1]=="-"?             n))                                                             Just n
                                                                                .map(n=>                                        )            Map each element into...
                                                                                .map(n=>(" ".repeat(q(s)/2-n)                   )            Repeat " ", q(s)/2-n times.
                                                                                .map(n=>(                   )+"*".repeat(n*2+1)))            Append "*", repeated 2n+1 times.
                                                                                .map(n=>(" ".repeat(        )+"*".repeat(n*2+1))).join("\n") Join with newlines

```
> 3 votes

# Answer
# Python 2, ~~157~~ 132 bytes

```
def f(s):
 S=int(s[1:-1])
 for n in([range(1,S+2,2),range(S,0,-2)]['-'in s],[S]*S)['s'in s]:
  print "{:^{S}}".format('*'*n,S=S)

```

First attempt firgured that the `+/-` on the end was optional, getting rid of that let me shave off a bunch

The idea here is to make a list which can get thrown into a generic output. Hardest part was separating out the length from the input.
> 3 votes

# Answer
## ES6, ~~178~~ ~~172~~ 159 bytes

```
s=>(p=s.match(/d+|./g),u=n=+p[1],m=n+1>>1,t=' '.repeat(n)+'*'.repeat(n),v=s<'t'?0:p[2]<'-'?(u=m,1):-1,[...Array(s<'t'?n:m)].map(_=>t.substr(u,u,u+=v)).join`
`)

```

This works due to an interesting observation I made. If you repeat `n` spaces and `n` asterisks you get (e.g. for `n=5`) this:

```
     *****

```

Now, take substrings with the same start and length:

```
     |*****| (5)
    | ***| (4)
   |  *| (3)

```

These substrings are exactly the strings we need for `t5`.

Edit: Saved 6 bytes thanks to @edc65.

Edit: Saved 13 bytes thanks to hiding the `u+=v` in the third argument of `substr` thus allowing me to simplify the initialisation.
> 2 votes

# Answer
## Retina, ~~102~~ 85 bytes

Byte count assumes that the source code is encoded as ISO 8859-1.

```
\d+
$0$*:¶
^((\w)+):(:+)
$1$2$3$2¶$0
m`s$|:t

)`(.+)¶-(\D*)
-$2¶$1
m`^.

G`.
T`ts:` *

```

Try it online.

I'll try to golf this some more later.
> 2 votes

# Answer
## Seriously, 54 bytes

```
,#i's=`≈;'**@½≈";#dXdXεj' +"£n`@`≈;'**n`@Iƒ('-=WXa0WXü

```

Try It Online

```
,#i                                                    Take input, push chars separately
   's=                                   Iƒ            IF the first char is "s":
                                `      `@                run the quoted function
                                 ≈;'**n                  make list of n strings of n *'s
      `                       `@                       ELSE run the quoted function:
       ≈;                                                make two copies of int n
         '**                                             use one to make string of n *'s
            @½≈                                          cut the other in half (e.g. 5->2)
               "           "£n                           run n/2 times the quoted function:
                ;#                                        copy the string as list of chars
                  dXdX                                    discard the last 2 *'s
                      εj                                  join back into string
                        ' +                               prepend a space
                                           ('-=WX 0WX  IF the third character is "-":
                                                 a       invert the stack
                                                     ü pop and print the entire stack

```

@Mego: See that `#dXdXεj`? STRING SLICING????
> 2 votes

# Answer
# MATL, 48 bytes

```
' *'jt4Y2m)U1$l't'Gm?2MQ2/:1L3$)R!P!R'+'Gm?P]]Q)

```

Uses current version (10.1.0) of the language/compiler.

The code accepts input characters in any order: all `s11+`, `11s+` and even `1+s1` would be valid input strings.

*EDIT (July 30, 2016): the linked code replaces `1L3$)` by `Y)` to conform to recent changes in the language*

**Try it online!**

### Explanation

```
' *'        % push string. Will be indexed into to obtain final result
j           % input string
t           % duplicate
4Y2         % predefined literal string '0123456789'
m           % logical index of digits in input string
)           % index into input string to obtain substring with digits
U           % convert to number
1$l         % generate square of ones with that size
't'         % push character 't'
G           % push input string
m           % true if input string contains 't'
?           % if so...
  2M        % push argument of call to function `l`, i.e. square size
  Q2/       % add 1 and divide by 2. Call result T
  :         % generate vector [1, 2, ... T]
  1L        % predefined literal representing Matlab's `:` index
  3$)       % two dimensional index. Transforms square into rectangle
  R         % remove (set to zero) lower-left corner
  !P!       % flip horizontally
  R         % remove lower-left corner. This gives inverted triangle
  '+'       % push character '+'
  G         % push input
  m         % true if input contains '+'
  ?         % if so...
    P       % flip vertically
  ]         % end if
]           % end if
Q           % add 1. This gives array of values 1 and 2
)           % index string ' *' with this array to produce char array
            % implicitly display that char array

```
> 2 votes

# Answer
# Ruby, 99

```
->s{n=s[1,2].to_i
n.times{|i|d=(s.ord-115)*(s[-1]<=>?,)*(n-1-i*2)
d<1&&puts((?**(n+d)).center(n))}}

```

Calculates a square or triangle of height `n` and *average width* `n` by verying the slope of the sides (so the calculated triangle width is 2n-1 at the base, 1 at the tip.) But it only *prints* those rows which do not exceed `n` characters.

**ungolfed in test program**

```
f=->s{                         #take a string as an argument
  n=s[1,2].to_i                #take 2 characters starting at index 1 and convert to a number for the size
  n.times{|i|                  #iterate through n rows
    d=                         #calculate how many stars "MORE THAN" n we need on a row
    (s.ord-115)*               #ascii code for 1st character of string - 115 : s-->0, t-->1
    (s[-1]<=>?,)*              #compare last character of input with comma character - --> +1 + --> -1
    (n-1-i*2)                  #row number * 2: 0 at centre, positive above it, negative below it
    d<1&&                      #only output if d is nonpositive (i.e we need less than n or exactly n stars)
    puts((?**(n+d)).center(n)) #print n+d stars, centred in a field of n characters padded by whitespace
  }
}

f[gets.chomp]

```
> 1 votes

# Answer
# C, 259 bytes

```
#define x(y);)putchar(y)
#define m(n)for(n=0;n++<
#define T {m(q)i x(32);m(q)s-i*2 x(42);puts("");}
main(q,v,i,s)char**v;{s=atoi(v[1]+1);if(*v[1]=='s')m(i)s*s x(42)&&!(i%s)&&puts("");else if(strchr(v[1],'+'))for(i=s/2+1;i-->0;)T else for(i=-1;i++<s/2+1;)T}

```

### ungolfed

```
main(q,v,i,size)char**v; // neat way of declaring variables
{
    size=atoi(v[1]+1);
    if(*v[1]=='s')
    {
        for(i=0;i++<size*size;)
        {
            putchar(42); // returns 42 (true)
            if(!(i%size))
                puts("");
        }
    }
    else if(strchr(v[1],'+')) // if finds plus sign
    {
        for(i=size/2+1;i-->0;) // iterate the height of the triangle
        {
            for(q=0;q++<i;)putchar(32); // conveniently i is the number os spaces before each line
            for(q=0;q++<size-i*2;) putchar(42);
            puts("");
        }
    }
    else for(i=-1;i++<size/2+1;) // does the same as above but inverted order
    {
        for(q=0;q++<i;)putchar(32);
        for(q=0;q++<size-i*2;)putchar(42);
        puts("");
    }
}

```

Suggestions and critique are very welcome.
> 1 votes

# Answer
# Jolf, 37 bytes, noncompeting

I added functions after this challenge was posted, so this cannot be considered for acceptation. This is encoded in ISO-8859-7. Try all test cases here.

```
onFiΒ€ioSgiγ?='sn―sΒ'*―TΒ1'*?='-SZiγγ

```

## Part 1: parsing the string

```
onFiΒ€ioSgi
on          set n to
  Fi         the first entity of i (the shape identifier)
    Β       set Β (beta) to
     €i      the "inside" of i (in this case, the size) as a number
       oS   set S to
         gi  the last entity of i (the inverter)

```

## Part 2: obtaining the result

```
γ?='sn―sΒ'*―TΒ1'*
γ                 set γ (gamma) to the result of the following expression
 ?='sn             if n is the character s,
      ―sΒ'*         then return a pattern "s" (a square) made with "*"s
           ―TΒ1'*    otherwise, return a pattern "T" (triangle) that is centered and
                     has a scale factor of 1, made with "*"s

```

## Part 3: inverting the result

```
?='-SZiγγ
?='-S     if S is a "-"
     Ziγ   return γ, inverted across its lines
        γ  otherwise, return γ untouched

```
> 1 votes

# Answer
# Vyxal, 22 bytes

```
[⁰(×⁰*,)|¹ƛ×*¹↳øm;⁰ßṘ⁋

```

Try it Online!

```
[                      # If truthy (square) then...
 ⁰(    )               # (size) times
   ×⁰*,                # Print (size) asterisks
        |              # Else...
         ¹ƛ      ;     # Map input to...
           ×*          # That many asterisks
             ¹↳        # Right-justified to triangulate
               øm      # Palindromise
                  ⁰ßṘ  # If (input), reverse
                     ⁋ # Join by newlines

```
> 0 votes

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


title: #OctothorpeAsciiArt

text:
# Question
Title: #OctothorpeAsciiArt
An Octothorpe, (also called number sign, hash or hashtag, or pound sign) is the following ASCII character:

```
#

```

Isn't that a fun shape? Lets make bigger versions of it! So here is your challenge:

> Given a positive integer **N**, output an ASCII hashtag of size **N**.

For example, an ASCII hashtag of size **1** looks like this:

```
 # #
#####
 # #
#####
 # #

```

Trailing whitespace on each line is allowed, but not required.

The input will *always* be a valid positive integer, so you don't have to handle non-numbers, negative, or 0. Your output can be in any reasonable format, so outputting to STDOUT, returning a list of strings, or string with newlines, a 2D matrix of characters, writing to a file, etc. are all fine.

## Test cases

```
2:
  ##  ##
  ##  ##
##########
##########
  ##  ##
  ##  ##
##########
##########
  ##  ##
  ##  ##

3:
   ###   ###
   ###   ###
   ###   ###
###############
###############
###############
   ###   ###
   ###   ###
   ###   ###
###############
###############
###############
   ###   ###
   ###   ###
   ###   ###

4:
    ####    ####
    ####    ####
    ####    ####
    ####    ####
####################
####################
####################
####################
    ####    ####
    ####    ####
    ####    ####
    ####    ####
####################
####################
####################
####################
    ####    ####
    ####    ####
    ####    ####
    ####    ####

5:
     #####     #####
     #####     #####
     #####     #####
     #####     #####
     #####     #####
#########################
#########################
#########################
#########################
#########################
     #####     #####
     #####     #####
     #####     #####
     #####     #####
     #####     #####
#########################
#########################
#########################
#########################
#########################
     #####     #####
     #####     #####
     #####     #####
     #####     #####
     #####     #####

```

Since this is a code-golf, try to write the shortest possible solution you can, and above all else, have fun!

# Answer
> 22 votes
# MATL, ~~20~~ ~~16~~ ~~12~~ 11 bytes

3 bytes thanks to DJMcMayhem.

1 byte thanks to Luis Mendo.

```
21BwY"&*~Zc

```

Try it online!

## Explanation

```
    % stack starts with input e.g. 2
21  % push 21 to stack             2 21
B   % convert to binary            2 [1 0 1 0 1]
w   % swap                         [1 0 1 0 1] 2
Y"  % repeat                       [1 1 0 0 1 1 0 0 1 1]
&*  % one-input multiplication    [[1 1 0 0 1 1 0 0 1 1]
                                   [1 1 0 0 1 1 0 0 1 1]
                                   [0 0 0 0 0 0 0 0 0 0]
                                   [0 0 0 0 0 0 0 0 0 0]
                                   [1 1 0 0 1 1 0 0 1 1]
                                   [1 1 0 0 1 1 0 0 1 1]
                                   [0 0 0 0 0 0 0 0 0 0]
                                   [0 0 0 0 0 0 0 0 0 0]
                                   [1 1 0 0 1 1 0 0 1 1]
                                   [1 1 0 0 1 1 0 0 1 1]]
~   % complement                  [[0 0 1 1 0 0 1 1 0 0]
                                   [0 0 1 1 0 0 1 1 0 0]
                                   [1 1 1 1 1 1 1 1 1 1]
                                   [1 1 1 1 1 1 1 1 1 1]
                                   [0 0 1 1 0 0 1 1 0 0]
                                   [0 0 1 1 0 0 1 1 0 0]
                                   [1 1 1 1 1 1 1 1 1 1]
                                   [1 1 1 1 1 1 1 1 1 1]
                                   [0 0 1 1 0 0 1 1 0 0]
                                   [0 0 1 1 0 0 1 1 0 0]]
Zc  % convert 0 to spaces            ##  ##
      1 to octothorpes               ##  ##
      and join by newline          ##########
                                   ##########
                                     ##  ##
                                     ##  ##
                                   ##########
                                   ##########
                                     ##  ##
                                     ##  ##

```

# Answer
> 15 votes
# Brain-Flak, 420 bytes

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

```

Try it online!

No, the score of 420 was not intentional. I promise. Readable version:

```
# 3 Times...
(()()())
{
({}<

    #Duplicate the input
    (({}))

    #Input times...
    {
        ({}<

        #Switch to the main stack
        <>

        #Grab the duplicate of the input
        (<>({})<>)

        #That many times...
        {({}<

            # Push a hash
            ((((()()()()){}){}()){}())

        >[()])}{}

        #Grab the duplicate of the input
        (<>({})<>)

        #That many times...
        {({}<

            #Push a space
            ((((()()()()){}){}){})

        >[()])}{}

        #Grab the duplicate of the input
        (<>({})<>)

        #That many times...
        {({}<

            # Push a hash
            ((((()()()()){}){}()){}())

        >[()])}{}

        #Grab the duplicate of the input
        (<>({})<>)

        #That many times...
        {({}<

            #Push a space
            ((((()()()()){}){}){})

        >[()])}{}

        #Push a newline
        ((()()()()()){})

        #Toggle back to the alternate stack
        <>

        #Decrement the (second) loop counter
        >[()])

    #Endwhile
    }

    #Pop the now zeroed loop counter
    {}

    #Turn [a] into [a, a*5, a]
    ((({}))<(({})(({}){}){})>)

    #A times....
    {
        ({}<

        #Toggle back over
        <>

        #Grab a*5
        (<>({})<>)

        #That many times...
        {({}<

            #Push a space
            ((((()()()()){}){}()){}())

        >[()])}{}

        #Push a newline
        ((()()()()()){})

        #Toggle back
        <>

        #Decrement the (second) loop counter
        >[()])

    }

    #Pop the loop counter and the a*5
    {}{}

#Decrement the outer loop counter
>[()])
}

#Pop the zeroed loop counter
{}

#Pop a over
({}<>)

#Pushes (a**2) * 5 + a
(({})((({({})({}[()])}{})){}){}{})

#That many times...
{({}<

    #Pop a character off the output stack
    {}

>[()])}

```

# Answer
> 14 votes
# 6502 machine code (C64), 59 56 bytes

```
00 C0 20 9B B7 A9 06 85 FC 86 FE A6 FE 86 FD A9 03 4D 1F C0 8D 1F C0 C6 FC D0
01 60 A9 23 A0 05 49 00 20 D2 FF CA D0 FA A6 FE 88 D0 F3 A9 0D 20 D2 FF C6 FD
D0 E6 F0 D3

```

### Online demo

Usage: `SYS49152,N` where N is a number between 1 and 255.

<sub>(values greater than 4 will already be too large for the C64 screen, starting from 8, the output is even too wide)</sub>

**Explanation**:

```
         00 C0       .WORD $C000    ; load address

.C:c000  20 9B B7    JSR $B79B      ; read N into X
.C:c003  A9 06       LDA #$06       ; number of "logical" lines plus 1 for hash
.C:c005  85 FC       STA $FC        ; store in counter variable for lines
.C:c007  86 FE       STX $FE        ; store N in counter variable for char repetitions
.C:c009  A6 FE       LDX $FE        ; load repetition counter
.C:c00b  86 FD       STX $FD        ; store in counter variable for line repetitions
.C:c00d  A9 03       LDA #$03       ; value to toggle the character toggle
.C:c00f  4D 1F C0    EOR $C01F      ; xor character bit toggle
.C:c012  8D 1F C0    STA $C01F      ; store character bit toggle
.C:c015  C6 FC       DEC $FC        ; decrement "logical" lines
.C:c017  D0 01       BNE $C01A      ; not 0 -> continue
.C:c019  60          RTS            ; program done
.C:c01a  A9 23       LDA #$23       ; load hash character
.C:c01c  A0 05       LDY #$05       ; load "logical" columns for hash
.C:c01e  49 00       EOR #$00       ; in each odd "logical" line, toggle character
.C:c020  20 D2 FF    JSR $FFD2      ; output one character
.C:c023  CA          DEX            ; decrement character repetition
.C:c024  D0 FA       BNE $C020      ; not 0 -> back to output
.C:c026  A6 FE       LDX $FE        ; reload character repetition
.C:c028  88          DEY            ; decrement "logical" columns
.C:c029  D0 F3       BNE $C01E      ; not 0 -> back to character toggle
.C:c02b  A9 0D       LDA #$0D       ; line done, load newline character
.C:c02d  20 D2 FF    JSR $FFD2      ; and output
.C:c030  C6 FD       DEC $FD        ; decrement line repetitions
.C:c032  D0 E6       BNE $C01A      ; not 0 -> back to character init
.C:c034  F0 D3       BEQ $C009      ; else back to main loop (toggle char toggling)

```

# Answer
> 10 votes
# Haskell, 43 bytes

```
l%n=l!!1:l++l<*[1..n]
f n=["##"%n,"# "%n]%n

```

Try it online!

Outputs a list of strings.

# Answer
> 8 votes
# Python 2, 55 bytes

```
def f(n):p=[(" "*n+"#"*n)*2]*n;print(p+["#"*n*5]*n)*2+p

```

Try it online!

This returns a 2D list of characters.

# Python 2, 65 bytes

```
def f(n):p=((" "*n+"#"*n)*2+"\n")*n;print(p+("#"*n*5+"\n")*n)*2+p

```

Try it online!

# Python 2, 66 bytes

```
def f(n):p=[(" "*n+"#"*n)*2]*n;print'\n'.join((p+["#"*n*5]*n)*2+p)

```

Try it online!

# Answer
> 8 votes
## Husk, ~~12~~ 10 bytes

```
´Ṫ▲Ṙ" # #

```

Try it online! Note the trailing space.

## Explanation

```
´Ṫ▲Ṙ" # #   Implicit input, e.g. n=2.
   Ṙ" # #   Repeat each character of the string n times: "  ##  ##  "
´Ṫ          Outer product with itself by
  ▲         maximum: ["  ##  ##  ","  ##  ##  ","##########","##########","  ##  ##  ","  ##  ##  ","##########","##########","  ##  ##  ","  ##  ##  "]
            Print implicitly, separated by newlines.

```

# Answer
> 7 votes
# CJam, ~~27~~ ~~26~~ 25 bytes

```
{_[{S3*'#*'#5*}3*;]fe*e*}

```

Try it online!

Fun fact: This originally started at 29 bytes, and bytes have been removed one-by-one ever since, alternating between block and full-program mode.

## Explanation:

```
{                          e# Stack:               | 2
 _                         e# Duplicate:           | 2 2
  [                        e# Begin array:         | 2 2 [
   {                       e# Do the following 3 times:
    S                      e#   Push a space       | 2 2 [" "
     3*                    e#   Repeat it 3 times: | 2 2 ["   "
       '#*                 e#   Join with '#':     | 2 2 [" # # "
          '#               e#   Push '#':          | 2 2 [" # # " '#
            5*             e#   Repeat it 5 times: | 2 2 [" # # " "#####"
              }3*          e# End:                 | 2 2 [" # # " "#####" " # # " "#####" " # # " "#####"
                 ;         e# Delete top of stack: | 2 2 [" # # " "#####" " # # " "#####" " # # "
                  ]        e# End array:           | 2 2 [" # # " "#####" " # # " "#####" " # # "]
                   fe*     e# Repeat characters:   | 2 ["  ##  ##  " "##########" "  ##  ##  " "##########" "  ##  ##  "]
                      e*   e# Repeat strings:      | ["  ##  ##  " "  ##  ##  " "##########" "##########" "  ##  ##  " "  ##  ##  " "##########" "##########" "  ##  ##  " "  ##  ##  "]
                        }  e# End
e# Result:
e# ["  ##  ##  "
e#  "  ##  ##  "
e#  "##########"
e#  "##########"
e#  "  ##  ##  "
e#  "  ##  ##  "
e#  "##########"
e#  "##########"
e#  "  ##  ##  "
e#  "  ##  ##  "]

```

# Answer
> 7 votes
# Perl 5, 49 + 1 (-p) = 50 bytes

```
$_=' # #
'=~s/./$&x$_/gre x$_;$_.=(y/ /#/r.$_)x2

```

Try it online!

**How?**

Implicitly store the input in `$_` via the `-p` flag. Start with the most basic possible top line `" # # "` with its trailing newline. Replicate each of those characters by the input number. Then replicate that by the input number to form the top part of the octothorpe, storing all of that back in `$_`. Then append the line with all characters replaced by '#' times the input number. Then append the top section. Do those last two sentences a total of two times. Output of the `$_` is implicit in the `-p` flag.

# Answer
> 6 votes
# , ~~23~~ 19 bytes

```
' #'{~1=]+./~@#i:@2

```

Saved 4 bytes thanks to @LeakyNun.

Try it online!

## Explanation

```
' #'{~1=]+./~@#i:@2  Input: integer n
                  2  The constant 2
               i:@   Range [-2, -1, 0, 1, 2]
        ]            Get n
              #      Copy each n times
         +./~@       GCD table
      1=             Equals 1, forms the hashtag for input 1
' #'{~               Index and select the char

```

# Answer
> 6 votes
# Charcoal, 21 bytes

```
ＮθＵＯ×²θ#ＵＯθ Ｆ²⟲ＯＯ²⁴⁶θ

```

Try it online! Link is to verbose version of code. I'd originally tried a cute bitmap approach:

```
Ｆ⁵Ｆ⁵Ｆ＆｜ικ¹«Ｊ×ιＩθ×κＩθＵＯθ#

```

Try it online! Link is to verbose version of code. Explanation: Works by considering the `#` as an array of 5×5 squares. The squares that are in odd rows or columns need to be filled in.

# Answer
> 6 votes
# J, 22 bytes

```
#('# '{~#:5$21,0)#~"1]

```

Try it online!

A lot of similarity to the other J answer, though I don't understand trains with lots of nouns well, so my answer has three potential bytes to cut off (two parens and a reflexive-`~`).

# Explanation

### Generating the octothorpe

The octothorpe is made by everything in the parenthetical, reproduced below for convenience.

```
'# '{~#:5$21,0

```

A lot of the way I make the octothorpe is abuse of the way that J pads its arrays when they aren't long enough.

`21,0` simply creates the array `21 0`.

`5$` reshapes that array into a 5-atom array: `21 0 21 0 21`.

`#:` converts each atom into a binary number. Since `#:` operates on each atom, the output is a matrix. Each `21` is replaced by `1 0 1 0 1` as expected, but each `0` is replaced by `0 0 0 0 0`! This is because J pads arrays not long enough to match the shape of the resulting 2D array which is forced to be `5 5` because of the `1 0 1 0 1` rows. Fortunately, for numbers it pads with `0`, so we get the resulting matrix

```
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1

```

`'# '{~` converts each `1` to a space and `0` to `#`. `{` means "take" and `~` means "switch the dyadic arguments, so J looks to each element in the matrix as indices for the string `'# '` meaning each `0` becomes the zeroth element, `#` and each `1` becomes the first element, a space. This yields the size one octothorpe.

### Resizing the octothorpe

This is simply a matter of copying `n` times along each axis, done using

the first `#` (which is part of a hook) and `#~"1]`. `#` copies along the horizontal axis and `#"1` copies along the vertical axis.

# Answer
> 6 votes
# Jelly, ~~14~~ ~~13~~ 11 bytes

*Saved 2 bytes thanks to @JonathanAllen*

```
5ẋ€Ẏ&þ`ị⁾ #

```

A monadic link returning a list of lines. Note the trailing space.

Try it online!

### How it works

```
5ẋ€Ẏ&þ`ị⁾ #    Main link. Arguments: n (integer)            1
5              Yield 5.
 ẋ€            Create a range and repeat each item n times. [[1], [2], [3], [4], [5]]
   Ẏ           Tighten; dump all sublists into the main list.
                                                            [1, 2, 3, 4, 5]
     þ         Create a table of                            [[1, 0, 1, 0, 1],
    &          bitwise ANDs,                                 [0, 2, 2, 0, 0],
      `        reusing this list.                            [1, 2, 3, 0, 1],
                                                             [0, 0, 0, 4, 4],
                                                             [1, 0, 1, 4, 5]]
       ị⁾ #    Index into the string " #".                   [" # # ",
               0 -> "#", 1 -> " ", 2 -> "#", etc.             "#####",
                                                              " # # ",
                                                              "#####",
                                                              " # # "]

```

# Answer
> 4 votes
# Game Maker Language, ~~138~~ 108 bytes

```
n=argument0 s=''for(j=0;j<5*n;j+=1){for(l=0;l<5*n;l+=1)if(j div n|l div n)&1s+='#'else s+=' 's+='
'}return s

```

Intended as a script (Game Maker's name for user-defined functions), thus the `n=argument0` and `return s`. 20 bytes could be shaved by taking `n` directly from the current instance and using `s` as the result. (The instance gets these variables anyway because they weren't declared with `var`).

Beware of course that `#` is used by Game Maker's graphics stuff as an alternative newline character, so you might want to prefix it with `\` if you want to output to the screen ;)

Also note that I'm using Game Maker 8.0's version of GML here; modern GML versions might have features that could save additional bytes.

Some ideas courtesy of friends wareya and chordbug.

# Answer
> 4 votes
# Brain-Flak, ~~338~~ 332 bytes

6 bytes thanks to Riley.

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

```

Try it online!

## More "readable" version

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

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~25~~ ~~22~~ 21 bytes

```
•LQ•bûε×}5ôεS„# èJ¹F=

```

Try it online!

---

***-1 because Emigna hates transliterate and, thankfully, reminds me I should too :P.***

---

Gotta be a better way than bitmapping it... Still working.

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

```
f=
n=>[...Array(n*5)].map((_,i,a)=>a.map((_,j)=>` #`[(i/n|j/n)&1]).join``).join`
`
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

Port of the bitmap approach that I'd used for my original Charcoal attempt.

# Answer
> 3 votes
# Python 2, ~~124~~, ~~116~~, ~~113~~, ~~112~~, ~~98~~, ~~96~~ 66 bytes

New (Credit: HyperNeutrino):

```
def f(a):i='print(" "*a+"#"*a)*2;'*a;exec(i+'print"#"*a*5;'*a)*2+i

```

Old:

```
a=input();b,c="# "
for i in"012":
	exec'print c*a+b*a+c*a+b*a;'*a
	if i<"2":exec'print b*a*5;'*a

```

Try it online!

Obviously not the shortest solution, but I think it's decent. Any feedback would be appreciated!

# Answer
> 3 votes
# Befunge, ~~105~~ 103 bytes

```
p9p&5*08p>08g-   v
>,g1+:00p^v0:/5g8_p9g1+:09p08g-#v_@
gvg90\/\g0< # # ##### 0:/5g8,+55<
^>\/2%5*+92++2

```

Try it online!

# Answer
> 3 votes
# brainfuck, 224 bytes

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

```

Try it online!

## Making-of

I tried to build this code by hand and spent quite a few hours, so I decided to make a transpiler in Python.

Here is the code I entered to make this code:

```
read(0)
copy(0,(1,1),(5,1))
add(3,1)
add(4,5)
loop(4)
loop(1)
add(2,1)

add(7,1)
add(8,5)
loop(8)
loop(5)
add(6,1)

loop(3)
add(9,1)
loop(7)
add(10,1)
add(11,-3)
end(7)
end(3)
copy(9,(3,1))
copy(10,(7,1))
add(10,5)
copy(10,(11,7))
write(11)
clear(11)

end(5)
copy(6,(5,1))
copy(7,(6,-1))
add(6,1)
copy(6,(7,1))
end(8)
add(6,10)
write(6)
clear(6)

end(1)
copy(2,(1,1))
copy(3,(2,-1))
add(2,1)
copy(2,(3,1))
end(4)

```

Try it online!

# Answer
> 3 votes
# MAWP 2.0, 46 bytes

```
@!!!"#"*/" "*\+2*"
"+*!:/!5*"#"*"
"+*!:\!:/:/:

```

Try it!

# Answer
> 2 votes
# SOGL (SOGLOnline commit 2940dbe), 15 bytes

```
ø─Ζ┘Χ⁴‘5n{.∙.*T

```

To run this, download this and run the code in the `index.html` file.

Uses that at that commit (and before it) `*` repeated each character, not the whole string.

Explanation:

```
ø─Ζ┘Χ⁴‘          push " # # ##### # # ##### # # "
       5n        split into lines of length 5
         {       for each line do
          .∙       multiply vertically input times
            .*     multiply horizontally input times
              T    output in a new line

```

Bonus: add 2 inputs for separate X and Y length!

# Answer
> 2 votes
# C (gcc), ~~98~~ 93 bytes

5 bytes thanks to Felix Palmen.

```
i,j;main(a){for(scanf("%d",&a);j<a*5||(j=!puts(""),++i<a*5);)putchar(i/a+1&j++/a+1&1?32:35);}

```

Try it online!

# Answer
> 2 votes
# Gaia, 9 bytes

```
 # ”ṫ&:Ṁ‡

```

Pretty much a port of Zgarb's great answer

Try it online! (the footer is just to pretty print, the program itself returns a 2D list of characters)

### Explanation

```
 # ”       Push the string " # "
    ṫ      Bounce, giving " # # "
     &     Repeat each character by input
      :    Copy
       Ṁ‡  Tabled maximum with itself

```

# Answer
> 2 votes
# Canvas, 11 bytes

```
 #¶##┼∙┼╶╶＊

```

Try it here!

Explanation:

```
 #¶##         push "#\n##"
     ┼        quad-palindromize with 1 overlap
      ∙┼      quad-palindromize with 1 overlap again
        ╶╶＊  expand vertically and horizontally by the input

```

# Answer
> 1 votes
# PowerShell, ~~72~~ ~~68~~ ~~63~~ 60 bytes

```
param($a)(,($x=,((' '*$a+"#"*$a)*2)*$a)+,("#"*5*$a)*$a)*2;$x

```

Try it online!

Takes input `$a`. Then, we do a bunch of ~~magic~~ string and array manipulation.

```
(,($x=,((' '*$a+"#"*$a)*2)*$a)+,("#"*5*$a)*$a)*2;$x
         ' '*$a+"#"*$a                              # Construct a string of spaces and #
        (             )*2                           # Repeat it twice
      ,(                 )*$a                       # Repeat that $a times to get the top as an array
  ($x=                       )                      # Store that into $x and immediately output it
 ,                            +                     # Array concatenate that with ...
                               ,("#"*5*$a)          # another string, the middle bar ...
                                          *$a       # repeated $a times.
(                                            )*2;   # Do that twice
                                                 $x # Output $x again

```

You can peel off the parts of the explanation starting from the bottom to see how the output is constructed, so hopefully my explanation makes sense.

# Answer
> 1 votes
# Python, ~~88~~ ~~84~~ 77 bytes

```
lambda x:[[(' #'[i//x%2]+'#')[j//x%2]for j in range(5*x)]for i in range(5*x)]

```

Try it online!

Returns 2D list of characters.

# Answer
> 1 votes
# Pyth, ~~28~~ 22 bytes

*-6 bytes thanks to @LeakyNun*

```
JsC*]S5Qjmsm@"# "*kdJJ

```

**Test Suite.**

# Answer
> 1 votes
# Dyalog APL, ~~35~~ ~~30~~ ~~28~~ 26 bytes

*2 bytes saved thanks to @ngn*

```
' #'[∘.{∨/2|⌊⍺⍵÷k}⍨⍳5×k←⎕]

```

Try it online!

With `⎕IO←0`.

# Answer
> 1 votes
# Mathematica, 63 bytes

```
ArrayFlatten@Array[x=#;Table[If[OddQ@-##," ","#"],x,x]&,{5,5}]&

```

### Explanation

```
ArrayFlatten@Array[x=#;Table[If[OddQ@-##," ","#"],x,x]&,{5,5}]&  (* input N *)

                   x=#                                           (* Set x to N *)
                                                      &          (* A function that takes two inputs: *)
                             If[OddQ@-##," ","#"]                (* if both inputs are odd (1), " ". "#" otherwise *)
                       Table[                    ,x,x]           (* Make N x N array of that string *)
             Array[                                     ,{5,5}]  (* Make a 5 x 5 array, applying that function to each index *)
ArrayFlatten@                                                    (* Flatten into 2D array *)

```

<sub>(1)`-##` parses into `Times[-1, ##]`</sub>

# Answer
> 1 votes
## Haskell, 72 bytes

```
a#b=a++b++a++b++a
c%l=((c<$l)#('#'<$l))<$l
f n=(' '%[1..n])#('#'%[1..n])

```

Returns a list of strings. Try it online!

How it works:

```
a#b=a++b++a++b++a          -- concatenate the strings a and b in the given pattern
c%l=                       -- take a char c and a list l (we only use the length
                           -- of l, the actual content doesn't matter)
    c<$l                   -- make length l copies of c
         '#'<$l            -- make length l copies of '#'
        #                  -- combine them via function #
               <$l         -- and make length l copies of that string
f n=                       -- main function
              #            -- make the "a b a b a" pattern with the strings
                           -- returned by the calls to function %
    ' '%[1..n]             --   one time with a space
               '#'%[1..n]  --   one time with a '#'

```

# Answer
> 1 votes
# Python 2, 113 bytes

**As an array of strings:**

```
r=[1-1*(i%(2*n)<n)for i in range(5*n)]
print[''.join(' #'[r[k]+r[j]>0]for k in range(len(r)))for j in range(n*5)]

```

---

**As ASCII art:**

# Python 3, 115 bytes

```
r=[1-1*(i%(2*n)<n)for i in range(5*n)]
for j in range(n*5):print(*(' #'[r[k]+r[j]>0]for k in range(len(r))),sep='')

```

# Python 3, 117 bytes

```
p=range(5*n)
for i,e in enumerate([j%(2*n)>=n for j in p]for k in p):print(*[' #'[i%(2*n)>=n or k]for k in e],sep='')

```

---

~~**As an array of booleans**~~

~~Python 2, 75 bytes
```
p=range(5*n)
f=lambda o:o%(2*n)>=n
print[[f(j)or f(i)for j in p]for i in p]

```~~

# Answer
> 1 votes
# Java 8, 103 bytes

Lambda accepts `Integer` and prints the octothorpe to standard out. Cast to `Consumer<Integer>`.

```
n->{for(int s=5*n,x=0,y;x<s;x++)for(y=0;y<s;)System.out.print((x/n%2+y++/n%2>0?'#':32)+(y<s?"":"\n"));}

```

Try It Online

## Ungolfed lambda

```
n -> {
    for (
        int
            s = 5 * n,
            x = 0,
            y
        ;
        x < s;
        x++
    )
        for (y = 0; y < s; )
            System.out.print(
                (x / n % 2 + y++ / n % 2 > 0 ? '#' : 32)
                + (y < s ? "" : "\n")
            );
}

```

The key observation here is that, on a 5 by 5 grid of *n* by *n* cells, octothorpes appear wherever the row or column number (0-based) is odd. I'm pretty sure this is the cheapest general approach, but it seems further golfable.

## Acknowledgments

* -1 byte thanks to *Kevin Cruijssen*

# Answer
> 1 votes
# , ~~87~~ ~~85~~ 62 bytes

```
m=matrix(" ",x<-scan()*5,x);m[s,]=m[,s<-rep(!1:0,e=x/5)]="#";m

```

2 bytes saved by representing c(F,T) as !1:0, thanks to LeakyNun

23 bytes saved thanks to Giuseppe

Try it online!

Explanation (ungolfed):

```
x=scan()*5              # Multiply input by 5 to get the required width/height of the matrix
m=matrix(" ",x,x)       # Create a matrix of the required dimensions
s=rep(!1:0,each=x/5)    # The sequence s consists of F repeated n times, followed by T repeated n times
m[s,]="#"               # Use s as logical indices to set those rows as "#" characters.
                        # R recycles the sequence to the height of the matrix.
m[,s]="#"               # Same, with columns
write(m,"",x,,"")       # Print out across the required number of columns

```

# Answer
> 1 votes
# Excel, 133 bytes

```
=REPT(REPT(REPT(REPT(" ",A1)&REPT("#",A1),2)&"
",A1)&REPT(REPT("#",5*A1)&"
",A1),2)&REPT(REPT(REPT(" ",A1)&REPT("#",A1),2)&"
",A1)

```

# Answer
> 1 votes
# Octave, 39 bytes

```
@(n)[kron(max(a=' # # ',a'),!!e(n)) '']

```

Try it online!

Explanation:

```
m = max(a=' # # ',a')  % Computes elementwise maximum of `a` and its transpose.

```

Since they have different dimensions broadcasting occurs and a `5*5` matrix (Octothorpe ASCII art of size `1`) is generated.

```
One = !!e(n);          % a n*n matrix of ones
kron(m , One)          % form the Kronecker product of 'm' and 'One'
                       % so each character converted to a n*n matrix of that character.

[  ... '']             % convert ASCII numeric values to char

```

# Answer
> 1 votes
# TeX, 240 bytes

```
\newcommand{\f}[1]{\h{\g{#1}{\h{\hphantom{\g{#1}{\#}}}{\g{#1}{\#}}\\}}{\g{#1}{\h{\g{#1}{\#}}{\g{#1}{\#}}\\}}}\newcommand{\g}[2]{\begingroup\count0=1\loop#2%
\advance\count0 by 1\ifnum\count0<#1\repeat\endgroup}\newcommand{\h}[2]{#1#2#1#2#1}

```

## Example usage

```
\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{\h{\g{#1}{\h{\hphantom{\g{#1}{\#}}}{\g{#1}{\#}}\\}}{\g{#1}{\h{\g{#1}{\#}}{\g{#1}{\#}}\\}}}\newcommand{\g}[2]{\begingroup\count0=1\loop#2%
\advance\count0 by 1\ifnum\count0<#1\repeat\endgroup}\newcommand{\h}[2]{#1#2#1#2#1}

\noindent\texttt{\f{8}}
\end{document}

```

# Answer
> 1 votes
# APL (Dyalog), 16 bytes

```
' #'[∘.⌈⍨⎕/5⍴⍳2]

```

Try it online!

`' #'[``]` index the string with

`⍳2` first two **ɩ**ntegers; `[1,2]`

`5⍴` cyclically reshape to length five; `[1,2,1,2,1]`

`⎕/` get input (mnemonic: console) and use that to replicate, e.g. `2``[1,1,2,2,1,1,2,2,1,1]`

`∘.⌈⍨` maximum table; `[[1,1,2,2,1,1,2,2,1,1],[1,1,2,2,1,1,2,2,1,1],[2,2,2,2,…`

# Answer
> 1 votes
# Stax, 10 bytes

```
┐/Θô¥+○╬µ^

```

Run and debug it

uses Zgarb's idea.

# Answer
> 1 votes
# 05AB1E, ~~16~~ 12 bytes

*-4 thanks to ovs*.

```
„# 5LI×SDδ&è

```

Try it online! Outputs as a list of lists of characters of lines. Link includes a footer to format the output.

# Answer
> 0 votes
# Recursiva, ~~56~~ 44 bytes

```
P+D+*aGD+*' 'a*'#'a*aG**5a'#'*aGD+*' 'a*'#'a

```

Try it online!

# Answer
> 0 votes
## PHP, 117, 114, 112, 111 110 bytes

Php isn't optimal for short code, but it less bad than expected. Open with ?a=5 in the url

```
for(;$i++<$_GET[a];){$a.="oxox
";$b.="xxxxx
";$c.=' ';$d.='#';}echo str_replace([o,x],[$c,$d],$a.$b.$a.$b.$a);

```

---

Or a little longer, but similar

### PHP 113 bytes

```
for(;$i++<$_GET[a];){$a.=oxoxoN;$b.=xxxxxN;$c.=' ';$d.='#';}echo str_replace([o,x,N],[$c,$d,"
"],$a.$b.$a.$b.$a);

```

# Answer
> 0 votes
# APL (Dyalog), 21 bytes

```
(⍴⍴'#'/⍨,)∘.⌈⍨¯1*⎕/⍳5

```

Try it online!

# Answer
> 0 votes
# Cubically \[Variant\], ~~163~~ 102 bytes

```
■f₀₂f₁₅D₁D₃B₀B₂D₁D₃B₄D₁D₃$-₀(+f₄6:7(f₅6-₀(+f₂6:7(f₃6*₅4₀+2₀@1⁶:3₁-)6:2₀-)6@₀:5₁-)6:4₀-)6

```

This is a variant of Cubically. It isn't as fun to use as the original, but it can complete certain challenges the original can't. For example, this variant has a command to set the value of each square on a face, which makes it a lot easier to store values in memory, although the number of values you can store this way is limited to the number of faces on the cube (6). You'll also see some constant values that don't need to be pulled from faces or stored in the notepad before use. For example,  which passes the value `32` to the command.

~~I don't think I'll be changing the language enough to break this code in the future~~ (`f` is changing to `ƒ` but does the same thing), but because this branch of the language is constantly changing, I've included a link to the commit this can run on in the header.

This solution creates a 5x5x5 cube and sets the left face to this:

```
01010
11111
01010
11111
01010

```

It then sets the value of face 0's squares to 32 and the value of face 1's and face 2's squares to 35, essentially creating a 1-width octothorpe on the left of the cube:

```
 # #
#####
 # #
#####
 # #

```

Then it goes through each square on the left face and enlarges it.

### How it works

```
■                   Set the cube to a new 5x5x5 cube
f₀₂f₁₅             Set face 0's values to 32 and face 1's values to 35
D₁D₃B₀B₂D₁D₃B₄D₁D₃ Create an octothorpe on face 1
$                    Input a number
-₀(                 Set the notepad to -5, and loop while notepad != 0
  +                   Add 5 to the notepad
  f₄6                  Set face 4's values to the notepad
  :7(                  Set the notepad to the input, and loop while notepad != 0
    f₅6                  Set face 5's values to the notepad
    -₀(                 Set the notepad to -5, and loop while notepad != 0
      +                   Add 5 to the notepad
      f₂6                  Set face 2's values to the notepad
      :7(                  Set the notepad to the input, and loop while notepad != 0
        f₃6                  Set face 3's values to the notepad
        *₅4₀                 Set the notepad to the value of the first square on the 4th face times 5
        +2₀                  Add the value of the first square on the 2nd face
        @1⁶                  Output the character with the ASCII value equal to the square on the 1st face with index equal to the notepad
        :3₁-                Set the notepad to the first square on the 3rd face minus 1
      )6
      :2₀-                Set the notepad to the first square on the 2nd face minus 4
    )6
    @₀                  Output \n
    :5₁-              Set the notepad to the first square on the 5th face minus 1
  )6
  :4₀-              Set the notepad to the first square on the 4th face minus 4
)6

```

~~I've actually found a way to easily create the octothorpe with only values from two faces, but I need to fix a bug in the language before that will work. It would open up the possibility of looping through the x-coordinate on the top face which would (most likely) shorten the answer.~~ Bug was fixed but it didn't affect whether that solution would work or not, so I've updated this answer.

# Answer
> 0 votes
# Actually, 29 bytes

```
5R@♀α♂i╗╜⌠╝╜⌠╛*2@%"# "E⌡MΣ⌡Mi

```

Try it online!

# Answer
> 0 votes
# Alice, 36 bytes

```
/a/E #...##Sd
\i&''d?!''yy'??dS.o!@/

```

Try it online!

### Explanation

This is a standard ordinal mode program, with two modifications:

* The `&` command is run in cardinal mode. This allows the input to be taken as an integer. This also forces the `&` to be run in ordinal mode later. While `&` can be skipped with `#`, in this case I arrange for it to be a no-op.
* The end is flattened a bit to allow a space literal to be encoded in empty space, saving a byte.

The linearized program is as follows:

```
i&' d.!.'#yd?d.!a&E'#?.'#yS' ?So@

i          take input
           STACK: ["2"]
&'(space)  push " " that many times
           STACK: [" ", " "]
d          push the concatenation of the entire stack
           STACK: [" ", " ", "  "]
.!         copy this string to tape
.'#y       change all characters to #
           STACK: [" ", " ", "##"]
d          concatenate stack again
           STACK: [" ", " ", "##", "  ##"]
?d         copy string back from tape and concatenate stack again
           STACK: [" ", " ", "##", "  ##", "  ", "  ##  ##  "]
           everything below the current top of the stack is irrelevant to the rest of the program
.!         copy string to stack: this will be used to set up individual rows
a&         for every character in "\n" (all 1 of them):
  E        place that character between every pair of characters
           this will put each character on one line, to be replaced by entire rows
           STACK: [..., " \n \n#\n#\n \n \n#\n#\n \n "]
'#         push "#" on the stack
?          copy string from stack
.'#y       replace all characters with #
           STACK: [..., " \n \n#\n#\n \n \n#\n#\n \n ", "#", "##########"]
S          substitute: replace each # with a full row of #s
' ?S       replace each space with the row "  ##  ##  " created earlier
o          output
@          terminate

```

# Answer
> 0 votes
# Mathematica, 59 bytes

```
Table[If[OddQ@*Ceiling/@(i/#&&j/#)," ","#"],{i,5#},{j,5#}]&

```

### Explanation

The input is `#`. Make a `Table` that's `5#`(implied multiplication) by `5#` where the variables `i` and `j` range from `1`(default) to `5#`. The entries in the table will be `" "` or `"#"` depending on `If` a condition is true.

The condition is a little complicated. Ungolfed, it's equivalent to `And[Composition[OddQ, Ceiling][i/#],Composition[OddQ, Ceiling][j/#]]`. We test if the `Ceiling` of `i/#` is odd `And` similarly for `j/#`. But this is golfed into `OddQ@*Ceiling/@(i/#&&j/#)` by:

* Using the fact that `Map` works for anything, not just lists, so we can write this as `Map[Composition[OddQ, Ceiling],And[i/#,j/#]]`
* Using the facts that `&&`, `/@`, and `@*` are infixes for `And`, `Map`, and `Composition`, respectively (adding parentheses to handle the fact that `&&` doesn't have higher precedence than `/@`).

## Try it online

You can try this in the Wolfram Cloud Sandbox by pasting code like:

```
Table[If[OddQ@*Ceiling/@(i/#&&j/#)," ","#"],{i,5#},{j,5#}]&@4//Grid

```

and pressing Shift+Enter or numpad Enter or clicking Gear\>Evaluate cell.

# Answer
> 0 votes
# C# (.NET Core), 225 192 169 165 161 160 158 bytes

```
using System;class P{static void Main(string[]args){for(int n=int.Parse(args[0]),d=5*n,i=0;i<d*d;)Console.Write(" ##"[i/d/n%2+i%d/n%2]+(i++%d<d-1?"":"\n"));}}

```

Try it online!

## Explanation:

Using the 1D array (representing a 2D array) row and column approach from before, I changed the area array to be the symbols to print, and as such, there are only two types of rows. The `i/d/n%2*5` selects the appropriate row in the string array, and `i%d/n` selects the column.

### Update

I simplified the string further, as each row has repetitions, so now it only looks at the first two characters of each row. Actually, I got the string down a # and simplified the equation. I'm sure the equation and the newline calculation could be shortened.

```
for(int n=int.Parse(args[0]),d=5*n,i=0;i<d*d;)
{
    Console.Write(" ##"[i/d/n%2+i%d/n%2]+(i++%d<d-1?"":"\n"));
}

```

Treat the octothorpe as a 5x5 area

```
var x=new[]{0,1,0,1,0}

```

The areas are accessed by a 1D array, where if the index is in a given area print " " otherwise print "#". Each area is determined by row and column position, `i/d` and `i%d`, respectively, then adjusted given `n`. Using `x`, both horizontally and vertically, gives the different areas as (0,0), (0,1), (1,0), and (1,1). If the area is (0,0) it should be " ", otherwise use "#".

```
for(;i<d*d;)
{
    Console.Write((x[i/d/n]+x[i%d/n]<1?" ":"#")+(i++%d==d-1?"\n":""));
}

```

(First time on code-golf, so comments or suggestions appreciated)

# Answer
> 0 votes
## TXR Lisp, ~~158 141 133 124~~ 122 bytes

```
(do each((i #1=(range* 0(* @1 5))))(each((j #1#))(pprint[[(repeat'(" # # ""#####"))(trunc i @1)](trunc j @1)]))(put-line))

```

Uncondensed:

```
(do each ((i #1=(range* 0 (* @1 5))))
  (each ((j #1#))
    (pprint [[(repeat '(" # # " "#####")) (trunc i @1)] (trunc j @1)]))
  (put-line))

```

Simply scale the basic 5x5 "bitmap" by backwards mapping from screen character coordinates into the texture.

Run:

```
1> (do each((i #1=(range* 0(* @1 5))))(each((j #1#))(pprint[[(repeat'(" # # ""#####"))(trunc i @1)](trunc j @1)]))(put-line))
#<interpreted fun: lambda (#:arg-01-0169 . #:rest-0168)>
2> [*1 1]
 # #
#####
 # #
#####
 # #
nil
3> [*1 3]
   ###   ###
   ###   ###
   ###   ###
###############
###############
###############
   ###   ###
   ###   ###
   ###   ###
###############
###############
###############
   ###   ###
   ###   ###
   ###   ###
nil
4> [*1 4]
    ####    ####
    ####    ####
    ####    ####
    ####    ####
####################
####################
####################
####################
    ####    ####
    ####    ####
    ####    ####
    ####    ####
####################
####################
####################
####################
    ####    ####
    ####    ####
    ####    ####
    ####    ####
nil

```

# Answer
> 0 votes
# Vyxal, 28 bytes

```
ð\#3*+2/2(ƛøm;øm)ƛƛ?*;ṅ;ƛ?(,

```

Try it Online!

What. A. Mess.

# Answer
> 0 votes
# Jelly, 10 bytes

```
⁾ #ŒḄ⁺xµ»þ

```

Try it online!

Another one using Zgarb's idea.

```
   ŒḄ         Palindromize
⁾ #           " #".
     ⁺        Palindromize it again. (" # # ")
      x       Repeat that by the input,
       µ»þ    then table it with itself by maximum.

```

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


title: Decode USB packets

text:
# Question
Title: Decode USB packets
*Inspired by this video by Ben Eater. This challenge forms a pair with Encode USB packets.*

The USB 2.0 protocol uses, at a low level, a line code called **non-return-to-zero** encoding (specifically, a variant called NRZI), in which a stream of bits is encoded into a stream of two electrical level states `J` and `K`. Decoding works as follows:

* Start with some initial state, which is either `J` or `K`
* For each state to be decoded:
    + If the state is different to the previous state, write a 0.
    + If the state is the same as the previous state, write a 1.

For this challenge, we will assume the encoding starts in state `J`.

However, it's not that simple: an additional process called **bit stuffing** takes place, which is designed to make it easier to detect if the signal has dropped out. After 6 consecutive 1 bits are written, a meaningless 0 bit is written to ensure the signal never stays in the same state (`J` or `K`) for too long. When decoding, you need to take this into account and remove the 0 bit that necessarily occurs after 6 consecutive 1s.

The full USB specification is available here on the USB website, or mirrored (and easier to access) here, but I'd caution you before reading it because it's extremely long and the pertinent information is hard to pin down.

## Task

Given a non-empty list of `J`s or `K` states as input, decode the string using the USB implementation of NRZI described above, and output a binary string.

You may assume the input will never contain invalid data with incorrect bit stuffing (i.e., it will never contain 7 consecutive 1s).

## Test-cases

```
Input              Output
=====================================
J                  1
K                  0
JKJKKJJ            1000101
KJKJKJKJ           00000000
JJJJJJKKK          11111111
KJJJJJJKJ          001111100
KJJJJJJJKJK        0011111100
KJJJJJJJKKJK       00111111100
KJJJJJJJKKKKKKKJKJ 0011111111111100
KJJJJJJJJKJ        (incorrect bit stuffing; does not need to be handled)
KJJJKKKJKJJJJKJJ   0011011000111001
KKKJJKJKJJJJKKJKJJJJKKJKJJJJKJKJKKKKJKKKJKKKKJJKJKKJJJJJKJJKKKKKJJJJKKKKJJJJKKKKJJJJKKKKJKKJJJJKJJJJJKJJKKKJJJJJKKKKJJKKJJJJKKJKJJJJKKJJKKKJKJJKJJJKJJKKJKKJJJJKJJJKJKKKJJJKKKKKJJJKKKJJKJJKKKKKJJJJKKKKJJJKJKJJKKKKJJKJKKKJKJJJKKKJJKJKJKKKKKKKJKKKKJJJKJKKKKKJJKKKJKKJKJJKKJKJJKKKKJJJJKJJJKKJKJJJJKKKKJKKKKJKKJJKKJJJJKKKJKKKKJJKKKJKJKKKJKJJJKKJJKJKK   01101000011101000111010001110000011100110011101000101111001011110111011101110111011101110010111001111001011011110111010101110100011101010110001001100101001011100110001101101111011011010010111101110111011000010111010001100011011010000011111101110110001111010110010001010001011101110011010001110111001110010101011101100111010110000110001101010001

```

## Rules

* The input should be a string or array, with the two states `J` and `K` being represented by two distinct values of your choice (within reason)
* The output should be a string or array of `1`s and `0`s or of `true`s and `false`s
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
# convey, 31 25 bytes

Takes `JK` as `01`.

```
>="*>0
",v+<"(6
{0>">>!`}

```

Try it online!

Compares `=` the string with itself with a `J` prepended `,0`. The middle loop just adds the comparisons to a counter (starting with 0) that gets reset on a 0. Only take `!` elements where the previous counter was less than 6 `(6`.
> 12 votes

# Answer
# Husk, 11 bytes

```
σḋ126ḋ63Ẋ=Θ

```

Try it online!

Takes an array of bits(0=J, 1=K), outputs an array of bits(formatted as string for convenience)

## Explanation

```
σḋ126ḋ63Ẋ=Θ
          Θ Prepend 0
        Ẋ=  map overlapping pairs by equality
σḋ126ḋ63    replace binary digits of 126 with binary digits of 63 (stolen from Luis Mendo)

```
> 8 votes

# Answer
# MATL, ~~15~~ 14 bytes

```
0ihd~126B63BZt

```

Input is an array with `0` for `'J'` and `1` for `'K'`.

Try it online! Or verify all test cases.

### Explanation

```
0       % Push 0
i       % Input: string
h       % Concatenate
d       % Consecutive differences
~       % Negate: converts nonzero to 0, and zero to 1. Gives a numeric vector (*)
126B    % Push 126, convert to binary. Gives [1 1 1 1 1 1 0]
63B     % Push 63, convert to binary. Gives [1 1 1 1 1 1]
Zt      % String replace (works for numeric vectors too). Replaces [1 1 1 1 1 1 0]
        % by [1 1 1 1 1 1] in (*)
        % Implicit display

```
> 6 votes

# Answer
# JavaScript (ES6), 54 bytes

```
s=>s.replace(/./g,a=>s^(s=a>"J")?i=i>5?'':0:++i/i,i=0)

```

Try it online!

Take input as a string of "J" / "K". Output a string with "0" and "1".

And `f=J=>J.replace(/./g,a=>J^(J=a>f)?i=i>5?'':0:++i/i,i=0)` is 54 bytes too.

---

# JavaScript (ES6), 44 bytes

```
s=>s.flatMap(a=>s^(s=a)?i=i>5&&[]:++i>0,i=0)

```

Try it online!

Take input as an array of false (for "J") and true (for "K"). Output an array of false and true.
> 4 votes

# Answer
# , ~~83~~ ~~76~~ 62 bytes

```
function(x)gsub('(1{6})0','\\1',Reduce(paste0,+!diff(c(0,x))))

```

Try it online!

Takes input as `0`(`J`) and `1`(`K`).

Outputs string of `1`s and `0`s.

Change of approach after looking at @Luis Mendo's answer.

```
function(x)    # function taking x as input
gsub(          # replace all occurences of
'(1{6})0',     # 6 ones and a zero
'\\1',         # with just 6 ones (first capturing group)
Reduce(paste0, # in a following vector collapsed to string
+!diff(c(0,x)) # negated differences of x with 0 prepended
               # converted from logical to numeric with unary +
               # this would be the output without bit stuffing
))

```
> 4 votes

# Answer
# C (gcc), ~~79~~ 76 bytes

-3 thanks to @ceilingcat

```
x;c;a(char*p){x=74;for(c=1;c*=*p==x,x=*p++;c=c>5?x=*p++,1:c+1)putchar(!!c);}

```

Try it online! Takes input as `J` and `K`, outputs with bytes `0x00` and `0x01` for `0` and `1`.

For output as numeric `0` and `1`, Try it online! for 78 bytes.

Encoder
> 4 votes

# Answer
# , 26 bytes

Takes in `JK` as `0 1`.

```
t#~0=_6|.(6$1)E.t=:2=/\0,]

```

Try it online!

```
t#~0=_6|.(6$1)E.t=:2=/\0,]
                       0,] prepend a J
                   2=/\    pair-wise equal
                t=:        store as t
         (6$1)E.           bitmask of places where 6 ones starts
     _6|.                  shifted by 6 bits
   0=                      negate
t#~                        take only truthy bits from t

```
> 3 votes

# Answer
# Vyxal, 16 bytes

```
1p-Ṫv¬ṅ\16*:0+$V

```

Try it Online!

```
1p               # Prepend a 1
  -              # Differences - truthy if unchanged, falsy if changed
   Ṫ             # Get rid of last
    v¬           # Vectorised not
      ṅ          # Joined
       \16*      # Six ones
           :     # Duplicate
            0+   # Append a 0 to the first
              $  # Swap
               V # Replace

```

Takes the difference of the list with a 1 prepended and the list itself, NOTted, to get the values. Then spend the remaining 10 bytes on doing the bit stuffing.
> 3 votes

# Answer
# PHP -F, 96 bytes

```
for($s=$r=$argn;$s[++$i]!='';)$r[$i]=+!abs($s[$i]-$s[$i-1]);echo str_replace(1111110,111111,$r);

```

Try it online!

Well, I.. tried.. to make it short.. hum!

takes a string of 0 (J) and 1 (K) as input
> 3 votes

# Answer
# Python 2, 77 bytes

```
lambda s:''.join((`+(x==y)`for x,y in zip('J'+s,s))).replace('1'*6+'0','1'*6)

```

Try it online!

-2 bytes thanks to @ovs
> 3 votes

# Answer
# 05AB1E, ~~13~~ 12 bytes

*-1 thanks to Kevin Cruijssen.*

```
0ìüQJƵPbD¨.:

```

Try it online! Uses `0` for `J` and `1` for `K`.

```
0ìüQJƵPbD¨.:  # full program
          .:  # replace all instances of...
     ƵP       # 126...
       b      # in binary...
          .:  # in...
    J         # joined...
  ü           # are all digits of each element in...
0             # literal...
 ì            # concatenated with...
              # implicit input...
   Q          # equal...
          .:  # with...
      ƵP      # 126...
        bD    # in binary...
          ¨   # excluding the last digit
              # implicit output

```
> 3 votes

# Answer
# Red, 79 bytes

```
func[x][p: s: 0 collect[foreach i x[s: any[all[s < 6 keep p = i s + 1]0]p: i]]]

```

Try it online!

Takes input as a block of \\$1\\$s and \\$0\\$s, outputs a block of booleans.

Test suite on TIO uses two additional transformation functions that allow reading inputs from JK-strings as in task specification and convert output to numbers for nicer visualization.
> 3 votes

# Answer
# Charcoal, 19 bytes

```
⪫⪪⭆θ⁼ι§⁺Jθκ⁺×1⁶0×1⁶

```

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

```
   θ                Input string
  ⭆                 Map over characters and join
        J           Literal string `J`
       ⁺            Concatenated with
         θ          Input string
      §             Indexed by
          κ         Current index
    ⁼               Equals
     ι              Current character
 ⪪                  Split on
             1      Literal string `1`
            ×       Repeated
              ⁶     Literal `6`
           ⁺        Concatenated with
               0    Literal string `0`
⪫                   Join with
                 1  Literal string `1`
                ×   Repeated
                  ⁶ Literal `6`
                    Implicitly print

```
> 2 votes

# Answer
# Stax, 16 bytes

```
Å3≈àE∩◄σ←π<δô╝ìà

```

Run and debug it

takes in a string/array of bytes `0x00` for J and `0x01` for K.

Outputs a string, same as the given testcases.

Sadly, this 14 byte program doesn't work since stax auto-replaces null bytes with spaces.
> 2 votes

# Answer
# K (ngn/k), 25 bytes

```
*|+(126=2/')_7':(&6),0=':

```

Try it online!

Takes `J` as `0`, and `K` as `1`. Returns a list of `0`s and `1`s.

* `0=':` run an equals-each-prior, seeded with `0` on the (implicit) input, handling the non-return-to-zero part
* `7':(&6),` prepend 6 `0`s to the input, then slice into length-7 sliding windows. the first 6 slices will contain some dummy `0`s
* `(126=2/')_` drop chunks of `1 1 1 1 1 1 0`, i.e. where the last value in the chunk is a dummy `0` inserted for bit stuffing purposes
* `*|+` return the last value of each chunk (saves a byte over `*'|'`)
> 2 votes

# Answer
# JavaScript (Node.js), 61 bytes

```
n=>n.replace(/./g,(e,i)=>1-e^n[i-1]).replace(/1{6}0/g,111111)

```

Try it online!

I have tried to make sure it outputs numbers.

-10 bytes by pxeger
> 1 votes

# Answer
# Jelly, 14 bytes

```
Ż⁼Ɲ0ȯ1×‘ʋ7Ƒ?ɼƇ

```

Try it online!

Takes `J` and `K` as `0` and `1`.
> 1 votes

# Answer
# Retina 0.8.2, 31 bytes

```
(.)(?<=(\1.|^J)?)
$#2
1{6}0
6$*

```

Try it online! Link includes test cases. Explanation:

```
(.)(?<=(\1.|^J)?)

```

For each letter, look behind for a possible duplicate or a leading `J`.

```
$#2

```

If it was then replace it with a `1` otherwise replace it with a `0`.

```
1{6}0
6$*

```

Remove the `0` that appears after a run of six `1`s.
> 1 votes

# Answer
# Jelly, 14 bytes

```
ŻI¬“~?‘B¤œṣjƭƒ

```

Try it online!

A monadic link taking the argument as a vector of 0 (=J) and 1 (=K) and returning a vector of 0 and 1.
> 1 votes

---
Tags: code-golf, binary, encoding
---


title: Combinatorial Pipes

text:
# Question
Title: Combinatorial Pipes
You're a plumber working on a house, and there's some pipes that must be connected at weird angles. You have 8°, 11.25°, 22.5°, 45°, and 90° fittings at your disposal, and you want to use as few as possible to match the angle as closely as possible.

# Goal

* Match the desired angle as closely as possible, with as few fittings as possible. It can be over or under the desired angle.
* Accuracy is more important than the number of fittings
* In the case of two different sets of fittings with the same resulting angle, whichever has the fewest number of fittings should be selected.
* If the two sets use different fittings, match the same angle, and have the same number of fittings, either may be chosen.
* Your fittings cannot add up to greater than 360 degrees (i.e. no looping all the way around)

# Input

Your input is a random integer between (non-inclusive) 0° and 180°, which represents the desired angle.

# Output

Your output should be an array where \[0\]-\># of 8° fittings, \[1\]-\># of 11.25° fittings, etc. If your language does not support arrays, you may output a comma separated list, where the first value represents the number of 8° fittings, and so on and so forth.

**Test Cases**

```
90° ->[0,0,0,0,1]
24°-> [3,0,0,0,0] ([0,0,1,0,0] uses less fittings, but is less accurate and therefore incorrect)
140°->[2,1,1,0,1]
140°->"2,1,1,0,1" acceptable if language does not support arrays

```

# Scoring

Lowest byte count for each language wins a high five from me if we ever bump into each other (and the challenge).

# Answer
# Jelly, 21 bytes

```
Ḷṗ5SÞðḋ90H3Ð¡;8¤ạðÞḢṚ

```

Try it online!

**Note** \- after Nick Kennedy's golfs, this answer is actually identical to Jonathan Allan's answer, which they arrived at independently. Make sure to upvote them.

-9 bytes thanks to Nick Kennedy by rewriting the conversion from counts to total angle

```
ḶṗSÞ5ðḋ90H3Ð¡;8¤ạðÞḢṚ  Main Link
Ḷ                      Lowered range; [0, 1, ..., N-1]
 ṗ5                    Cartesian product; size 5 lists of the above elements
   SÞ                  Sort by sum
     ð           ðÞ    Sort by:
                ạ      - absolute difference of the following and the input:
      ḋ                - dot product with
       90H3Ð¡;8¤       - [90, 45, 22.5, 11.25, 8] via the following
       90                - 90
          3Ð¡            - repeat 3 times and collect results:
         H               - halve
             ;8          - append 8
                   Ḣ   take the first one (since it'll already be sorted by count and it's stable)
                    Ṛ  reverse it

```
> 6 votes

# Answer
# Jelly, 21 bytes

```
Ḷṗ5SÞḋ90H3Ð¡;8¤ạɗÞ⁸ḢṚ

```

A monadic Link that accepts an integer in \\$\[0,180\]\\$ and yields a list of the five pipe counts in the prescribed order.

**Try it online!** although it'll time out for inputs above \\$15\\$ :(

### How?

Builds all selections of pipes consisting of less than `input-angle` of each pipe, sorts these by their number of pipes, then (stable) sorts by the difference between the angle-sum and `input-angle` and yields the first.

```
Ḷṗ5SÞḋ90H3Ð¡;8¤ạɗÞ⁸ḢṚ - Link: angle, A
Ḷṗ5                   - (A) Cartesian product 5 -> all selections of the five pipes with
                                                   up to A-1 of each pipe
   SÞ                 - sort by sum (number of pipes)
                 Þ    - sort (the elements X of that) by:
                ɗ ⁸   -   last three links as a dyad - f(X, A)
              ¤       -     nilad followed by links as a nilad:
      90              -       90
         3Ð¡          -       collect & repeat three times:
        H             -         halve -> [90, 45, 22.5, 11.25]
            ;8        -       concatenate 8 -> [90, 45, 22.5, 11.25, 8]
     ḋ                -     (X) dot-product (that)
               ạ      -     (that) absolute-difference (A)
                   Ḣ  - head
                    Ṛ - reverse (to the prescribed order of pipe counts)

```
> 4 votes

# Answer
# , ~~95~~ ~~88~~ ~~87~~ 86 bytes

*Edit: -1 byte thanks to pajonk*

```
function(a,b=expand.grid(rep(list(23:0),5)))b[order((c(8,90/2^(3:0))%*%t(b)-a)^2)[1],]

```

Try it online!

**Ungolfed code**

```
fittings=
function(a){                        # a=desired angle
b=expand.grid(rep(list(23:0),5))    # b=all combinations of 5 elements of 23..0 (note: largest-to-smallest - see below)
                                    # (23 is number of smallest (8-degree) fittings needed to get over 180 degrees)
c=colSums(t(b)*c(8,2^(-2:1)*45))    # c=the total angle made by each combination of fittings
d=which.min((d-a)^2)                # d=the first combination that minimized the absolute difference to angle a
                                    # (we take the square to save a byte getting the absolute difference,
                                    # and we automatically get the combination with the smallest numbrer of fittings
                                    # since we constructed the combinations largest-to-smallest)
return(b[d,])                       # finally, return that element of b

```
> 4 votes

# Answer
# Jelly, 22 bytes

```
ṗⱮẎSạ¥ÞḢċⱮ⁸
90H3Ð¡;8Ṛç

```

Try it online!

A pair of links which takes a single argument, the number of degrees to match, and returns a list of 5 integers. Hopelessly slow for increasing values, but should theoretically work for all of the required range.

This is a much more efficient implementation but is three bytes longer.
> 4 votes

# Answer
# Julia 0.7, 93 bytes

```
!x=minimum(i->((4x-[32,45,90,180,360]⋅i)^2,sum(i),i),Iterators.product(fill(0:22,5)...))[3]

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 129 bytes

```
f=(n,a=[0,0,0,0,0],c=e=C=1/0)=>n<(n*n<e|n*n==e&c<C&&[e=n*n,C=c,o=a])?o:a.map((_,i,[...a])=>f(n-(i?90/(16>>i):8),a,-~c,a[i]++))&&o

```

Try it online!

### Commented

```
f = (                    // f is a recursive function taking:
  n,                     //   n = input
  a = [0, 0, 0, 0, 0],   //   a[] = pipe counters
  c =                    //   c = current number of pipes
  e =                    //   e = best (smallest) squared error
  C = 1 / 0              //   C = number of pipes for the best solution
) =>                     //
n < (                    //
  n * n < e |            // if the current error is less than the best error
  n * n == e & c < C &&  // or they're equal but we're using less pipes:
  [ e = n * n,           //   update the best error
    C = c,               //   update the best count
    o = a                //   update the output
  ]                      // if e, C and o have been updated, we compare n with
                         // an array, which is always falsy
) ?                      // otherwise, we test whether n is negative:
  o                      //   in which case we return o[]
:                        // else:
  a.map(                 //
  (_, i, [...a]) =>      //   for each value at position i in a[], using a copy
                         //   of a[]:
    f(                   //     do a recursive call:
      n - (              //       subtract from n:
        i ?              //         if i is not equal to 0:
          90 / (16 >> i) //           11.25, 22.5, 45 or 90
        :                //         else:
          8              //           8
      ),                 //
      a,                 //       pass the copy of a[]
      -~c,               //       increment c
      a[i]++             //       increment a[i]
    )                    //     end of recursive call
  ) && o                 //   end of map(); return o[]

```
> 3 votes

# Answer
# Charcoal, 60 bytes

```
≔↔⁻ＮＥφ⁺×¹¹·²⁵﹪ι¹⁶×⁸÷ι¹⁶θ≔Ｅ⌕Ａθ⌊θ…⮌⊞Ｏ↨⁺¹⁶ι²÷ι¹⁶¦⁵θＩ⊟Φθ⁼Σι⌊ＥθΣλ

```

Try it online! Link is to verbose version of code. Outputs using Charcoal's default array format i.e. each element on its own line. Explanation:

```
≔↔⁻ＮＥφ⁺×¹¹·²⁵﹪ι¹⁶×⁸÷ι¹⁶θ

```

Calculate the possible angles using sets of up to `999` 8° fittings and optionally one each of each of the other fittings, and see how closely they compare to the input.

```
≔Ｅ⌕Ａθ⌊θ…⮌⊞Ｏ↨⁺¹⁶ι²÷ι¹⁶¦⁵θ

```

Find the indices of the most accurate sets and calculate the fittings corresponding to each of those indices.

```
Ｉ⊟Φθ⁼Σι⌊ＥθΣλ

```

Output the last set with the fewest fittings.
> 2 votes

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


title: A Snake, A Camel And A Kebab

text:
# Question
Title: A Snake, A Camel And A Kebab
As many of you will know, almost every programming language has a standard casing system; unfortunately, we have not been able to agree on a singular system to use and now must frequently switch between camelCase, snake\_case, PascalCase and kebab-case.

Now I know what you're thinking... wouldn't it be nice if we had a program that could convert from one casing to another?
Well - soon we're going to have plenty!!! *(This is where you come in)*

## Challenge

You're job is to write a program/function that will take an input string, and a casing system. It will then print/return the converted string.

### Inputs:

You're program will receive two inputs, an alphabetic string that is to be converted and a string that **will always** be one of `kebab` `camel` `pascal` or `snake`.

### Outputs:

You're program should output a string that conforms to the new casing. You can assume the input string is valid and will only conform to one of the casings (*i.e. it won't be* `mixed_Casing`).
As most programming languages prefer lowercase variable names, you should convert all letters to lowercase unless it is needed to be upper case for the casing requirements.

* Snake Case: All letters are lower case, with underscores separating words.
* Kebab Case: All letters are lower case, with hyphens separating words.
* Camel Case: The first letter of every word after the first is capitalized, with no spaces.
* Pascal Case: The first letter of every word is capitalized, with no spaces.

## Test Cases:

```
"aJavaVariable", "snake" = "a_java_variable"
"a_python_variable", "kebab" = "a-python-variable"
"golf", "camel" = "golf"
"camelToPascal", "pascal" = "CamelToPascal"
"PascalToCamel", "camel" = "pascalToCamel"
"", "snake" = ""
"doHTMLRequest", "kebab" = "do-h-t-m-l-request"

```

```
<!-- Run the snippet to see the leaderboard. Report any bugs to @ozewski on Github. -->    <iframe src="https://ozewski.github.io/ppcg-leaderboard/?id=216396" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>
```

# Answer
> 6 votes
# JavaScript (Node.js),  ~~127 126~~  120 bytes

Expects `(string)(type)`.

```
s=>t=>s.split(/_|-|(?=[A-Z])/).map((s,i)=>(k=parseInt(t,29)%5,(b=Buffer(s))[0]=b[0]&95|(k+!i>1)<<5,b)).join(['-_'[k-3]])

```

Try it online!

### How?

The type string \\$t\\$ is converted to an ID \\$k \in \[0..4\]\\$ by parsing it as a base-29 value and applying a modulo \\$5\\$:

```
 type     | base 29 -> dec. | mod 5
----------+-----------------+-------
 "pascal" |    520544830    |   0
 "camel"  |      8750191    |   1
 "kebab"  |     14496618    |   3
 "snake"  |     20373819    |   4

```

This formula was chosen because it puts *pascal* next to *camel* and *kebab* next to *snake*, allowing the following expressions:

* Put the leading character in uppercase if 1) the type is *pascal* (\\$k=0\\$), or 2) the type is *camel* (\\$k=1\\$) and this is not the first word (\\$i\neq 0\\$):

```
(b = Buffer(s))[0] = b[0] & 95 | (k + !i > 1) << 5

```
* Join with `"-"` for *kebab* (\\$k=3\\$), `"_"` for *snake* (\\$k=4\\$) or an empty string otherwise:

```
.join(['-_'[k - 3]])

```

# Answer
> 4 votes
# Perl 5 `-lF'_|-|(?=[A-Z])'`, 69 bytes

```
$,=('_','-')[$c=3-ord(<>)%14%7];say map$c>1&&$i++||$c>2?ucfirst:lc,@F

```

Try it online!

# Answer
> 4 votes
# Retina 0.8.2, 81 bytes

```
T`l\_-`L_`^.|_.|-.
\B(?=[A-Z].*¶s)
_
\B(?=[A-Z].*¶k)
-
T`L`l`^.(?!.*¶p)|_.|-.
1G`

```

Try it online! Takes input on separate lines but link includes test suite that splits the input on commas. Explanation:

```
T`l\_-`L_`^.|_.|-.

```

Uppercase the first letter and any letters after `_` or `-`, which get deleted. This gives you Pascal case.

```
\B(?=[A-Z].*¶s)
_
\B(?=[A-Z].*¶k)
-

```

Prefix interior capital letters with `_` (for snake case) or `-` (for kebab case).

```
T`L`l`^.(?!.*¶p)|_.|-.

```

Except for Pascal case, lowercase the first letter, plus (since we just marked them) all the letters for snake or kebab case.

```
1G`

```

Delete the second input (the case) leaving the result.

# Answer
> 3 votes
# 05AB1E, ~~50~~ ~~48~~ 47 bytes

```
.ªÐáмÙ¡¸˜Dgi`.œ.ΔD™Q]l²ÇO5%©2‹i„_-®èýë™J®4Qićlì

```

Try it online or verify all test cases.

**Explanation:**

```
.ª           # Sentence capitalize the first (implicit) input-string, which titlecases
             # without removing existing capital letters
  Ð          # Triplicate that string
   á         # Only leave its letters
    м        # Remove all those letters (so only "-"/"_" are left, if any)
     Ù       # Uniquify the potential multiple "-"/"_" to a single character
      ¡      # Split the string on this character
       ¸˜    # Wrap it into a list, and flatten
Dg           # Get the length of a copy of this list
  i          # If this length is 1 (thus no "-"/"_" were present):
   `         #  Push the string to the stack to remove the wrapped list
    .œ       #  Get all partitions of this string
      .Δ     #  Find the first partition which is truthy for:
        D    #   Duplicate the list of substrings
         ™   #   Titlecase each string
          Q  #   Check that the two lists are equal
  ]          # Close both the find_first and if-statement
   l         # Lowercase each string in the list
    ²        # Push the second input-string
     Ç       # Convert it to a list of codepoint integers
      O      # Sum those
       5%    # And take modulo-5 on it (snake=0; kebab=1; camel=4; pascal=3)
         ©   # Store this in variable `®` (without popping)
2‹i          # If it's smaller than 2 (thus snake or kebab):
   „_-       #  Push string "_-"
      ®è     #  (0-based) index `®` into this string
        ý    #  Join the list by this character as delimiter
  ë          # Else (thus camel or pascal):
   ™         #  Titlecase each string in the list
    J        #  Join them together
     ®4Qi    #  If `®` equals 4 (thus camel):
         ć   #   Extract head; pop and push remainder-string and first character
             #   separated to the stack
          l  #   Lowercase this first character
           ì #   And then prepend it back in front of the remainder-string
             # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Ruby,  ~~112~~  103 bytes

```
->s,c{x=s.split(/(?=[A-Z])|-|_/).map{x=c[5]||x&&c<?d?_1.capitalize: _1.downcase}*(c>?s??_:c[?k]??-:'')}

```

Try it online! (+1 byte because TIO doesn't support ruby 2.7's `_1`)

Multiple bytes saved thanks to @Dingus

* `x` tracks whether it's not the first iteration
* `c[5]` asks whether it's `"pascal"` (the only one with 6 letters)
* `c>?s` asks if `c` is greater than `'s'`, this is only true for `"snake"`, etc.
* the multiplication at the end is equivalent to `join`

# Answer
> -1 votes
# Laravel/PHP, 264 bytes

It accepts a GET request to `/{string}/{kebab|camel|pascal|snake}` as input, and output is done via dumping. Bytes are counted for the one file that I wrote.

web.php:

```
<? use Illuminate\Support\Str;Illuminate\Support\Facades\Route::get('/{a}/{b}',function(){$a=str_replace("_","-",request()->a);switch(request()->b[0]){case'p':dd(Str::studly($a));case'c':dd(Str::camel($a));case'k':dd(Str::kebab($a));default:dd(Str::snake($a));}});

```

I wrote/ran this on PHP Sandbox and verified it with PHPUnit tests like so (must be run one at a time!):

```
$this->get('/aJavaVariable/snake');
$this->get('/a_python_variable/kebab');
$this->get('/golf/camel');
$this->get('/camelToPascal/pascal');
$this->get('/PascalToCamel/camel');
$this->get('//snake'); // 404 (no output)
$this->get('/doHTMLRequest/kebab');

```

Could probably save bytes by using Laravel \< 6 and the helpers str\_\*, but didn't feel like verifying it would run. Does anyone see any other shortcuts?

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


title: A triangle of numbers

text:
# Question
Title: A triangle of numbers
# Challenge

Make a triangle of numbers like below.

# How to?

Let say we get a numbers in the form of ab, for example `12`. We then create a triangle like below:

Sorry for my bad drawing!

First we have `12`, and we take sum of the two numbers `1` and `2`, which is `3`. In case the sum of two numbers are greater than 9, we just take the second number from the sum. For example if we have `49` then the sum will be `4+9=13`, we just take 3.

`12` is the number we input, which is line 1, `3` \- its sum, is line 2. We now create line 3 by cross-adding. For example, Line 1 contain `12` is split to `1` and `2`, line 2 contain 3, so the line 3's first element will be the second element of line 1 plus line 2, and the second element of line 3 will be the first element of line 1 plus line 2. And remember, if the sum is greater than 9, just take the second number of the sum just like explained.

Now we come to line 4: the first element of line 4 now is calculated by line 2 plus the first element of line 3, and the third element of line 4 is line 2 plus the second element of line 3. The second element of line 3 - the middle, is the sum of all element in the previous line, which is line 3.

Now we come to line 5. Like line 4, the first and the last element of line 5 is calculated by the line 3's first element plus line 4 is first element and line 3's last element and line 4's last element. And the middle element of line 5, of course is the sum of all element in line 4. Now come to the second and the fourth element. You may notice that line 4 started to have the *middle element*, and the line 5's second element is just line 3's last element plus that middle element, and the line 5's fourth element is line 3's first element plus that middle element.

Line 6 is the same as line 5. And from now on, all the line just has 5 elements :)

# Rule

* The integer ab will be a positive integer and contain only two digits (from 10 -\> 99) Program will let user input two line: the first line is the ab number, and the second line is the number of lines they want to output.
* The program will output the triangle as a bunch of numbers. See the example in the Output section below.
* The number of lines will always be greater than or equal to 5.
* This is , so the shortest code in bytes wins!

# Output example

If we input:

```
12
6

```

It should print out:

```
12
3
54
897
33441
11528

```

Have fun and good luck!

## Note that I will select the winner after 4 more hour since the time edited.

# Answer
# 05AB1E, 53 bytes

```
ÐˆO©D¸ˆ+Âˆ®+®3*ªÀ©ˆI4-F®н®ÅsD®Os®θ)¯¨θÂ‚€н0ª5∍+©ˆ}¯T%

```

Try it online!

This uses lists of digits as I/O, 56 bytes with the format in the challenge. The output is built row by row in the global array:

```
Ð                    # push three copies of the input [w, a]
 ˆ                   # append one copy to the global array
  O©                 # take the sum s=w+a and store it in the register
    D¸               # duplicate s and wrap in a list
      ˆ              # append [s] to the global array
       +             # add s to each [w, a]
        Â            # duplicate and reverse the copy
         ˆ           # append [a+s, w+s] to the global array
          ®+         # add s to [w+s, a+s]
            ®3*      # push 3*s
               ª     # append: [w+2*s, a+2*s, 3*s]
                À    # rotate left
                 ©   # store in the register, from now the register always stores the last row
                  ˆ  # append [a+2*s, 3*s, w+2*s] to the global array

I4-                  # push second input - 4
   F              }  # iterate this many times
    ®н               # get the first value of the last row y
      ®Ås            # middle value of last row
          ®O         # sum of last row
         D  s        # middle value again
             ®θ      # last value of last row
               )     # wrap all these numbers into a list      [y[0], y[m], sum(y), y[m], y[-1]]
    ¯¨θ              # push second-to-last row of global array (x)
       Â‚            # pair with its reverse                   [x, x[::-1]]
         €н          # push first element for each             [x[0], x[-1]]
           0ª        # append a 0                              [x[0], x[-1], 0]
             5∍      # extend to length 5                      [x[0], x[-1], 0, x[0], x[-1]]
               +     # add both lists element-wise             [y[0]+x[0], y[m]+x[-1], sum(y)+0, y[m]+x[0], y[-1]+x[-1]]
                ©ˆ   # save new row in register and add to global array

¯                    # push the global array
 T%                  # each number modulo 10

```
> 2 votes

# Answer
# Python 3, ~~195~~ ~~184~~ 181 bytes

-3 bytes thanks to MarcMush!

Based on OP's code

```
def f(a,b):w=a//10;s=w+a;t=[[w,a],[s],[a+s,s+w],[2*s+a,s*3,2*s+w]];exec('*_,(x,*_,z),y=t;Y=y[len(y)//2];r,*t=t+[[x+y[0],z+Y,sum(y),x+Y,z+y[-1]]];print(*[x%10for x in r],sep="");'*b)

```

Try it online!
> 4 votes

# Answer
# Charcoal, 102 bytes

```
≔Ｉ⪪⮌Ｓ¹θ⊞υ⮌θ⊞υ⟦Σθ⟧≧⁺Σθθ⊞υθ≔⁺§υ¹θζ≔Ｅζ⁺ι§ζ⊕κη⊞υη≔ηζＦ⁻Ｎ⁴«≔⁺⊞ＯＥθ⁺κ§ηλΣζＥθ⁺κ§η⊕λζ⊞υζ≔Φη¬﹪λ²θ≔Φζ¬﹪λ²η»Ｅυ⭆ι﹪λχ

```

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

```
≔Ｉ⪪⮌Ｓ¹θ

```

Input the two digits, reverse them, split them, and cast to integer.

```
⊞υ⮌θ

```

Push the reverse of this (i.e. the original integers) to the list of results.

```
⊞υ⟦Σθ⟧

```

Push the sum as a list to the list of results, giving the second row.

```
≧⁺Σθθ

```

Add the two together, giving the third row. This is also the first row that takes part in diagonal calculations.

```
⊞υθ

```

Push this to the list of results.

```
≔⁺§υ¹θζ

```

Concatenate the second and third rows.

```
≔Ｅζ⁺ι§ζ⊕κη

```

Rotate the result and add it elementwise to produce the fourth row. This is also the second row that takes part in diagonal calculations.

```
⊞υη

```

Push this to the list of results.

```
≔ηζ

```

This is also the last result so far.

```
Ｆ⁻Ｎ⁴«

```

For the remaining rows...

```
≔⁺⊞ＯＥθ⁺κ§ηλΣζＥθ⁺κ§η⊕λζ

```

Calculate the diagonal sums before and after the sum of the previous row, thus producing the next row.

```
⊞υζ

```

Push this to the list of results.

```
≔Φη¬﹪λ²θ≔Φζ¬﹪λ²η

```

Shift all the rows back one, removing elements that do not participate in the diagonal sums.

```
»Ｅυ⭆ι﹪λχ

```

Output just the last digit of every element.
> 3 votes

# Answer
# Python 3, ~~517~~ ~~501~~ ~~410~~ 408 bytes

-32 bytes thanks to mypetlion

-3 bytes thanks to Dion

After fixing a bunch of bugs :), i come up with this:

```
a=int(input());b=int(input());t=[[a//10,a%10]];t.append([(t[0][0]+t[0][1])%10]);t.append([(t[0][1]+t[1][0])%10,(t[0][0]+t[1][0])%10]);t.append([(t[1][0]+t[2][0])%10,(t[2][0]+t[2][1])%10,(t[1][0]+t[2][1])%10])
for i in range(4,b):x=t[i-2];y=t[i-1];t.append([(x[0]+y[0])%10,(x[-1]+y[len(y)//2])%10,sum(y)%10,(x[0]+y[len(y)//2])%10,(x[-1]+y[-1])%10])
for i in range(b):
 for j in t[i]:print(end=str(j))
 print()

```

Input and output:

```
D:\Data\dev>python codegolf1.py
12
6
12
3
54
897
33441
11528

```

The first `12` and `6` is the input, all other number is output.
> 3 votes

# Answer
# Jelly, 54 bytes

```
.ị+U,$€Ḣ$}Ṛṭ@FṖS;`ʋ
“½“¿“€“ç!‘Dṫ-ç@/ṭƊ⁸¡EÐḟUṚ;@Ʋ€ḋ%⁵ḣ⁸

```

Try it online!

A set of links taking the left argument as the number of rows and the right as the initial integers. Returns a list of lists of integers.

If the IO is inflexible, here is a solution for 56 bytes that takes the arguments in the opposite order, the starting point as a single integer and prints the number triangle to STDOUT.

## Explanation

### Helper link

Take the previous line on the left and the last but one on the right and generate the next line

```
.ị                  | Last and first items in the most recent line
  +     $}          | Add to the following applied to the last but one line:
   U,$€             | - Pair a reversed version of each list member to itself
       Ḣ            | - And then just take the first of these
          Ṛ         | Reverse order
           ṭ@     ʋ | Tag on the following (effectively applied to the previous line)
             F      | - Flatten
              Ṗ     | - Remove last
               S    | - Sum
                ;`  | - Concatenate to itself

```

### Main link

```
“½“¿“€“ç!‘                          | [[10],[11],[12],[23,33]]
          D                         | Convert to decimal digits [[[1,0]],[[1,1]],[[1,2]],[[2,3],[3,3]]]
                 Ɗ⁸¡                | Repeat the following the number of times indicated by the original left argument
           ṫ-                       | - Take the last two list members
             ç@/                    | - Call the helper link using the last line as the left argument and the penultimate one as the right
                ṭ                   | - Tag the new line onto the end of the list
                           Ʋ€       | For each line:
                    EÐḟ             | - Filter out items where both members of the list are equal
                       U            | - Reverse each list member
                        Ṛ           | - Reverse order of list members
                         ;@         | - Concatenate to existing list
                             ḋ      | Dot product with starting integers
                              %⁵    | Mod 10
                                ḣ⁸  | Take the number of lines indicated by the original left argument

```
> 3 votes

# Answer
# JavaScript (SpiderMonkey), 226 bytes

```
R=readline
v=R()
h=(n,k=--n<4?n:5,g=(i,j,s=`1
12
233
35845
51508`.split`
`[i])=>s?s[j]*v[0]+v*s[(i<3?i:4)-j]:j-2?g(i-2,j%3*4)+g(i-1,j&4|j%2*2):(v- -v[0])*'093859835433'[i%12])=>k--?h(n,k)+g(n-1,k)%10:n?h(n)+`
`:v
print(h(R()))

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6),  ~~203~~  198 bytes

Expects `(N)(n)`, where `N` is the initial number as a string and `n` is the number of lines.

```
N=>n=>(s=7,g=k=>k<n?`${F=n=>n>k-2?k-n:F(++n)+F(++n),A=[d=s+F(1),b=F``,c=s+F(2),s+=a,a=F(-1)],[41,1,14,134][k]||10324}
`.replace(/./g,n=>(A[n]*N[0]+A["24031"[n]]*N)%10)+g(k+1,a+=k>3?b+c+d:b):'')(a=0)

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~295~~ ~~292~~ ~~289~~ ~~281~~ 272 bytes

```
a,b=map(int,input())
e=[[a,b],[a+b],[b+a+b,a+a+b],[3*b+a+a,3*a+3*b,3*a+b+b]]
for i in range(3,int(input())-1):f=e[i];e.append([e[i-1][0]+f[0],e[i][len(e[i])//2]+e[i-1][-1],sum(f),f[len(f)//2]+e[i-1][0],e[i-1][-1]+f[-1]])
for i in e:
 for j in i:print(j%10,end="")
 print()

```

Try it online!

-11 bytes thanks to @raspiduino

-9 bytes thanks to @MarcMush
> 1 votes

# Answer
# Julia 0.7, <sup>~~162~~ ~~159~~ ~~153~~ ~~148~~</sup> 144 bytes

-6 bytes from ovs's answer

```
!x=x.%10
~L=L[end]
(a,b)$n=.![(a,b);c=a+b;((b,a).+c,(b,c,a).+2c)>n]
(l,L)>n=n<3?l:[l;(L,(l[1]+L[1],(N=L[end÷2+1])+~l,sum(L),N+l[1],~l+~L))>n-1]

```

Try it online!

takes the initial number as 2 numbers and output is a list of tuples

+10 bytes with stricter I/O
> 1 votes

# Answer
# Haskell, 205 bytes

```
l=last
x%y|m<-y!!div(length y)2=x:y%[x!!0+y!!0,l x+m,sum y,x!!0+m,l x+l y]
a#b|s<-a+b=[a,b]:[s]:[s+b,a+s]%[3*s-a,3*s,3*s-b]
main=do[a,b]<-getLine;n<-readLn;mapM(putStrLn.map(l.show))$take n$read[a]#read[b]

```

Try it online!
> 1 votes

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