title: Translate English to Corpus

text:
# Question
Title: Translate English to Corpus
The Corpus are a fictional faction from the popular video game Warframe who have a somewhat interesting language.

Whilst other factions in the game such as the Grineer have some logic behind their language, the Corpus is simply a lossy substitution of the English language.

All Corpus words are the same as their English counterparts, except with the following alphabetical mappings:

This causes some problems with pronunciation as:

`yes` becomes `yey`
`say` becomes `yay`
`yay` becomes `yay`
`sassy` becomes `yayyy`
`case` becomes `yaye`

Here's a text version of the mappings:

```
a -> a
b -> t
c -> y
d -> p
e -> e
f -> t
g -> j
h -> k
i -> i
j -> t
k -> k
l -> p
m -> s
n -> t
o -> o
p -> k
q -> r
r -> t
s -> y
t -> p
u -> u
v -> t
w -> j
x -> k
y -> y
z -> b

```

# The challenge

Given text using the English alphabet, output its Corpus translation.

For example, the text `Hello, World!` becomes `Keppo, Jotpp!` in Corpus

### The Rules

* Input will only consist of ASCII printable characters
* Input text may contain whitespace and punctuation, these must be preserved
* Capitalization of letters must be preserved
* This is so naturally, fewest bytes wins!

## The Testcases

Test cases are separated with `<===========>`, with a blank line between input and expected output

```
Hello, World!

Keppo, Jotpp!
<===========>
Yes

Yey
<===========>
TestcaSe

PeypyaYe
<===========>
Programming Puzzles and Code Golf

Ktojtassitj Kubbpey atp Yope Jopt
<===========>
This text has a
newline in it

Pkiy pekp kay a
tejpite it ip
<===========>
Corpus language best language

Yotkuy patjuaje teyp patjuaje
<===========>
Strip the flesh! Salt the wounds!

Yptik pke tpeyk! Yapp pke joutpy!
<===========>
"Install Warframe" they said, "It'll be fun" they said

"Itypapp Jatttase" pkey yaip, "Ip'pp te tut" pkey yaip
<===========>
What the **** did you just ****ing say about me, you little *****?
I'll have you know I graduated top of my class in the Navy Seals,
and I've been involved in numerous secret raids on Al-Quaeda,
and I have over 300 confirmed kills.

Jkap pke **** pip you tuyp ****itj yay atoup se, you pipppe *****?
I'pp kate you ktoj I jtapuapep pok ot sy ypayy it pke Taty Yeapy,
atp I'te teet ittoptep it tusetouy yeytep taipy ot Ap-Ruaepa,
atp I kate otet 300 yottitsep kippy.

```

### The Bonus

If you also include an audio recording (or video with audio) of you pronouncing each of the testcase's Corpus translations, you may multiply your bytecount by `1` as a reward.

# Answer
> 8 votes
# Bash \+ coreutils, 46

```
tr b-zB-Z ${a=typetjkitkpstokrtyputjkyb}${a^^}

```

Try it online!

# Answer
> 4 votes
# T-SQL, 107 Bytes

```
SELECT TRANSLATE(v,'bcdfghjlmnpqrstvwxzBCDFGHJLMNPQRSTVWXZ',
                   'typtjktpstkrtyptjkbTYPTJKTPSTKRTYPTJKB')FROM t

```

Line break and indent are for readability only.

Uses the SQL 2017 function `TRANSLATE` for character replacement.

Unfortunately had to put (almost) the entire alphabet in there *twice* to maintain casing. There are probably better ways, maybe something that handles the **t**'s as a group, but this worked for me.

Input is via a pre-existing table **t** with varchar column **v**, per our IO rules.

In this case the table must be created using a *case-sensitive collation*, either by running on a case-sensitive server, or by using the `COLLATE` keyword (not counted toward character total):

```
CREATE TABLE t(v varchar(999) COLLATE Latin1_General_CS_AS)

```

# Answer
> 4 votes
# 05AB1E, 24 bytes

```
ži.•ÜÁ©;«ìñä°ÔG·ÖYΘ•Du«‡

```

Explanation:

```
                       ‡   transliterate
ži                         a-zA-Z with
  .•ÜÁ©;«ìñä°ÔG·ÖYΘ•       atypetjkitkpstokrtyputjkyb
                    Du«    concatenated with itself, uppercased

```

Try it online!

# Answer
> 4 votes
# Charcoal, 42 bytes

```
≔”$⌊∧Ｔ-¶I^F⁷ü@n⁹γ›7η”η⭆θ⎇№β↧ι§⎇№βι↧ηη⌕β↧ιι

```

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

```
≔                       Assign
 ”$⌊∧Ｔ-¶I^F⁷ü@n⁹γ›7η”  Compressed string `ATYPETJKITKPSTOKRTYPUTJKYB`
                     η  To variable

 θ                      Input string
⭆                       Map over characters and join
  ⎇                     If
    β                   Lowercase alphabet
   №                    Contains
      ι                 Current character
     ↧                  Lowercased
                        (Then)
        ⎇               If
          β             Lowercase alphabet
         №              Contains
           ι            Current character
                        (Then)
             η          Variable
            ↧           Lowercased
                        (Else)
              η         Variable
       §                Indexed by
               ⌕        Index of
                  ι     Current character
                 ↧      Lowercased
                β       In lowercase alphabet
                        (Else)
                   ι    Current character
                        Implicitly print

```

# Answer
> 3 votes
# JavaScript (Node.js), 100 bytes

```
s=>s.replace(/[a-z]/gi,c=>(C='_atypetjkitkpstokrtyputjkyb'[Buffer(c)[0]&31],c>{}?C:C.toUpperCase()))

```

Try it online!

```
s =>                                  // s = input string
  s.replace(                          // replace in s ...
    /[a-z]/gi,                        // ... all letters, no matter the case
    c => (                            // for each letter c:
      C =                             //   pick a replacement letter C
        '_atypetjkitkpstokrtyputjkyb' //   from a 1-indexed lookup string
        [Buffer(c)[0] & 31],          //   using the 5 lowest bits of the ASCII code of c
      c > {} ?                        //   if the original letter was in lower case:
        C                             //     use the replacement letter as-is
      :                               //   else:
        C.toUpperCase()               //     convert it to upper case
    )                                 //
  )                                   // end of replace()

```

# Answer
> 3 votes
# , 79 bytes

```
function(x)chartr("b-zB-Z",paste0(y<-"typetjkitkpstokrtyputjkyb",toupper(y)),x)

```

Try it online!

Only 3 bytes shorter than literally typing both lower- and uppercase replacement strings together...

# , 79 bytes

```
function(x,`[`=chartr)"B-Z"[toupper(y),"b-z"[y<-"typetjkitkpstokrtyputjkyb",x]]

```

Try it online!

Fancier code, same byte count.

# Answer
> 2 votes
# Perl 5 `-p`, 54 bytes

```
eval"y/B-Zb-z/".uc($a=typetjkitkpstokrtyputjkyb)."$a/"

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~151~~ 83 bytes

```
n=>n.Select(a=>char.IsLetter(a)?(char)(" ATYPETJKITKPSTOKRTYPUTJKYB"[a%32]|a&32):a)

```

Try it online!

Saved a whopping 68 bytes thanks to Pietu1998!

# Answer
> 2 votes
# Ruby, 55 bytes

```
$_.tr!"b-zB-Z",(x="typetjkitkpstokrtyputjkyb")+x.upcase

```

Try it online!

# Answer
> 2 votes
# , 78 61 bytes

-17 bytes thanks to FrownyFrog!

```
rplc(u:,98 66+/i.25);"0(,toupper)@'typetjkitkpstokrtyputjkyb'

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), ~~87~~ ~~63~~ ~~61~~ ~~60~~ 59 bytes

```
f:{`c$x-a-@[!128;98+!25;:;0+"typetjkitkpstokrtyputjkyb"]a:_x}

```

Try it online!

`{` `}` function with argument `x`

`_` to lowercase

`a:` assign to `a`

`!128` the list `0 1 2 ... 127`

`@[!128;` *indices* `;:;` *values* `]` amend it by replacing the elements at *indices* with the given *values*

`98+!25` the list `98 99 100 ... 122` which are the ascii codes for `"bcd`...`z"`

juxtaposition is indexing, so we use `a` (implicitly converted to integers) as indices in the amended list

`x-a-` subtract from `a`, then subtract form `x`; this restores upper/lowercase as in the original string

``c$` convert to characters

# Answer
> 1 votes
# Retina 0.8.2, 59 bytes

```
[a-z]
 $&
T`l`L
T`L`ATYP\ETJKITKPST\OKRTYPUTJKYB
T`L `l_` .

```

Try it online! Link includes test cases. Explanation:

```
[a-z]
 $&

```

Prefix a non-ASCII character to each letter. (I tried to use a non-breaking space but Firefox might have changed it back to a regular space after copying and pasting.)

```
T`l`L

```

Uppercase all of the letters.

```
T`L`ATYP\ETJKITKPST\OKRTYPUTJKYB

```

Convert the letters to Corpus.

```
T`L `l_` .

```

Lowercase the letters after the non-ASCII character and delete the non-ASCII character.

Naïve solution is 63 bytes:

```
T`lL`aty\petjkitk\pst\okrty\putjkybATYP\ETJKITKPST\OKRTYPUTJKYB

```

Try it online! Link includes test cases.

# Answer
> 1 votes
# Python 2, 115 bytes

```
lambda i:i.translate(''.join(a))
a=map(chr,range(256))
b='typetjkitkpstokrtyputjkyb'
a[66:91]=b.upper();a[98:123]=b

```

Try it online!

Adapted from @ElPedro's answer. This generates the replacement for every ascii character in the array `a` and then uses `str.translate`.

Can be brought to **113 bytes** if returning an array of chars is acceptable:

```
lambda i:[a[ord(x)]for x in i]
a=map(chr,range(256))
b='typetjkitkpstokrtyputjkyb'
a[66:91]=b.upper();a[98:123]=b

```

Try it online!

# Answer
> 1 votes
# Jelly, 29 bytes

```
“qḍỊYl4ḃ©ƭṄxḳ½Dy’ṃⱮØA,Øa¤⁺żẎy

```

Try it online!

# Answer
> 1 votes
# Japt, 37 bytes

```
;®i`…ypetjkŠkp¡okrtyp©jkyb`pu)gCpu bZ

```

Try it online!

The above link includes most test cases, but I haven't been able to input the second to last one as a string because it contains both single and double quotes. Here is that test case, input as an array of characters instead.

Explanation:

```
;                                        #Set C to the lowercase alphabet
 ®                                       #For each character Z of the input:
                                   bZ    # Find its index in:
                               C         #  The lowercase alphabet
                                pu       #  Plus the uppercase alphabet
                                         #  (-1 if it is not a letter)
                              g          # And get the character at that index in:
   `…ypetjkŠkp¡okrtyp©jkyb`              #  Get the lowercase Corpus alphabet
                           pu)           #  Plus the uppercase Corpus alphabet
  i                                      #  Add Z at the end (index -1)

```

# Answer
> 0 votes
# Python 2, ~~138~~ 132 bytes

```
def f(i,a='bcdfghjlmnpqrstvwxz',b='typtjktpstkrtyptjkb'):a+=a.upper();b+=b.upper();return''.join((x,b[a.find(x)])[x in a]for x in i)

```

Try it online!

Actually shorter with a named function than with a lambda!

lambda version, **138** bytes

```
lambda i,a='bcdfghjlmnpqrstvwxzBCDFGHJLMNPQRSTVWXZ',b='typtjktpstkrtyptjkbTYPTJKTPSTKRTYPTJKB':''.join((x,b[a.find(x)])[x in a]for x in i)

```

Try it online!

**~~131~~ 125** if we are allowed to return an array of characters and have the `join` outside the function.

```
def f(i,a='bcdfghjlmnpqrstvwxz',b='typtjktpstkrtyptjkb'):a+=a.upper();b+=b.upper();return[(x,b[a.find(x)])[x in a]for x in i]

```

Try it online!

# Answer
> 0 votes
# PHP, 100 bytes

**Code**

```
<?=strtr($argv[0],($u=bcdfghjklmnpqrstvwxyz).($f=strtoupper)($u),($v=typtjktkpstkrtyptjkyb).$f($v));

```

Try it online!

**Explanation**

```
# using the provided character mapping given on the question, as an array
strtr($argv[0],                                  # strtr for the string replacement
($u=bcdfghjklmnpqrstvwxyz).($f=strtoupper)($u),  # Taking onthe the keys for the first string
($v=typtjktkpstkrtyptjkyb).$f($v));              # Using the values for second string
 # In both Strings appending the upper version of each string.

```

# Answer
> 0 votes
# Pyth, 35 Bytes

```
XQ.*m+r1dd[tG."byàHuH¯¹e?rJyfh

```

Try it!

Could probably use Left map or something to get rid of the two d's, but I couldn't figure out how.

# Answer
> 0 votes
# Java, 211 Bytes

```
a->{String b="BCDFGHJLMNPQRSTVWXZbcdfghjlmnpqrstvwxz",c="TYPTJKTPSTKRTYPTJKBtyptjktpstkrtyptjkb";a.chars().map(x->{int z;return(z=b.indexOf(x))>-1?c.toCharArray()[z]:x;}).forEach(x->System.out.print((char)x));};

```

Try it online!

# Answer
> 0 votes
# Pyth, 34 chars

```
J."byàHuH¯¹e?rJyfh"XXztGJrtG1rJ1
```

Try it online!

The string is a compressed version of *"typetjkitkpstokrtyputjkyb"*. For some reason I cannot get Pyth to compress *"atypetjkitkpstokrtyputjkyb"* with the function

```
+++\.N++hSzeSzCi-RChSzCMz-hCeSzChSzN
```
even though it would probably save a byte or two as the two t's could be eliminated.

# Answer
> 0 votes
# Tcl, 114 bytes

```
proc C s {string map [split {btcydpftgjhkjtlpmsntpkqrrtsytpvtwjxkzbBTCYDPFTGJHKJTLPMSNTPKQRRTSYTPVTWJXKZB} ""] $s}

```

Try it online!

# Answer
> 0 votes
# Lua, 153 bytes

```
t="atypetjkitkpstokrtyputjkyb"for c in(...):gmatch"."do i=c:lower():byte()-96n=t:sub(i,i)io.write((i<0or i>26)and c or(c==c:upper()and n:upper()or n))end

```

Try it online!

---
Tags: code-golf, text-processing
---


# Question
Title: Range interval insert which should split into unique ranges
Given a range and a list thereof, while keeping the existing intervals in the list unchanged, split the additional range into sub-intervals and add them to the list, such that all the ranges in the final list are disjoint and contain all numbers present in the input ranges.

The goal is to create an insertInterval(intervals, newInterval) function which returns a new interval list if there are any changes.

**Pre-condition:** Interval range is sorted **smallest to larger** \[\[0, 1\], \[3, 5\]\].

**Examples:** Input and output:

```
assert.deepEqual(
  insertIntervalSec([[1,5],[10,15],[20,25]], [12,27]),
  [[1,5],[10,15],[15,20],[20,25],[25, 27]]
);

assert.deepEqual(
  insertIntervalSec([[1,5],[10,15],[20,25]], [-3,0]),
  [[-3,0],[1,5],[10,15],[20,25]]
);

assert.deepEqual(
  insertIntervalSec([[1,5],[10,15],[20,25]], [-3,3]),
  [[-3,1],[1,5],[10,15],[20,25]]
);

assert.deepEqual(
  insertIntervalSec([[0,5],[10,15],[20,25]], [15,15]),
  [[0,5],[10,15],[20,25]]
);
assert.deepEqual(
  insertIntervalSec([[0,5],[10,15],[20,25]], [20,21]),
  [[0,5],[10,15],[20,25]]
);
assert.deepEqual(
  insertIntervalSec([[0,5],[10,15],[20,25]], [26,27]),
  [[0,5],[10,15],[20,25],[26, 27]]
);
assert.deepEqual(
  insertIntervalSec([[0,5],[10,15],[20,25]], [25,27]),
  [[0,5],[10,15],[20,25],[25,27]]
);
assert.deepEqual(insertIntervalSec([], [25,27]), [[25,27]]);
assert.deepEqual(insertIntervalSec([[1,1]], [1,1]), [[1,1]]);
assert.deepEqual(insertIntervalSec([[1,1]], [1,3]), [[1, 1], [1, 3]]);
assert.deepEqual(insertIntervalSec([[2,2]], [1,3]), [[1, 2], [2, 2], [2, 3]]);

```

All programming languages are welcome.

# Answer
# Japt, 44 bytes

```
rò
íU c ò@Vc øX ©X¥YÃke@V®ròÃc øXÃ®gJõ0ÃcV n

```

Try it online!

Reworked it, at the cost of 1 byte. Now handles the `[[2,2]],[1,3]` test case properly.

**Explanation**:

```
rò                                           #Turn the second input into a range
íU c                                         #Duplicate each item in that range
     ò@      ©X¥YÃ                           #Split in the middle of the duplicates that:
       Vc øX                                 # Appear in the first input
                  k                          #Remove the segments where:
                   e@       øXÃ              # Every item in the segment is in...
                     V®ròÃc                  # A range from the first input
                               ®    Ã        #For the remaining segments:
                                gJõ0         # Get the first and last items
                                     cV      #Add those pairs to the first input
                                        n    #Sort the whole thing

```

**Worked Example**:

Input: `[[2,2],[5,7]],[1,8]`

Second input as a range: `[1,2,3,4,5,6,7,8]`

Duplicate each item: `[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]`

Numbers that appear in the first input: `[2,5,7]`

After splitting: `[[1,1,2],[2,3,3,4,4,5],[5,6,6,7],[7,8,8]]`

Numbers within the first input's *ranges*: `[2,5,6,7]`

Segments using only those numbers:`[[5,6,6,7]]`

Remaining segments after those are removed: `[[1,1,2],[2,3,3,4,4,5],[7,8,8]]`

First and last item of each: `[[1,2],[2,5],[7,8]]`

Merge with the first input: `[[1,2],[2,5],[7,8],[2,2],[5,7]]`

Sort it: `[[1,2],[2,2],[2,5],[5,7],[7,8]]`

Which matches the actual output of the code
> 4 votes

# Answer
# 05AB1E, ~~34~~ ~~33~~ 30 bytes

```
ŸεI˜yåiðy)]˜#ʒI€Ÿ˜KgĀ}εнyθ‚}«ê

```

Created a port of *@KamilDrakari*'s Japt answer, in order to fix the new test case `[[2,2]], [1,3]` (which golfed 4 bytes at the same time). So make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
Ÿ            # Get the ranged list of the first (implicit) input
             #  i.e. [1,8] → [1,2,3,4,5,6,7,8]
 ε           # Map each number `y` to:
  I˜yåi      #  If the second input flattened contains the current map-number:
             #    i.e. [[2,2],[5,7]] and `y`=2 → 1 (truthy)
       ðy    #   Push a space character, and value `y` again
         )   #   Wrap `y`, space, `y` into a list
 ]           # Close the if-statement and the map
             #  i.e. [1,2,3,4,5,6,7,8] and [[2,2],[5,7]]
             #   → [1,[2," ",2],3,4,[5," ",5],6,[7," ",7],8]
  ˜          # Flatten the list
             #  i.e. [1,[2," ",2],3,4,[5," ",5],6,[7," ",7],8]
             #   → [1,2," ",2,3,4,5," ",5,6,7," ",7,8]
   #         # Split the list on spaces
             #  i.e. [1,2," ",2,3,4,5," ",5,6,7," ",7,8] → [[1,2],[2,3,4,5],[5,6,7],[7,8]]
ʒ       }    # Filter this list of lists by:
 I€Ÿ         #  Push the second input, and create a range of each pair
             #   i.e. [[2,2],[5,7]] → [[2],[5,6,7]]
    ˜        #  Flatten this list of lists
             #   i.e. [[2],[5,6,7]] → [2,5,6,7]
     K       #  Remove these numbers from the current filter-list
             #   i.e. [2,3,4,5] and [2,5,6,7] → [3,4]
             #   i.e. [5,6,7] and [2,5,6,7] → []
      g      #  Take the length of this list
             #   i.e. [3,4] → 2
             #   i.e. [] → 0
       Ā     #  And truthify it (0 remains 0; everything else becomes 1)
             #   i.e. 2 → 1 (truthy)
             #   i.e. 0 → 0 (falsey)
             #  i.e. [[1,2],[2,3,4,5],[5,6,7],[7,8]] and [[2,2],[5,7]]
             #   → [[1,2],[2,3,4,5],[7,8]]
ε    }       # Map each inner list to:
 н           #  Take the first value
             #   i.e. [2,3,4,5] → 2
  yθ         #  And the last value
             #   i.e. [2,3,4,5] → 5
    ‚        #  And pair them together
             #   i.e. 2 and 5 → [2,5]
             #  i.e. [[1,2],[2,3,4,5],[7,8]] → [[1,2],[2,5],[7,8]]
«            # Merge this list of pairs with the second (implicit) input
             #  i.e. [[2,2],[5,7]] and [[1,2],[2,5],[7,8]]
             #   → [[2,2],[5,7],[1,2],[2,5],[7,8]]
 ê           # Sort the list of pairs, and remove any duplicated pairs at the same time
             #  i.e. [[2,2],[5,7],[1,2],[2,5],[7,8]]
             #   → [[1,2],[2,2],[2,5],[5,7],[7,8]]
             # (and output the result implicitly)

```
> 2 votes

# Answer
# Python 2, ~~119~~ ~~118~~ 116 bytes

```
lambda l,A,B:sum([[[max(A,b),min(c[0],B)],c][max(A,b)>=min(c[0],B):]for(a,b),c in zip([[A,A]]+l,l+[[B,B]])],[])[:-1]

```

Try it online!

---

If I/O can be flat lists (of even length):

# Python 2, 112 bytes

```
lambda l,A,B:sum([[a]+[max(A,a),min(B,b)]*(max(A,a)<min(B,b))+[b]for a,b in zip(*[iter([A]+l+[B])]*2)],[])[1:-1]

```

Try it online!

---

# Python 3, 111 bytes

```
lambda l,A,B:sum([[a]+[max(A,a),min(B,b)]*(max(A,a)<min(B,b))+[b]for a,b in zip(*[iter([A,*l,B])]*2)],[])[1:-1]

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Very Simple Triangles

text:
# Question
Title: Very Simple Triangles
Write a program or function that takes in a positive integer (via stdin, command line, or function arg) and prints or returns a string of that many of these small triangles tiled together, alternating which way they point:

```
 /\
/__\

```

This sole triangle is the output if the input is `1`.

If the input is `2`, the output is

```
  ____
 /\  /
/__\/

```

If the input is `3`, the output is

```
  ____
 /\  /\
/__\/__\

```

If the input is `4`, the output is

```
  ________
 /\  /\  /
/__\/__\/

```

And so on. Your program must support inputs up to 216 \- 1 = 65535.

**Details**

* The leftmost triangle always points upwards.
* There may be trailing spaces but there may not be unnecessary leading spaces.
* There may be an optional trailing newline.
* Note that for `1` the output is two lines long but otherwise it's three. This is required.
* The shortest submission in bytes wins.

# Answer
> 33 votes
# Pyth, ~~44~~ 42

```
ItQpdd*\_*4/Q2)jbms<*dQhQ,c" /\ "2,\/"__\\

```

The first line:

```
ItQpdd*\_*4/Q2)
ItQ           )    If the input is not 1
   pdd             Print two spaces
      *\_*4/Q2     Then groups of 4 underscores, repeated input/2 times.

```

The other two lines are generated by noticing that the second line consists of `" /"` and `"\ "` alternating input + 1 times, and the third line consists of `"/"` and `"__\"` alternated in the same fashion.

# Answer
> 24 votes
# SQL, ~~182~~ ~~175~~ ~~173~~ 187 bytes

Not that this'll ever be the shortest, but it's still amusing to try to minimize sql ;) lol I did this in Oracle 11, however, these should be basic SQL. \[edit\] as pointed out, I didn't apply the when input = 1 rule - only show 2 lines. can't think of a better way to do it, however, I did save a couple bytes by modifying the v logic ;) adding 2 ahead of time saves a couple bytes by not having to repeat it later \[/edit\]

```
select decode(&i,1,'',rpad('  ',v,'____')||z)||rpad(' /',v,'\  /')||decode(y,1,'\')||z||rpad('/',v-1,'__\/')||decode(y,1,'__\')from(select 2+floor(&i/2)*4v,mod(&i,2)y,chr(10)z from dual);

```

\[edit1\] removed some unnecessary spaces\[/edit1\] \[edit2\] changed &&i to just &i. It cuts down 2 chars, but forces user to input the # of triangles twice ... :P I realized my "good coding habits" using &&i were costing be 2 bytes!! The horror!! \[/edit2\]

**Explanation** (note: I use &&1 in this explanation so it only prompts once, the &1 above saves code space, but prompts multiple times ;) )

```
 select  -- line 1
     decode(&&1,1,'',   -- don't need line 1 if input is 1
     rpad('  ',v,'____') || z ) || -- every pair of triangles
     -- line 2
     rpad(' /',v,'\  /') ||  -- every pair of triangles
          decode(y,1,'\') || z || -- add the final triangle, input: 1,3,5 etc.
     -- line 3
     rpad('/',v-1,'__\/') ||  -- every pair of triangles
          decode(y,1,'__\')   -- add the final triangle, input: 1,3,5 etc.
from (select 2+floor(&&i/2)*4 v,   -- common multiplier. 4 extra chars for every triangle pair
             mod(&&i,2) y,  -- Flag for the final triangle (odd inputs, 1,3,5, etc)
             chr(10) z  -- CR, here to save space.
        from dual);

```

**Output**

```
  SQL> accept i
  1
  SQL> /

   /\
  /__\

  SQL> accept i
  2
  SQL> /

    ____
   /\  /
  /__\/

  SQL> accept i
  3
  SQL> /

    ____
   /\  /\
  /__\/__\

  SQL> accept i
  12
  SQL> /

    ________________________
   /\  /\  /\  /\  /\  /\  /
  /__\/__\/__\/__\/__\/__\/

  SQL>

```

# Answer
> 11 votes
# Python 2, ~~89~~ ~~88~~ ~~87~~ ~~85~~ 83 named / 81 unnamed

```
f=lambda n:1%n*("  "+n/2*4*"_"+"\n")+(" /\ "*n)[:2+2*n]+"\n"+("/__\\"*n)[:n-~n+n%2]

```

*(Thanks to @orlp for a byte, and @xnor for another three)*

This is a function which takes in an int `n` and returns the triangles as a string using the row-by-row approach.

e.g. `print f(10)` gives

```
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

```

For the first row, instead of `(n>1)*` we use `1%n*`, since `1%n` is 0 if `n == 1` and 1 if `n > 1`.

# Answer
> 7 votes
# JavaScript (ES6), 101 ~~109~~

Way too long

```
f=(n,z=a=>a.repeat(n/2))=>(n>1?'  '+z('____')+'\n ':' ')+z('/\\  ',w=' /'[++n&1]+'\n')+w+z('/__\\')+w

```

**Explanation**

Using fat arrow for function definition. Moreover no `{}` block: the function body is a single expression that is the return value. `f=(a,b,c)=>expr` is equivalent to

```
function f(a,b,c)
{
  return expr;
}

```

Inside a single expression you can not use statements like `if` or `var`, but

* parameters with default values can be used as local variables
* conditional expressions `?:` work well instead of `if else`
* you can add more subexpressions using the comma operator or even better as unused parameter to functions. In this case the assignment of `w` is the second (unused) parameter to the function `z`

We can rewrite the `f` function as

```
f = function(n) {
  var z = function(a) { // use current value of n (that changes)
    return a.repeat(n/2);
  };
  var result;
  if (n > 1) {
    result = '  ' + z('____') + '\n '; // top row if more than 1 triangle
  else
    result = ' '; // else just the blank
  ++n; // increase n, so invert even/odd
  w = ' /'[n&1]+'\n'; //  blank if n is now even, else '/' if n is now odd
  // the next rows will end in "/\" or "\  /" based on n even/odd
  result +=  z('/\\  ') + w; // offset by the blank char added before
  result += z('/__\\') + w;
  return result;
}

```

**Test** in Firefox/FireBug console

```
console.log(f(1),f(2),f(3),f(4),f(9))

```

*Output*

```
 /\
/__\

  ____
 /\  /
/__\/

  ____
 /\  /\
/__\/__\

  ________
 /\  /\  /
/__\/__\/

  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\

```

# Answer
> 6 votes
# Haskell ~~155~~ ~~153~~ ~~139~~ 131 Bytes

I found a slightly different approach that turned out to be shorter than my original method. My original attempt is preserved below. As with before, golfing tips are appreciated.

```
m n=unlines.dropWhile(=="  ").z["  "," /","/"].foldr1 z$map t[1..n]
t n|odd n=["","\\","__\\"]
t _=["____","  /","/"]
z=zipWith(++)

```

Thanks to Nimi for the golfing tips.

---

# Previous Attempt ~~197~~ 179 Bytes

```
t n=putStr.unlines.dropWhile(all(==' ')).z(flip(++))(if odd n then["","\\","__\\"]else repeat"").z(++)["  "," /","/"].map(take(4*div n 2).cycle)$["____","\\  /","__\\/"]
z=zipWith

```

# Answer
> 6 votes
# CJam, ~~55~~ ~~53~~ 51 bytes

```
SSri:I2/4*'_*N]I1>*" /\ "I*I)2*<N"/__\\"I*I2*)I2%+<

```

I tried porting my Python answer and it turned out to be shorter than the other CJams.

Permalink.

# Answer
> 4 votes
# CJam, ~~73~~ ~~68~~ ~~63~~ ~~62~~ 60 bytes

This definitely needs some golfing...

```
S2*l~:I2/'_4**N]I(g*S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

```

Test it here.

## Explanation

```
"Print the first line:";
S2*l~:I2/'_4**N]I(g*

S2*                  "Push a string with 2 spaces.";
   l~:I              "Read and eval the input, store it in I.";
       2/            "Divide by two to get the number of top segments.";
         '_4**       "Push '____' and repeat it by the number of segments.";
              N]     "Push a newline and wrap everything in an array.";
                I(g* "Get sign(I-1) and repeat the array that often. This is a no-op
                      for I > 1 but otherwise empties the array.";

"Print the other two lines. The basic idea is to define block which takes as arguments
 a repeatable 4-character string as well as another string which only gets printed for
 even I.";
S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

S                                        "Push a space.";
 "\\__/"'\                               "Push the string '\__/' and the character \.";
          {             }:F~             "Store this block in F and evaluate it.";
           I2md                          "Get I/2 and I%2 using divmod.";
               @*                        "Pull up the second argument and repeat it I%2
                                          times. This turns it into an empty string for
                                          even I.";
                 @@                      "Pull up I/2 and the 4-character string.";
                   *                     "Repeat the string I/2 times.";
                    '/\@                 "Push a / and reorder the three line parts.";
                            N            "Push a newline.";
                             "__\\/"_W<F "Call F again, with '__\/' and '__\'.";

```

# Answer
> 4 votes
# Julia, 115 bytes

```
n->(m=n÷2;p=println;k=n%2>0?m+1:m;e=m<k?"":"/";t=" /\\ ";b="/__\\";if n>1 p("  "*"_"^4m)end;p(t^k*" "*e);p(b^k*e))

```

This creates an unnamed function which accepts an integer and prints the triangles. To call it, give it a name, e.g. `f=n->(...)`.

Ungolfed + explanation:

```
function f(n)

    m = n ÷ 2                    # Number of upside down triangles
    p = println                  # Store println function to save space
    k = n % 2 > 0 ? m + 1 : m    # Number of right side up triangles
    e = m < k ? "" : "/"         # n even? End lines with a /

    # Top of the triangle
    t = " /\\ "

    # Bottom of the triangle
    b = "/__\\"

    # Print the bottoms of any upside down triangles
    # * performs string concatenation
    # ^ performs string repetition
    if n > 1
        println("  " * "_"^4m)
    end

    # Print the triangle tops (these have two trailing spaces
    # if the last triangle isn't upside down)
    println(t^k * " " * e)

    # Print the triangle bottoms
    println(b^k * e)
end

```

Example output:

```
julia> for i = 1:10 f(i) end
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

```

I'm pretty bummed that this is so long. I'm sure there are golfing opportunities aplenty but they aren't clear to me at the moment. Let me know if you have any suggestions or if you'd like any further explanation!

# Answer
> 3 votes
# CJam, ~~68 62~~ 60 bytes

As far as I can see, this is a completely different approach than the other CJam solution. This can be golfed a lot.

```
"/__\\ /\\"4/]ri:R(['/"  /"'_4*"__\\"'\L]3/R*<+zR1>SS+*\W%N*

```

Try it online here

# Answer
> 3 votes
# C#, ~~257~~183 bytes

```
void C(int t){int i;var n="\r\n";var s="  "+string.Join("____",new string[1+t/2])+n;for(i=0;i++<=t;)s+=i%2<1?"\\ ":" /";s+=n;for(i=0;i++<=t;)s+=i%2<1?"__\\":"/";Console.WriteLine(s);}

```

**Edit:** Thanks to the tips from @VisualMelon, saved 74 bytes.

I know it's far from the best language to golf in, but I'm mostly interested in learning about the various nuances of C#, rather than winning the competition. This is basically a port of this Pyth answer.

I'm thinking the for loops could be golfed further, but I'm not quite sure how, given the tertiary statements embedded within them.

Example (1, 2, 3, 10):

```
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

```

**Ungolfed:**

```
void C2(int t)
{
    int i;
    var n="\r\n";
    var s="  "+string.Join("____",new string[1+t/2])+n;
    for(i=0;i++<=t;)
        s+=i%2<1?"\\ ":" /";
    s+=n;
    for(i=0;i++<=t;)
        s+=i%2<1?"__\\":"/";
    Console.WriteLine(s);
}

```

# Answer
> 3 votes
## C# 190

```
void f(int n){string s=(n>1)?"\n  ":"",t=" /",u = "/";bool b=true;int m=n;while(m-->0){s+=(n>1&&b&&m>0)?"____":"";t+=b?"\\":"  /";u+=b?"__\\":"/";b=!b;}Console.Write("{0}\n{1}\n{2}",s,t,u);}

```

Ungolfed

```
void f(int n)
{
string s = (n > 1) ? "\n  " : "", t = " /", u = "/";
bool b = true;
int m = n;
while(m-->0)
{
s += (n > 1 && b && m>0) ? "____" : "";
t += b ? "\\" : "  /";
u += b ? "__\\" : "/";
b = !b;
}
Console.Write("{0}\n{1}\n{2}",s,t,u);
}

```

# Answer
> 2 votes
# Java, 185

```
String f(int n){int i;String s="";if(n>1){s="  ";for(i=0;i<n/2;i++)s+="____";s+='\n';}for(i=0;i<=n;)s+=i++%2<1?" /":"\\ ";s+='\n';for(i=0;i<=n;i++)s+=i%2<1?i<n?"/_":"/":"_\\";return s;}

```

# Explanation

```
String f(int n) {
    int i;
    String s = "";
    if (n > 1) {
        s = "  ";
        for (i = 0; i < n / 2; i++) {
            s += "____";
        }
        s += '\n';
    }
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? " /" : "\\ ";
    }
    s += '\n';
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? i < n ? "/_" : "/" : "_\\";
    }
    return s;
}

```

# Answer
> 2 votes
## C# - ~~151~~ ~~146~~ ~~141~~ 138

Inspired by @bacchusbeale's answer

```
string f(int n){string t="\n",s=n>1?"  "+new string('_',n/2*4)+t:"";for(var b=n<0;n-->=0;t+=b?"__\\":"/",b=!b)s+=b?"\\ ":" /";return s+t;}

```

Ungolfed

```
    string f(int n)
    {
        string t = "\n", s = n > 1 ? "  " + new string('_', n / 2 * 4) + t : "";
        for (var b = n < 0; n-- >= 0; t += b ? "__\\" : "/", b = !b)
            s += b ? "\\ " : " /";
        return s + t;
    }

```

# Answer
> 1 votes
# C89, 150

```
r(p,q,n)int*p,*q;{n?printf(p),r(q,p,n-1):puts(p);}main(c,v)int**v;{c=atoi(v[1]);if(c>1)printf("  "),r("","____",c-1);r(" /","\\ ",c);r("/","__\\",c);}

```

An ungolfed version:

```
r(p, q, n) char *p, *q; {
    if(n > 0) {
        printf(p);
        r(q, p, n-1); /* swap p and q */
    } else {
        puts(p);
    }
}

main(c, v) char**v; {
    c = atoi(v[1]);
    if(c>1) {
        printf("  ");
        r("", "____", c - 1);
    }
    r(" /", "\\ ", c);
    r("/", "__\\", c);
}

```

The output:

```
$ seq 1 3 10 | xargs -n1 ./triangles
 /\
/__\
  ________
 /\  /\  /
/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

```

The stack overflows if I enter `65535` (but not if you compile with `-O3`!), but theoretically it should work ;-)

*edit:* program now fulfills the requirement that only two lines should be outputted if `1` is passed to the program *edit 2:* use `int*` instead of `char*`

# Answer
> 1 votes
# Go, ~~156~~ 144

```
func f(n int){a,b,c:="  ","","";for i:=0;i<=n;i++{if i<n/2{a+="____"};if i%2<1{b+=" /";c+="/"}else{b+=`\ `;c+=`__\`}};print(a+"\n"+b+"\n"+c)}

```

Ungolfed:

```
func f(n int) {
    a, b, c := "  ", "", ""   // Initialize 3 accumulators
    for i := 0; i <= n; i++ { // For each required triangle
        if i < n/2 {          // Yay integer math
            a += "____"
        }
        if i%2 < 1 {          // Even, uneven, (are we drawing up or downslope?)
            b += " /"
            c += "/"
        } else {
            b += `\ `
            c += `__\`
        }
    }
    print(a + "\n" + b + "\n" + c)
}

```

The only real trick here (and it isn't even a good one) is using 3 accumulators so I can condense the solution down to 1 loop.

The code can be run here: http://play.golang.org/p/urEO1kIjKv

# Answer
> 1 votes
# Bash, ~~166~~ ~~127~~ ~~125~~ ~~119~~ 105 bytes

```
printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

```

In a function:

```
triangle() {
    printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
}

```

With some presentations:

```
for i in {1..5} 10 31;do
    paste -d\  <(
        figlet -fsmall $i |
             sed 's/^/         /;s/^ *\(.\{10\}\)$/\1  /;$d'
    ) <(triangle $i)
  done

```

May render (if you have *figlet* installed):

```
        _
       / |    /\
       | |   /__\
       |_|
      ___      ____
     |_  )    /\  /
      / /    /__\/
     /___|
      ____     ____
     |__ /    /\  /\
      |_ \   /__\/__\
     |___/
     _ _       ________
    | | |     /\  /\  /
    |_  _|   /__\/__\/
      |_|
      ___      ________
     | __|    /\  /\  /\
     |__ \   /__\/__\/__\
     |___/
   _  __       ____________________
  / |/  \     /\  /\  /\  /\  /\  /
  | | () |   /__\/__\/__\/__\/__\/
  |_|\__/
    _____      ____________________________________________________________
   |__ / |    /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
    |_ \ |   /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|

```

### Save 2 chars if *input* from variable instead of `$1`: 103

```
printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

```

Into the loop:

```
for i in {1..3} {31..34};do
    [ $i == 31 ] && figlet -fsmall ...
    paste -d\  <(
        figlet -fsmall $i |
            sed 's/^/         /;s/^ *\(.\{10\}\)$/\1   /;$d'
    ) <(
        printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
    )
  done

```

Will render (approx) same:

```
        _
       / |     /\
       | |    /__\
       |_|
      ___       ____
     |_  )     /\  /
      / /     /__\/
     /___|
      ____      ____
     |__ /     /\  /\
      |_ \    /__\/__\
     |___/

 _ _ _
(_|_|_)

    _____       ____________________________________________________________
   |__ / |     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
    |_ \ |    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|
  _______       ________________________________________________________________
 |__ /_  )     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
  |_ \/ /     /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
 |___/___|
  ________      ________________________________________________________________
 |__ /__ /     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
  |_ \|_ \    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
 |___/___/
 _____ _        ____________________________________________________________________
|__ / | |      /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
 |_ \_  _|    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
|___/ |_|

```

# Answer
> 1 votes
# \>\<\> (Fish), 215 183 156 bytes

Edit: Notepad++ was giving me 5 extra bytes due to CR, so modified count accordingly

Slightly more golfed, but it is my first fish program so far \>\_\< The requirement to not have a blank first line for 1 triangle doubled the size of the program.

```
99+0{:}1=?.~~"  "oo:2,:1%-v
-1  oooo  "____"  v!?  )0:/!
" /"oa~~.?=1}:{24~/:oo
v!?)0:-1o"\"v!?)0:/!-1ooo"  /"
/v   ~o"/"oa/!
!\:0)?!;"\__"ooo1-:0)?!;"/"o1-

```

Can test at http://fishlanguage.com/ (Int on initial stack for length)

Explanation:

```
       Start with initial stack as input number
99+0   Push 18 and 0 to the top of the stack
{:}    Shift the stack to the left (wraps), copy the top value, and shift it back to the left (i.e. copy bottom of stack to the top)
1=     Check to see if the top of the stack is equal to 1, pushes 1 for true, 0 for false
?.     If top of stack is zero, skip the ., otherwise jumps to x,y coordinates on top of stack (18,0). This skips the next 8 instructions
~~     Pop the top 2 values from the stack (if they're not popped by the jump)
"  "   Push the string literal "  " onto the stack
oo     Pop the top two values of stack and output them as characters
:2,    Copy top value of stack, ad divide by 2
:1%-   Since ><> uses float division, and doesn't have >= notation, remove the decimal part (if exists)
v      Redirect pointer down
/      Redirect pointer left
:0)    Copy top of stack, and see if its greater than 0 (1 for true, 0 for false)
?!v    If top of stack is non-zero, then ! is executed, which skips the next instruction (redirect), otherwise, code is redirected
"____" Push the literal "____" to the stack
oooo   Pop the top four values of stack and output them as characters
1-     Decrement the top of the stack by 1
!/     Ignore the redirect action.
       When the loop gets to 0, it goes to next line, and gets redirected to the left.
~      Pops the top of the stack (0 counter)
42     Pushes 4 and 2 to the stack
{:}    As before, copies the bottom of the stack to the top
1=?.   Also as before, if the initial value is 1, jump to (2,4) (skipping next 4 instructions
~~     Pop 2 values from stack if these instructions haven't been skipped
ao     Push 10 onto the stack and output it as a character (LF)
"/ "oo Push the literal "/ " onto the stack and output it
://    Copies the top of the stack then redirects to the line below, which then redirects to the left
:0)    Copies top of the stack and compares if its greater than 0
?!v    If it is, redirect to next line
"\"o   Push "\" to stack, then output it as a character
1-     Decrement top value of stack
:0)?!v If loop is not greater than 0, redirect to next line
       Either mode of redirect will loop to the left, and (potentially) skip the far right redirect because of the !
ao     Push 10 to stack and output it as a character (LF)
"/"o~  Push "/" to stack, then output it as a character. Pop top value of stack (the 0 from previous loop)
v      Redirects to next line, which then redirects to the right
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"\__"  Pushes "\__" to the stack
ooo    Outputs top 3 stack values as characters ("__\")
1-     Decrement top of stack by 1
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"/"o   Push "/" to top of stack then output it as a character
1-     Decrement top of stack by 1
!\     Ignore the redirect

```

# Answer
> 1 votes
# perl 109 108 106

```
$i=<>;$t=join$/,$i-1?"  "."_"x($i/2)x4:(),$m.=(" /")[$_&1]||"\\ ",$b.=("/")[$_&1]||"__\\"for 0..$i;print$t

```

I think this is alright for my first golf, I used Vynce's section for the first line, with the rest of my code to get past the new line problem with 1 triangle.

Now to see if I can shorten it :)

**Edit**: Whitespace

**Edit 2**: replaced `"\n"` with `$/`

```
1:
 /\
/__\

4:
  ________
 /\  /\  /
/__\/__\/

```

# Answer
> 1 votes
# C++ stdlib, 194 bytes

```
string f(int n){char* p[]={"____"," /\\ ","/__\\"};int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;string s=n>1?"  ":"";for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")for (j=0;j<x[i];)s+=p[i][j++%4];return s;}

```

Test program:

```
#include <string>
#include <iostream>

using namespace std;

string f(int n)
{
    char* p[]={"____"," /\\ ","/__\\"};
    int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;
    string s=n>1?"  ":"";
    for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")
        for (j=0;j<x[i];)
            s+=p[i][j++%4];
    return s;
}

int main(int argc, char* argv[])
{
    cout << f(10);
    return 0;
}

```

# Answer
> 1 votes
# Charcoal, 27 bytes

```
ＦＥＮ﹪ι²«Ｐ×⁴_↗⊗¬ι↓Ｐ↘²↘⊗ι↑Ｐ↗⊗ι

```

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

```
ＦＥＮ﹪ι²«

```

Generate a list of alternating bits of length `n` and loop over them.

```
Ｐ×⁴_

```

Draw `____` without moving the cursor.

```
↗⊗¬ι↓

```

On the first and every other triangle, draw the left `/` side.

```
Ｐ↘²

```

Draw the `\` side without moving the cursor.

```
↘⊗ι↑

```

On the second and every other triangle, draw the left `\` side again to move the cursor.

```
Ｐ↗⊗ι

```

On the second and every other triangle, draw the right `/` side, without moving the cursor.

# Answer
> 1 votes
# PowerShell, ~~116~~ 95 bytes

Big thanks to Mazzy and ASCII-Only for saving 21 bytes

```
param($n)@("  "+"_"*4*($x=$n-shr1))[$n-eq1]
" /"+"\  /"*$x+"\"*($a=$n%2)
"/"+"__\/"*$x+"__\"*$a

```

Try it online!

Not allowing an empty line for n = 1 ate up like ~~14~~ 10 bytes. This solution is ~~pretty brain dead~~ now much more clever with a minimal amount of repeated code. Banker's Rounding is still the actual devil.

# Answer
> 0 votes
# C, 368 Bytes

```
void p(char* c){printf(c);}
int x(int s,int f){int t=0,p=s;for(int i=0;i<f;i++){if(p==1){t++;p=0;}else{p=1;}}return t;}
int main(int argc,char* argv[]){int t=atoi(argv[1]);if(t>1){p("  ");for(int i=0;i<x(0,t);i++)
{p("____");}p("\n");}for(int i=0;i<x(1,t);i++){p(" /\\ ");}if(t%2==0){p(" /");}p("\n");
for(int i=0;i<x(1,t);i++){p("/__\\");}if(t%2==0){p("/");}p("\n");}

```

It's more if you count the `#include` statements, but it compiled on gcc, albeit with warnings, without them. I know it's not the shortest by far, but I still like that I did it in C.

# Answer
> 0 votes
# Perl (simple) 131 125 120

fairly straightforward first pass:

```
$i=<>;print join"\n",$i-1?"  "."_"x(4*int($i/2)):(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

```

oh who needs explicit int?

```
$i=<>;print join"\n",$i-1?"  "."_"x($i/2)x4:(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

```

# Answer
> 0 votes
# Prolog, 126 bytes

```
A+B:-writef(A,B).
$N:-(N>1,"  %r\n"+['____',N//2];!),(0is N/\1,T='/';T='')," %r%w\n"+['/\\  ',N/2,T],"%r%w\n"+['/__\\',N/2,T].

```

Invoke like `$3`.

More readable:

```
triangle(N):-
    (   N > 1
    ->  writef("  %r\n", ['____', N//2])
    ;   true
    ),
    (   0 is N mod 2
    ->  T = '/'
    ;   T = ''
    ),
    writef(" %r%w\n", ['/\\  ', N/2, T]),
    writef("%r%w\n", ['/__\\', N/2, T]).

```

Example:

```
?- findall(N,between(1,10,N),NN), maplist($, NN), !.
 /\
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/
NN = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

```

# Answer
> 0 votes
# C#: 1 line LINQ, 198 bytes

```
string f(int n){return(n>1?"  ":"")+string.Join("\n",new[]{"____"," /\\ ","/__\\"}.Zip(new[]{(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},(s,l)=>string.Join(s,new string[n+1]).Substring(0,l)).Where(x=>x.Any()));}

```

# Answer
> 0 votes
# Retina, 88 bytes

```
K`  ____¶ /\  /¶/__\/
%`....$
$+*$&
%`(.+)\1$
$1
(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4
G`\S

```

Try it online! Explanation:

```
K`  ____¶ /\  /¶/__\/

```

Replace the input with a pair of triangles.

```
%`....$
$+*$&

```

Multiply the triangles by the original input.

```
%`(.+)\1$
$1

```

Divide the triangles by 2.

```
(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4

```

Remove the left-over half triangle.

```
G`\S

```

Remove the first line if it is now blank.

# Answer
> 0 votes
# Perl 6, 83 bytes

```
{~["  {'____'x$_/2-.5}
"x($_>2),'/\  'x$_/2~($!='/'x$_%2),"
"~'/__\\'x$_/2~$!]}o*+1

```

Try it online!

Anonymous code block that takes a number and returns a string.

# Answer
> 0 votes
# C (gcc), ~~117~~ 115 bytes

-2 thanks to ceilingcat.

All those parentheses suggest something less clunky is surely possible.

```
f(n,i,j){for(j=3-1/n;j--;puts("/"+(n%2|j>1)))for(i=0;i<n+(j<2)>>1;)printf("  %.4s"+2-j*!i++,"/__\\/\\  ____"+j*4);}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 37 bytes

```
≠iðð'_I2÷4*×J}„ /„\ ‚I>∍J'/…__\‚I>∍J»

```

Try it online or verify the first 10 outputs.

**Explanation:**

```
≠i            } # If the (implicit) input is NOT 1:
                #   i.e. 1 → 0 (falsey)
                #   i.e. 5 → 1 (truthy)
  ðð            #  Push two spaces "  "
    '_         '#  Push string "_"
      I         #  Push the input
       2÷       #  Integer-divide it by 2
                #   i.e. 5 → 2
         4*     #  And then multiply it by 4
                #   i.e. 2 → 8
           ×    #  Repeat the "_" that many times
                #   i.e. "_" and 8 → "________"
            J   #  Join everything on the stack together to a single string
                #   i.e. "  ________"
„ /             # Push string " /"
   „\           # Push string "\ "
     ‚          # Pair them together: [" /","\ "]
      I>        # Push the input+1
        ∍       # Extend the list to that size
                #  i.e. [" /","\ "] and 2 → [" /","\ "]
                #  i.e. [" /","\ "] and 6 → [" /","\ "," /","\ "," /","\ "]
         J      # Join the list together to a single string
                #  i.e. [" /","\ "] → " /\ "
                #  i.e. [" /","\ "," /","\ "," /","\ "] → " /\  /\  /\ "
'/             '# Push string "/"
  …__\          # Push string "__\"
      ‚         # Pair them together: ["/","__\"]
       I>       # Push the input+1
         ∍      # Extend the list to that size
                #  i.e. ["/","__\"] and 2 → ["/","__\"]
                #  i.e. ["/","__\"] and 6 → ["/","__\","/","__\","/","__\"]
          J     # Join the list together to a single string
                #  i.e. ["/","__\"] → "/__\"
                #  i.e. ["/","__\","/","__\","/","__\"] → "/__\/__\/__\"
»               # Join the entire stack with a newline delimiter
                #  i.e. " /\ " and "/__\" → " /\ \n/__\"
                #  i.e. "  ________", " /\  /\  /\ " and "/__\/__\/__\"
                #   → "  ________\n /\  /\  /\ \n/__\/__\/__\"
                # (and output the result implicitly)

```

# Answer
> 0 votes
# Java 11, 122 bytes

```
n->(n>1?"  "+"_".repeat(n/2*4)+"\n":"")+" /\\ ".repeat(n).substring(0,++n*2)+"\n"+"/__\\".repeat(n).substring(0,n/2*4+n%2)

```

Try it online.

**Explanation:**

```
n->                   // Method with integer parameter and String return-type
  (n>1?               //  If the input is larger than 1:
    "  "              //   Return two spaces
    +"_".repeat(      //   Appended with "_" repeated the following amount of times:
          n/2         //    The input integer-divided by 2
             *4)      //    And then multiplied by 4
    +"\n"             //   Appended with a newline
   :                  //  Else:
    "")               //   Return nothing
  +" /\\ ".repeat(n)  //  Appended with " /\ " repeated the input amount of times
    .substring(0,     //   After which we only leave the first `x` characters, where `x` is:
      ++n             //    Increase the input by 1 first with `++n`
         *2)          //    And then multiply it by 2
                      //     i.e. For input 1, `x` becomes 4 here
                      //     i.e. For input 6, `x` becomes 14 here
  +"\n"               //  Appended with a newline
  +"/__\\".repeat(n)  //  Appended with "/__\" repeated the input amount of times
    .substring(0,     //   After which we only leave the first `y` characters, where `y` is:
      n/2             //    The input+1 integer-divided by 2
         *4           //    Then multiplied by 4
           +n%2)      //    And then the input+1 modulo-2 added
                      //     i.e. For input 1, `y` becomes 4 here
                      //     i.e. For input 6, `y` becomes 13 here

```

# Answer
> 0 votes
# MathGolf, 35 bytes

```
½û__∞* ∞qpÿ /\ *k∞⌠<p)½ÿ/__\*k¥┬'/*

```

Try it online!

## Explanation

The program is split into 3 parts, `½û__∞* ∞qp`, `ÿ /\ *k∞⌠<p`, and `)½ÿ/__\*k¥┬'/*`. One part for each line of the output.

### First part

```
½           Halve input to integer
 û__∞       Push "__" and double
     *      Repeat string (input//2 times)
       ∞    Push space character and double
        qp  Print the spaces first, then the underscores

```

### Second part

```
ÿ /\ *      Push " /\ " and repeat it <input> times
      k∞    Push input and double it
        ⌠   Increment by two
         <p Slice the string to get the first (<input>*2 + 2) characters and print

```

### Third part

```
)½              Increment input by 1 and halve it to integer
  ÿ/__\*        Repeat "/__\" that many times
        k¥┬     Check if input is divisible by 2
           '/*  Repeat "/" either zero or one times based on input

```

# Answer
> 0 votes
# C# (.NET Core), 151 bytes

Without LINQ - 3 string array.

Like most of these, this fails if the integer goes over the max char count per line for stdout.

```
p=>{var s=new string[3]{ "  ","",""};for(var j=0;j< p;){if(j++%2<1){s[1]+=j==p-1?@" /":@" /\ ";s[2]+=j==p-1?@"/":@"/__\";}else s[0]+="____";}return s;}

```

Try it online!

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


title: N times program for the N-th number

text:
# Question
Title: N times program for the N-th number
Given an array of positive integers `A` as the input, generate a program that, when repeated for `k` times, output the `k`th(1-index) value of the array.

For example, if the array is `[1,11]`, the output should be a program that outputs `1`, and when repeated twice, output `11`. Code like `print(end="1");` in Python 3 works: `print(end="1");` prints 1 and `print(end="1");print(end="1");` prints 11

Smallest sum of code lengths to solve all test cases win. Your meta code should solve 500 test cases in 60s, and each of your solution code should return in 10s. Meta code and solution code needn't be in the same language, but all solutions your meta-program generates should be in same language.

Pretest data and generator can be seen here. 7 days later will use the sum of submission time(e.g. 12:34 mean 1234) to be the random seed and generate another test case as the final test case.

---

The final seed is 7335 in GMT+8, so the final test data is here

# Answer
# Python 3, generates Stax

This uses a variety of strategies. Most strategies only apply under certain conditions, but there's one fallback strategy that is always usable. At the end, the smallest candidate program is selected.

```

from functools import reduce
from math import sqrt

symbols = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}"

def uncycle(arr):
    for size in range(1, len(arr)):
        if all(e == arr[i % size] for (i, e) in enumerate(arr)):
            return arr[:size]
    return arr

def constant(val):
    return "A" if val == 10 else str(val)

def shift(val):
    if not val: return ""
    return constant(abs(val)) + "+-"[val < 0]

def encode(a, offsetMode):
    result = "";
    if offsetMode:
        for i in range(len(a) - 1, 0, -1):
            a[i] -= a[i - 1]
    for i in range(len(a)):
        parts = []
        signBit = (a[i] < 0) * 2
        continuing = (offsetMode and i == len(a) - 1) * 1
        remain = abs(a[i])
        while remain > 22:
            parts.insert(0, remain % 46 * 2 + continuing);
            remain //= 46
            continuing = 1

        parts.insert(0, remain * 4 + signBit + continuing)
        result += "".join(symbols[p] for p in parts)

    return result

def cram(arr):
    flat = encode(arr, False)
    offset = encode(arr, True)
    return offset if len(offset) < len(flat) else flat;

def issquare(num):
    root = int(sqrt(num))
    return root * root == num

def isgeometric(arr):
    r = arr[0]
    return all(r ** (i + 1) == e for (i,e) in enumerate(arr))

def generateProgram(arr):
    candidates = []
    rotated = uncycle(arr)
    rotated = rotated[-1:] + rotated[:-1]

    deltas = [b - a for a,b in zip(arr, arr[1:])]

    # single constant strategy
    if len(arr) == 1:
        candidates.append(constant(arr[0]))

    # repeated constant
    elif len(set(arr)) == 1:
        num = arr[0]
        if num == 10: candidates.append("A")
        if num % 2 == 0: candidates.append(constant(num // 2) + "H")
        if issquare(num): candidates.append(str(int(sqrt(num))) + "J")
        candidates.append(constant(num - 1) +  "^")

    # repdigit
    if len(arr) == 2 and 10 < arr[1] == arr[0] * 11 < 100:
        candidates.append(str(arr[0]) + "p")

    # single digits
    if max(arr) < 10:
        candidates.append("".join(map(str, rotated)) + "E|X@")

    # max 10
    if max(arr) == 10 and rotated[0] != 1:
        candidates.append("".join(str(e - 1) for e in rotated) + "E|X@^")

    fns = [
        ("", lambda x: x),
        ("H", lambda x: 2 * x),
        ("^", lambda x: x + 1),
        ("J", lambda x: x * x),
        ("Hv", lambda x: 2 * x - 1),
        ("H^", lambda x: 2 * x + 1),
        ("^H", lambda x: 2 * x + 2),
        ("HJ", lambda x: 4 * x * x),
        ("JH", lambda x: 2 * x * x),
        (":T", lambda x: x * (x + 1) / 2),
        ("|F", lambda x: reduce(lambda a, b: a*b, range(1, x+1))),
        ("J^", lambda x: x * x + 1),
        ("^J", lambda x: x * x + 2 * x + 1),
    ]
    for (stax, fn) in fns:
        if all(fn(i + 1) == e for (i,e) in enumerate(arr)):
            candidates.append("|X" + stax)

    # fixed delta
    if len(set(deltas)) == 1:
        delta = deltas[0]
        start = arr[0] - delta
        if start == 0:
            candidates.append(shift(delta))
        if delta == 1:
            candidates.append("|X" + shift(start))
        elif delta == -1:
            candidates.append("|x" + shift(start))
        elif delta > 1:
            candidates.append("|X" + constant(delta) + "*" + shift(start))
        elif delta < -1:
            candidates.append("|x" + constant(-delta) + "*" + shift(start))

    # geometric series
    if isgeometric(arr):
        candidates.append(constant(arr[0]) + "*")

    # prefix
    if len(arr) == 2 and arr[1] // 10 == arr[0] < 10:
        candidates.append("." + str(arr[1]) + "|X(")

    # suffix
    if len(arr) == 2 and arr[0] % 10 == arr[1] < 10:
        candidates.append("." + "".join(map(str, arr)) + "|X)")

    # uncycled cram
    candidates.append('"' + cram(rotated) + '"!|X@')

    candidates.sort(key=len)
    return candidates[0]

while True:
    arr = eval(input())
    prog = generateProgram(arr)
    print(prog)

```

Try it online!

**Update: Validation** It will be time consuming to execute each multiplicity of each program separately. It's possible to run them all at the same time. In order to do this, a small piece of code must be used. It's responsible for a few things.

1. Do implicit output if any. Normally, at the end of a stax program, the top of stack is printed if there has been no other output. When running multiple programs in the same source file, this must be done explicitly.
2. Clear both stacks.
3. Reset registers. For these programs only the x register is used.

This boilerplate should be applied after every individual program to be executed.

```
|d{P}{zP}?0XLd

```

For example, the input `[5,2,7,3]` produces the stax program `3527E|X@`. All four multiplicities can be tested at once.

```
3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

```

Try it online!

In this way, it's possible to test all the multiplicities of all the program in the same run, assuming nothing breaks. It would probably be the largest stax program ever executed if all 500 are done.
> 5 votes

# Answer
# Perl 5 `-p`, generates Perl 5 `-p`, overhead ~~19~~ ~~17~~ 13

-1 thanks to @Dom Hastings

The score for one input will be `length of the input + 13`. Can obviously be improved by generating self-decompressing programs for larger inputs, but I won't bother.

Give the input array separated by commas on one line on STDIN.

```
#!/usr/bin/perl -p
chomp;$_="}{\$_=($_)[\$%++]"

```

Try it online!

Run the output concatenated `n` times with no input (e.g. redirect from /dev/null)

Sample way to run it for input `2,6,4,7` and the resulting program repeated 4 times:

```
perl -p '}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]}{$_=(3,6,4,7)[$%++]' < /dev/null

```

Try it online!

If you don't like the resulting program trying to read from STDIN use this version with overhead 17:

```
#!/usr/bin/perl -p
chomp;$_="1/!say+($_)[\$-++],"

```

Try it online!

Sample way to run it for input `2,6,4,7` and the resulting program repeated 4 times:

```
perl -E '1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],1/!say+(2,6,4,7)[$-++],'

```

Try it online!

This version crashes after printing the required output
> 4 votes

# Answer
# 05AB1E, generates 05AB1E

```
¸»“"ÿ"#.g<“ƵƒçJ

```

Try it online!

The generated program for the input `[5,17,7,13,2]` is `"5 17 7 13 2"#.g<è`.

Test suite for \[5,17,7,13,2\]

The length of the generated program is `len(input) + 5`
> 3 votes

# Answer
# APL (Dyalog Unicode)

Anonymous prefix lambda. Returns a program body.

```
 {
     1=≢⍵:⍕⍵ ⍝ single element

     (2=≢⍵)∧(⍵[2]=11×⍵[1]):⍕⍵[1] ⍝ 2, 22 etc.

     1=≢∪⍵:'⊢',⍕⊃⍵ ⍝ all the same

     (⊢≡⊃×⍳∘≢)⍵:'+',⍕⊃⍵ ⍝ linear

     ((⌊=⊢)!⍣¯1⊢⊃⍵)∧(1∧.=1↓⍵):'!',⍕!⍣¯1⊃⍵ ⍝ factorial followed by all 1s

     (⍵[2]∧.=1↓⍵)∧(⍵[1]=10|2⊃⍵):(⍕⊃⍵),'⌈',(⊃⍕2⊃⍵) ⍝ b ab ab ab

     e←{∊⍉2 2⍴'+×',⍕¨⍵}¨⍸(⊃⍵)=∘.×⍨⍳10
     b←⍵∘≡¨e(({0::⍬ ⋄ ⍎⍵}¨,\)⍴∘⊂)¨⍨(≢⍵)
     ∨/b:⊃b/e

     Q←{'''',⍨⍵/⍨1+''''=⍵}
     (5∧.≤⍵)∧(≢⍕⍵)>6+(+/14=⍵)+≢⍵:'{⍺←⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[⍵] ⍝ string fallback

     (≢⍕⍵)>9+(+/5=⍵)+≢⍵:'{⍺←¯4+⎕AV⍳⊃⋄1⌽⍺⊢⍵}''',Q ⎕AV[4+⍵] ⍝ offset string fallback

     '{⍺←⊃⋄1⌽⍺⊢⍵}',⍕⍵ ⍝ fallback
 }

```

Try it online!

## Methods

This explores various methods and returns the first usable one, eventually falling back to a universally applicable method.

### Single element

If the list has only one element, it is returned as-is.

### 2, 22 etc.

A single digit can just be repeated to generate the number 11 times bigger,

### All the same

We just return the rightmost () number.

### Linear

*f(n) = k×n* sequences just insert a plus before the first term.

### Factorial followed by all 1s

When the first number n=!m and subsequent numbers are 1, then `!m` is a solution because `!m` is n and `m!m` is 1 and `!1` is 1.

### b ab ab ab

Since all two-digit numbers are larger than all single-digit numbers, a running maximum, where the front of the first number is glued to the back of the second number, is a solution.

### The three-line-code

Check whether any formula of the type `+a×b` is valid.

### String fallback

Long sequences with no numbers under 5 (because 4 is a line break) can be encoded as characters of the SBCS.

### Offset string fallback

If there are numbers under 5, we shift up by 9 to avoid those.

### Fallback

Simple string concatenation of the string `"{⍺←⊃⋄1⌽⍺⊢⍵}"` and the stringified () input. E.g. `[3,1,4]` returns the program body `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4`.

The part in braces is an ambivalent function which means it can be either a prefix function or an infix function. Thus the leftmost instance of it will run in prefix mode, and all the others in infix mode. The difference between the modes is whether , signifying the left argument, has a value. If it doesn't then it will be assigned the function  (first).

**Explanation of fallback method**

`{``}` anonymous lambda:

`⍺←⊃` If there is no left argument () assign the function  (first) to

then:

At this point, the following code means two different things depending on whether  is a list of numbers (infix call) or the function "first" (prefix call).

If  is a list of numbers:

`⍺⊢⍵` discard the left argument in favour of the right argument

`1⌽` rotate that one step left

If  is the function "first":

`⊢⍵` yield the right argument

pick the first element of that

`1⌽` rotate it one step (a no-op on a scalar)

**Example run of fallback method**

Executing `3 1 4`'s code, `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4`, assigns the "first" function to  and thus returns the first element; `3`.

Executing `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4` lets the rightmost lambda "capture" the left `3 1 4` as its left argument, so  has a value which is discarded in favour of `3 1 4` which is then rotated one step left and yields `1 4 3` as result. This is then used as sole argument to the leftmost lambda, where  becomes the "first" function, causing the result to be the first element; `1`.

Executing `{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4{⍺←⊃⋄1⌽⍺⊢⍵}3 1 4` lets the rightmost lambda "capture" the middle `3 1 4` as its left argument which is then discarded in favour of the right argument, `3 1 4`, which when rotated one step left is `1 4 3`. This is then used as right argument of the middle lambda together with the leftmost `3 1 4` as left argument. The left argument is discarded for the right, which rotated one step left yields `4 3 1`. This then becomes the sole argument of the leftmost lambda, so  becomes the "first function", returning the first element; `4`.

## Scoring

When it becomes time to test using actual data, use this test harness (linked populated with pretest data). The test cases go in the Input field, and the Output will be the total byte count of all 500 programs together. (It will also throw an error, but that's just because it afterwards tries to evaluate the Input as-is.)
> 3 votes

# Answer
# Haskell, generates Haskell

```
main = interact $ ("main=print$("++) . (++"!!)$ -1\n +1--")

```

Try it online! For the first testcase `[5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4]` it produces the following program:

```
main=print$([5,2,7,3,2,3,15,10,7,2,14,11,16,16,3,3,4,3,8,4]!!)$ -1
 +1--

```

Try it once, doubled and trippled. This uses the same approach as my Haskell answer to *I double the source, you double the output*.

The length of each generated program is the length of the input list as string plus 25, thus the score for the currently available testcases is `12266 + 500 * 25 = 24766`. This shows that the code to data ratio is basically equal, and I doubt it is possible to write small enough decompression code which will decreases the score. It might be possible if the lists where much larger.
> 2 votes

# Answer
# Charcoal

```
´⎚´§´⪪⪫ＩＡ ”y¦ Ｌυ⊞υω

```

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

```
´⎚´§´⪪

```

Output the literal string `⎚§⪪`.

```
⪫ＩＡ

```

Cast the input array to string, join with spaces, and print.

```
”y¦ Ｌυ⊞υω

```

Output the literal string `¦ Ｌυ⊞υω`.

Output of for example `5,17,7,13,2` is `⎚§⪪5 17 7 13 2¦ Ｌυ⊞υω`. Try it online! Explanation:

Clear the canvas, so that only the last output is visible.

```
§⪪5 17 7 13 2¦ Ｌυ

```

Take the length of the predefined list `u`. Use that to index into the list of integers that have been split on spaces and output the selected element.

```
⊞υω

```

Push a dummy variable to the predefined list `u`, so that the next copy will output the next element of the list.

Total output length = (length of all integers in all lists) + (number of integers in all lists) + (number of lists * 9) characters (SBCS).
> 2 votes

# Answer
# Python 2, generates Python 2

```
import sys
a=`input()[::-1]`.replace(' ','')
sys.stdout.write('print%s[-open(__file__,"a").tell()/%s]#'%(a,len(a)+37))

```

Try it online!

For the input

```
[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]

```

the generated program is

```
print[29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10][-open(__file__,"a").tell()/98]#

```

which is 98 bytes.

Adapted from this solution in "I double the source, you double the output!".

Dammit, two shorter answers popped in before I finished writing this answer.
> 1 votes

# Answer
# Java 8, generates Python 2

```
interface M{static void main(String[]a){int l=a[0].length();System.out.print("print"+a[0]+"[open(__file__,'a').tell()/"+(l+35+(l+"").length())+"]#");}}

```

Try it online.

I.e. `[3,4,5,6,7]` generates this Python 2 program:

```
print[3,4,5,6,7][open(__file__,'a').tell()/48]#

```

Try it online once; Try it online twice; Try it online three times.

Generated Python program is based on *@Mr.Xcoder*'s answer for the *Third time the charm* challenge.

**Explanation:**

Java 8 code:

```
interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    int l=a[0].length();        //   The length of the first argument
                                //   (Note that this is the length of the input as String,
                                //   not the size of the array)
    System.out.print(           //   Print:
      "print"                   //    Literal "print"
      +a[0]                     //    Appended with the argument
      +"[open(__file__,'a').tell()/"
                                //    Appended with literal "[open(__file__,'a').tell()/"
      +                         //    Appended with an integer that is formed by:
       (l                       //     Getting the length we got earlier
       +35                      //     +34 for the rest of the Python 2 code + 1
       +(l+"").length())        //     + the length of the length (<10→1; 10-99→2; etc.)
       +"]#");}}                //    Appended with literal "]#"

```

Python 2 code:

```
print                        # Print
 [3,4,5,6,7]                 #  From this array
 [                           #   The `k`'th item,
  open(__file__,'a').tell()  #   where `k` is the length of its own source code
  /                          #   divided by
  48                         #   the length of its own source code (once) + 1
 ]#                          # With a trailing comment, so we can repeat the program

```
> 1 votes

# Answer
# Python 2, Generates C++

This isn't going to beat any records, I was mainly interested in thinking about if I could figure out how to do it :) Use the fact that global variables are run before main, and so can increment a global variable, then using a #ifdef to ensure main is only defined once.

```
import sys
print("""#include <stdio.h>
#ifndef A
#define A
int v;
int d[]={""" + sys.argv[1] + """};
struct C{C(){v++;}};
int main(void){ printf("%d",d[v]); }
#else
C c1;
#endif
""")

```
> 1 votes

# Answer
# Bash, outputs programs in Perl 5

Bash program can be called like `script.sh 1,2,3`.

Perl program should be called with the `-E` flag.

```
echo "shift@a;@a=($1)unless@a;END{say\$a[0];exec'true'}"

```

The generated `perl` code for an input of `4,7,8` is:

```
shift@a;@a=(4,7,8)unless@a;END{say$a[0];exec'true'}

```

Pretty brute force. Removes an element of the array (`perl` doesn't care that the array doesn't exist at first), sets it if it is not already set. It then echoes the first element of the array at the end. (The `END` block is run last). The `exec 'true'` quits the program, so that the further `END` blocks are not executed.

Example:

```
#Once
$ perl -E "$(bash script.sh 4,7,8)"
4

#Duplicated twice
$ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)"
7

#Duplicated thrice
$ perl -E "$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)$(bash script.sh 4,7,8)"
8

```
> 0 votes

# Answer
# Runic Enchantments, generates Runic

```
74akw94/85akw
R32B~~?US' Sqq1Ky1Ky
\i<{1[lil1-{S{)]{{1KyB
D'0$'´$$' $     Rl0) ?
R"{Zs$;|1|l;|y"@
"UwR'10<|I+}"$~ /' Su0
       Rakwc4akw/

```

Try it online!

Takes input as a space-separated list of values.

Output done once
Output done twice
Output done four times

Utilizes the continuous numerical read mode command, `´` that was committed on Jan 12 and I found this question on the 14th. This command allows arbitrary length values can be encoded as without this feature it would be very difficult to do so (e.g. `1392` would need to be represented as `1X3+X9+X2+`, necessitating an additional loop at a minimum); precisely the problem I wanted to solve when I created the `´` command.

In the original code, the `|` in the strings `"{Zs$;|1|l;|y"` and `"UwR'10<|I+}"` are replaced with `\n` (which sit in the grid and not modify it, as they normally would) with `w`rite commands: `74akw`, `94/Rakw`, `c4akw`, and `85akw`. The original characters can be literally anything. `|` was chosen to be a symbolic placeholder that visually represented what I wanted. Several bytes saved (if unscoring ones) by not having to reflectively add an entry point, as `wR'10<` writes an `R` into a location where one already exists (position `0,1`), and then proceeds to fill its stack with junk before running out of mana, following a looping sequence `U"'i34`.

The resulting output code works by using the `w`rite command to change the first character on the second line to a `R`ight redirection (so only one IP executes a print statement), with clever use of stack length resulting from taller and taller programs to determine which index to read. Every other IP changes that same location to the same instruction and terminates. Everything else goes unused.

<sub>*Image is out of date, but sufficient for flow explanation.*</sub>

Each execution of `1Iy` maintains the IP's ability to handle a larger and larger stack (caused by the `l` command), the size of which allows the program to determine how many copies of the base source code there are. The final `1` is used to increment the previous `l` to the required number when rotating the stack (created next) in order to arrive at the correct value. The `Z` command negates this value so that the stack rotates in the correct direction.

The original input array is then encoded using continuous read mode, primed with a 0 to avoid incrementally modifying the same value, to read the original inputs. The space NOP is required to exit continuous read mode and allow the subsequent 0 to prime the stack again.

Score should equal approximately `3+v.toString().length`, for each array entry `v`, `+23` for each array. Approximately `(2.55*total length of input)` or `33837` for the sample input, if I did things right.

Minor changes were introduced into my expected final program due to side effects introduced in the same build regarding the `s` command, however it resulted in a better score at the same time.
> 0 votes

---
Tags: source-layout, metagolf
---


title: Unix timestamp to datetime string

text:
# Question
Title: Unix timestamp to datetime string
Given a unix timestamp as an input, give a datetime string, in a format like so: "YYMMDD.HHmm"

## Rules

* The input is a number (integer) of a millisecond-precise UNIX epoch time (milliseconds since 1970 January 1st 00:00:00.000 UTC).
* The values must be padded with zeroes if they are 1 character instead of 2. (e.g.: for "DD", "1" is not acceptable, but "01" is.)
* The output must be a single string. No arrays.
* Leap second handling doesn't matter.
* Shortest wins.

Good luck!

## Example

```
Input: 1547233866744
Output: 190111.1911

```

# Answer
# Japt v1.4.5, ~~19~~ 16 bytes

```
GîÐU s3)¤o>J i.G

```

1 byte saved thanks to Oliver, which led to another 2 bytes saved.

Try it

---

## Explanation

```
GîÐU s3)¤o>J i.G
                     :Implicit input of integer U
G                    :16
 î                   :Get the first 16 characters of the following string
  ÐU                 :  Convert U to a date object
     s3              :  Convert to ISO string
       )             :End get
        ¤            :Slice off the first 2 characters
         o           :Filter
          >J         :  Greater than -1
             i.G     :Insert "." at 0-based index 16, with wrapping

```

---

## Notes / Tips
> 3 votes

# Answer
# JavaScript (ES6), 65 bytes

```
n=>'101010.1010'.replace(i=/\d/g,x=>new Date(n).toJSON()[i=x-~i])

```

Try it online!

### How?

We initialize the pointer \\$i\\$ to a non-numeric value (coerced to \\$0\\$) and then add alternately \\$2\\$ and \\$1\\$ to it to pick the relevant characters from the ISO-8601 conversion of the input timestamp.

```
yyyy-mm-ddThh:mm:ss.sssZ
  ^^ ^^ ^^ ^^ ^^

```

---

# JavaScript (ES6), 66 bytes

```
n=>'235689.BCEF'.replace(/\w/g,x=>new Date(n).toJSON()[+`0x${x}`])

```

Try it online!

### How?

Once the input timestamp is converted in ISO-8601 format, all required characters can be accessed with a single hexadecimal digit.

```
yyyy-mm-ddThh:mm:ss.sssZ
  ↓↓ ↓↓ ↓↓ ↓↓ ↓↓
0123456789ABCDEF

```
> 8 votes

# Answer
# Bash \+ coreutils, 29 bytes

```
date -d@${1::-3} +%y%m%d.%H%M

```

Try it online!
> 7 votes

# Answer
# PHP, ~~40~~ ~~32~~ 31 bytes

*-8 bytes thanks to Luis felipe*
*-1 byte thanks to Jo King*

```
<?=date('ymd.hi',$argv[1]/1e3);

```

Try it online!

Simple naive answer. PHP's `date` function takes a format string and an integer timestamp. Input from cli arguments, which is a string by default, then `/1e3` because `date` expects second-precise timestamps. This also coerces the string to a number.
> 7 votes

# Answer
# PowerShell, ~~59~~ 58 bytes

```
"{0:yyMMdd.HHmm}"-f(Date 1/1/1970).AddSeconds("$args"/1e3)

```

Try it online!

Gets the `Date` of `1/1/1970` (defaults to 00:00:00am), then `Add`s the appropriate number of `Seconds`. Passes that to the `-f`ormat operator, which correctly formats the datetime.

Probably culture-dependent. This works on TIO, which is `en-us`.

*-1 byte thanks to shaggy.*
> 5 votes

# Answer
# MATL, 28 bytes

*Thanks to @skiilaa for a correction in the output format.*

```
864e5/719529+'YYmmDD.HHMM'XO

```

Try it online!

### Explanation

MATL, like MATLAB, defines date/time numbers as the (possibly non-integer) number of days since time 00:00 of the reference "date" 0-Jan-0000.

Thus we take the input, divide it by 86400000 (number of milliseconds in one day), add 719529 (number of days from MATL's reference to UNIX reference), and convert to the desired format 'YYmmDD.HHMM'.
> 5 votes

# Answer
# GNU AWK, ~~34~~ 33 characters

```
$0=strftime("%y%m%d.%H%M",$0/1e3)

```

(`strftime()` is GNU extension, will not run in other AWK implementations.)

Thanks to:

Sampler run:

```
bash-4.4$ awk '$0=strftime("%y%m%d.%H%M",$0/1e3)' <<< 1547233866744
190111.2111

```

Try it online!
> 4 votes

# Answer
# Perl 6,  ~~111 89~~  87 bytes

```
{~DateTime.new($_/Ⅿ,:formatter{"{(.year%Ⅽ,.month,.day).fmt('%02d','')}.{(.hour,.minute).fmt('%02d','')}"})}

```

Try it (111)

```
{TR/-//}o{S/..//}o{.yyyy-mm-dd~'.'~(.hour,.minute).fmt('%02d','')}o{DateTime.new($_/Ⅿ)}

```

Try it (89)

```
{TR/- //}o{S/..//}o{.yyyy-mm-dd~'.'~(.hour,.minute).fmt('%02d')}o{DateTime.new($_/Ⅿ)}

```

Try it (87)

## Explanation:

The `o` infix operator takes two functions and creates a composite function. The rightmost one gets called first, and the one to the left gets called with its result.

Basically we use 4 block lambdas to generate a single lambda.

Which is not much different to how a WhateverCode lambda like `* + *` gets created.

---

Divide by 1000 and use that to create a DateTime object.

```
{DateTime.new($_/Ⅿ)} # Ⅿ is ROMAN NUMERAL ONE THOUSAND (3 bytes)

```

The result gets used by:

```
{
   .yyyy-mm-dd # 2019-01-11

   ~ '.' ~     # str concatenation with '.'

   ( .hour, .minute ).fmt('%02d') # add leading 0s (returns List)
}

```

That leaves us with a string like `2019-01-11.19 11`

We need to remove the first two digits

```
{S/..//}

```

We also need to remove `-` and

```
{TR/- //}

```
> 3 votes

# Answer
# Python 2, 64 bytes

```
lambda s:strftime('%y%m%d.%H%M',gmtime(s/1e3))
from time import*

```

Try it online!

The input is considered to be in UTC.
> 3 votes

# Answer
# , ~~58~~ 56 bytes

```
format(as.POSIXct(scan()/1e3,,'1970-1-1'),'%y%m%d.%H%M')

```

Try it online!
> 3 votes

# Answer
# C (gcc) (32-bit, little endian), 67 bytes

```
f(t,s)long long t;{t/=1e3;strftime(s,12,"%y%m%d.%H%M",gmtime(&t));}

```

Try it online!

On an ILP64 platform, the following **55 byte** version should work:

```
f(t,s){t/=1e3;strftime(s,12,"%y%m%d.%H%M",gmtime(&t));}

```
> 3 votes

# Answer
# Javascript ES6, ~~76~~ 66 bytes

```
x=>new Date(x).toJSON().slice(2,16).replace(/\D/g,a=>a>'S'?'.':'')

```

Try it online

-10 bytes thanks to Shaggy!

---

```
x // timestamp
=>
new Date(x) // date object from timestamp
.toJSON() // same as .toISOString()
.slice(2,16) // cut off excess
.replace(/\D/g, // match all non-digits
a // a is matched character
=>
a>'S'?'.' // if a is T (bigger than S is shorter) replace it with .
:''       // if it's not T, replace it with nothing
          // this way the dashes get removed and the dot gets put in the right place
) // end of replace

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~67~~ ~~61~~ 60 bytes

```
n=>$"{new DateTime(1970,1,1).AddTicks(n*10000):yyMMdd.HHmm}"

```

For reasons unknown to me, DateTime.UnixEpoch doesn't work.

Try it online!
> 2 votes

# Answer
# Perl 6, ~~57~~ 50 bytes

```
{TR:d/T:-/./}o{substr ~DateTime.new($_/1e3): 2,15}

```

Try it online!

Takes the default stringification of a Datetime, in the format `yyyy-mm-ddThh:mm:ssZ` and modifies it to fit the output format. Perl 6 is in need of a date formatter method.

### Explanation:

```
                       Datetime.new($_/1e3) # Create a date time
                      ~                 # Stringify it to the format yyyy-mm-ddThh:mm:ssZ
                                        # e.g. 2019-01-11T19:11:06.744000Z
               substr                      : 2,15  # Take the middle 15 characters
 {TR:d/T  /./}o   # Then replace 'T' with '.'
        :-        # Then remove ':' and '-'

```
> 2 votes

# Answer
# C (clang), 117 111 bytes

Thanks to @chux and @ceilingcat for the suggestions.

```
#import<time.h>
*l;f(long t){t/=1e3;printf("%02d%02d%02d.%02d%02d",5[l=gmtime(&t)]%100,l[4]+1,l[3],l[2],l[1]);}

```

Try it online!
> 2 votes

# Answer
# Twig, 25 characters

```
{{d[:-3]|date('ymd.hi')}}

```

This is a template. Call it by including it and pass the Unix time as parameter d.

Sample usage:

```
{{include('datetime.twig', {'d': 1547233866744})}}

```

Try it on TwigFiddle
> 2 votes

# Answer
# JavaScript, 64 bytes

```
n=>'2356891911121415'.replace(/1?./g,x=>new Date(n).toJSON()[x])

```

Try it online!
> 2 votes

# Answer
# Java 8, 78 bytes

```
n->new java.text.SimpleDateFormat("yyMMdd.HHmm").format(new java.util.Date(n))

```

Try it online.

**Explanation:**

```
n->                       // Method with long parameter and String return-type
  new java.text.SimpleDateFormat("yyMMdd.HHmm")
                          //  Create the formatter
   .format(               //  Format the date to a String in this format and return it:
     new java.util.Date(  //   Create a new Date
      n))                 //   With the input-long as timestamp

```
> 2 votes

# Answer
# jq, 33 characters

(30 characters code + 3 characters command line option)

```
./1000|strftime("%y%m%d.%H%M")

```

Sample run:

```
bash-4.4$ jq -r './1000|strftime("%y%m%d.%H%M")' <<< 1547233866744
190111.1911

```

Try it online!
> 1 votes

# Answer
# ksh, 36 bytes

```
printf "%(%y%m%d.%H%M)T" $(($1/1e3))

```

Try it online!

Thanks to Jo King for 15 bytes saved
> 1 votes

# Answer
# MediaWiki, 46 bytes

```
{{#time:ymd.Hi|@{{#expr:floor({{{1}}}/1e3)}}}}

```
> 1 votes

---
Tags: code-golf, date
---


title: Matrix Jigsaw Puzzles

text:
# Question
Title: Matrix Jigsaw Puzzles
### Input:

* An integer `n`
* Two equal-sized square matrices (with their width/height being a multiple of `n`)

### Output:

One of two distinct values of your own choice, one being for truthy results and one for falsey results (so yes, `1/0` instead of `true/false` are valid outputs for languages like Java, even though they're not considered official truthy/falsey values).

The truthy/falsey output indicates whether we can rearrange blocks of size `n by n` in one matrix to make it equal to the other matrix.

### Example:

Input:

```
Matrix 1:
1 2 3 4 5 6
7 8 9 0 1 2
3 4 5 6 7 8
9 8 7 6 5 4
3 2 1 0 9 8
1 1 1 1 1 1

Matrix 2:
3 2 9 8 7 8
1 1 1 1 5 4
3 4 5 6 1 0
9 0 7 6 1 1
5 6 1 2 3 4
1 2 7 8 9 8

Integer n:
2

```

Output: `truthy`

**Why?**

If we split the matrices in blocks of `2 by 2`, we can see that all blocks on one matrix can also be found in the other matrix:

```
Matrix 1:
1 2 | 3 4 | 5 6
7 8 | 9 0 | 1 2
---------------
3 4 | 5 6 | 7 8
9 8 | 7 6 | 5 4
---------------
3 2 | 1 0 | 9 8
1 1 | 1 1 | 1 1

Matrix 2:
3 2 | 9 8 | 7 8
1 1 | 1 1 | 5 4
---------------
3 4 | 5 6 | 1 0
9 0 | 7 6 | 1 1
---------------
5 6 | 1 2 | 3 4
1 2 | 7 8 | 9 8

```

## Challenge rules:

* You can assume the matrices will only contain non-negative digits (range `[0,9]`)
* You can assume the width/height of the matrices are equal, and a multiple of `n`
* You can assume `n` will be in the range `[1, 50]`, and the width/height of the matrices are in the range `[1,100]`.
* The individual blocks of `n by n` can only be used once to determine if the matrices are permutations of each other when split into blocks of `n by n`.
* There can be multiple `n by n` blocks that are the same.
* The `n by n` blocks will remain in the same orientation when checking if the two matrices are permutation of each other when split into blocks of `n by n`.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:
Matrix 1:       Matrix 2:       Integer:
1 2 3 4 5 6     3 2 9 8 7 8     2
7 8 9 0 1 2     1 1 1 1 5 4
3 4 5 6 7 8     3 4 5 6 1 0
9 8 7 6 5 4     9 0 7 6 1 1
3 2 1 0 9 8     5 6 1 2 3 4
1 1 1 1 1 1     1 2 7 8 9 8
Output:
truthy

Input:
Matrix 1:       Matrix 2:       Integer:
1 2 3 4 5 6     3 2 9 8 7 8     1
7 8 9 0 1 2     1 1 1 1 5 4
3 4 5 6 7 8     3 4 5 6 1 0
9 8 7 6 5 4     9 0 7 6 1 1
3 2 1 0 9 8     5 6 1 2 3 4
1 1 1 1 1 1     1 2 7 8 9 8
Output:
truthy

Input:
Matrix 1:       Matrix 2:       Integer:
1 2 3 4 5 6     3 2 9 8 7 8     3
7 8 9 0 1 2     1 1 1 1 5 4
3 4 5 6 7 8     3 4 5 6 1 0
9 8 7 6 5 4     9 0 7 6 1 1
3 2 1 0 9 8     5 6 1 2 3 4
1 1 1 1 1 1     1 2 7 8 9 8
Output:
falsey

Input:
Matrix 1:    Matrix 2:    Integer:
1 2 3 4      1 2 3 4      4
2 3 4 5      2 3 4 5
3 4 5 6      3 4 5 6
4 5 6 7      4 5 6 7
Output:
truthy

Input:
Matrix 1:    Matrix 2:    Integer:
1 2 3 4      3 4 3 4      2
2 3 4 5      4 5 4 5
3 4 5 6      1 2 5 6
4 5 6 7      2 3 6 6
Output:
falsey

Input:
Matrix 1:    Matrix 2:    Integer:
1 2          2 3          1
3 4          1 1
Output:
falsey

Input:
Matrix 1:    Matrix 2:    Integer:
0            8            1
Output:
falsey

Input:
Matrix 1:    Matrix 2:    Integer:
1 2 3 4      1 2 1 2      2
5 6 7 8      5 6 5 6
9 0 0 9      0 9 9 0
4 3 2 1      2 1 4 3
Output:
falsey

Input:
Matrix 1:    Matrix 2:    Integer:
1 2 1 2      9 5 1 2      2
3 4 3 4      7 7 3 4
8 3 9 5      1 2 8 3
6 1 7 7      3 4 6 1
Output:
truthy

Input:
Matrix 1:      Matrix 2:      Integer:
1 0 2 0 0 3    1 1 1 0 0 3    2
1 1 1 1 1 1    2 0 1 1 1 1
2 2 2 2 2 2    2 2 2 2 2 2
3 3 3 3 3 3    3 3 3 3 3 3
4 4 4 4 4 4    4 4 4 4 4 4
5 5 5 5 5 5    5 5 5 5 5 5
Output:
falsey

```

Pastebin with matrices in `[[,]]` format.

# Answer
> 4 votes
# Jelly,  ~~10~~  9 bytes

```
ż⁹/ẎsṢʋ€E

```

**Try it online!** (or with pre-processing for easier copy & paste from the test cases)

A dyadic Link accepting a list of the two matrices (as lists of lists) on the left and the integer on the right which yields `1` or `0` for truthy or falsey respectively.

### How?

```
ż⁹/ẎsṢʋ€E - Link: [M1, M2]; N
       €  - for each of [M1, M2]:
      ʋ   -   last four links as a dyad (i.e. f(M, N)):
 ⁹        -     (chain's right argument, N)
 ⁹/       -     N-wise-reduce with:
ż         -       zip together
   Ẏ      -     tighten
    s     -     split into chunks of length N
     Ṣ    -     sort
        E - equal?

```

# Answer
> 8 votes
# APL (Dyalog Extended), ~~19~~ ~~18~~ 17 bytes

-2 thanks to ngn.

Anonymous tacit infix function. Takes `n` as left argument and list of two matrices as right argument. Requires zero-indexing (`⎕IO←0`). Incidentally, this function works on arrays of any number of dimensions.

```
≡.{∧,⍵⊂⍨⊂0=⍺|⍳≢⍵}

```

Try it online!

`≡.{``}` identical results of the following function applied to each matrix  with `n` as ?

`≢⍵` size of matrix

indices 0…size–1

`⍺|` division remainder when divided by `n`

enclose to use along all dimensions

`⍵⊂⍨` use that to partition\* the matrix into a matrix of submatrices
<sup>* begins new partition when corresponding element is less than the previous; removes elements marked by zero</sup>

`,` ravel the matrix into a list of submatrices

sort ascending

# Answer
> 6 votes
# Python 2, ~~108~~ 103 bytes

```
lambda s,*a:len(set(`sorted(sum([zip(*[iter(zip(*l))]*s)for l in zip(*[iter(m)]*s)],[]))`for m in a))<2

```

Try it online!

# Answer
> 6 votes
# Perl 6, ~~94 68~~ 63 bytes

```
{[eqv] map *.rotor($^a).map({[Z] $_}).flat.rotor($a²).sort,@_}

```

Try it online!

Anonymous code block that takes input as `size, [matrix1, matrix2]` and returns a boolean `True/False`. There might be a more efficient way of splitting the matrix into chunks than `rotor`.

### Explanation:

```
{                                                            }  # Anonymous code block
       map                                                ,@_   # For both matrices
           *.rotor($^a)   # Split the matrix into N sized chunks
                       .map({[Z] $_})  # Then zip each of those chunks together
                                     .flat  # Flatten the resulting list
                                          .rotor($a²)  # Then split into the NxN lists
                                                     .sort   # And sort them
 [eqv]    # And then check if the lists are equivalent

```

# Answer
> 6 votes
# 05AB1E, 14 bytes

```
εε²ô}ø˜²ô²ô{]Ë

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 88 bytes

```
(n,a,b)=>(g=a=>a.map((r,y)=>r.map((v,x)=>o[y/n<<7|x/n]+=[v]),o=[])&&o.sort()+o)(a)==g(b)

```

Try it online!

### How?

This code is:

* extracting all sub-matrices in each input matrix as a concatenation of cells
* sorting the sub-matrices in lexicographical order
* testing whether the result is the same for both input matrices

It is taking advantage of the limits described in the challenge:

* A matrix consists of single digits, so we can just concatenate all cells of a sub-matrix without any separator and still get a unique representation of it (e.g. `[[1,2],[3,4]]` can be stored as `"1234"`).
* The width of the input matrices is less than or equal to \\$100\\$. To convert the coordinates \\$(x,y)\\$ in an input matrix into a unique slot index \\$I\\$ in our storage area, we can do:

$$I=\left\lfloor\frac{y}{n}\right\rfloor\times128+\left\lfloor\frac{x}{n}\right\rfloor$$

or as JS code: `y / n << 7 | x << n`

### Commented

```
(n, a, b) =>           // n, a, b = input variables (integer, matrix 1, matrix 2)
  (g = a =>            // g = helper function taking one of the two matrices
    a.map((r, y) =>    // for each row r[] at position y in a[]:
      r.map((v, x) =>  //   for each value v at position x in r[]:
        o[             //     update o[]:
          y / n << 7 | //       the position of the slot is computed by taking advantage
          x / n        //       of the limit on the matrix width (see above)
        ] += [v]       //     coerce v to a string and append it to o[slot]
                       //     all slots are initially undefined, so all resulting strings
                       //     are going to start with "undefined", which is harmless
      ),               //   end of inner map()
      o = []           //   start with o = empty array
    ) &&               // end of outer map()
    o.sort() + o       // sort o[] and coerce it to a string by concatenating it with itself
  )(a) == g(b)         // test whether g(a) is equal to g(b)

```

# Answer
> 4 votes
# TSQL, 164 bytes

Populating a table variable in order to have input, this creating input and inserting data has not been included in the byte count. Only the actual query to extract the data.

Golfed(not including test table - it can be found in the ungolfed version):

```
SELECT iif(exists(SELECT*FROM(SELECT string_agg(v,'')within
group(order by x,y)s,m FROM @t GROUP BY x/@,y/@,m)x
GROUP BY s HAVING max(m)=min(m)or sum(m-.5)<>0),0,1)

```

Ungolfed:

```
-- test data
DECLARE @ INT = 2
-- x = x-position of the input
-- y = y-position of the input
-- v = value
-- m = matrix(0 or 1)
DECLARE @t table(x int, y int, v int, m int)
--insert first matrix values
INSERT @t values
(0,0,1,0),(0,1,2,0),(0,2,1,0),(0,3,2,0),
(1,0,3,0),(1,1,4,0),(1,2,3,0),(1,3,4,0),
(2,0,8,0),(2,1,3,0),(2,2,9,0),(2,3,5,0),
(3,0,6,0),(3,1,1,0),(3,2,7,0),(3,3,7,0)
INSERT @t values
(0,0,9,1),(0,1,5,1),(0,2,1,1),(0,3,2,1),
(1,0,7,1),(1,1,7,1),(1,2,3,1),(1,3,4,1),
(2,0,1,1),(2,1,2,1),(2,2,8,1),(2,3,3,1),
(3,0,3,1),(3,1,4,1),(3,2,6,1),(3,3,1,1)

-- query
SELECT iif(exists
  (
    SELECT *
    FROM
    (
      SELECT string_agg(v,'')within group(order by x,y)s,m
      FROM @t
      GROUP BY x/@,y/@,m
    ) x
    GROUP BY s
    HAVING max(m)=min(m)or sum(m-.5)<>0
  ),0,1)

```

**Try it out**

# Answer
> 4 votes
# Java (JDK), 217 bytes

```
(n,a,b)->{java.util.Arrays A=null;int l=a.length,x=l/n,j=0,z;var c=new String[x*x];A.fill(c,"");var d=c.clone();for(;j<l*l;d[z]+=b[j/l][j++%l])c[z=j/l/n+j%l/n*x]+=a[j/l][j%l];A.sort(c);A.sort(d);return A.equals(c,d);}

```

Try it online!

## Explanation

The idea is to pick each small cell as a string, which is comparable, and then to sort those strings and compare them in order.

```
(n,a,b)->{
 java.util.Arrays A=null;             // Shortcut A for the several java.util.Arrays that'll come
 int l=a.length,x=l/n,i=0,j,z;        // Variable declarations
 var c=new String[x*x];               // Declare the small squares list
 A.fill(c,"");                        // Fill the lists of small squares with the empty string.
 var d=c.clone();                     // Make a copy of the list, for the second matrix
 for(;i<l;i++)
  for(j=0;j<l;d[z]+=b[i][j++])        // For each matrix cell
   c[z=i/n+j/n*x]+=a[i][j];           // Fill the small square with the value, string-wise
 A.sort(c);A.sort(d);                 // Sort both small squares list
 return A.equals(c,d);                // Return true if they're equal, false otherwise.
}

```

Note: some lines are obsolete.

## Credits

* -12 bytes thanks to Kevin Cruijssen!
* -4 bytes thanks to ceilingcat.

# Answer
> 4 votes
# Japt, 18 bytes

```
®mòV yòV rc n qÃr¥

```

Try it online!

Explanation:

```
®              Ã      #Apply this to each of the input matrices:
 mòV                  # Split each row into groups of n
     yòV              # Split each column into groups of n
         rc           # Flatten into a list of nxn submatrices
            n         # Sort that list
              q       # Turn it into a string
                r¥    #Return true if both matrices had identical results

```

The "Turn it into a string" step is necessary because Japt doesn't compare arrays by value and the builtin to work around that doesn't work for multidimensional arrays.

# Answer
> 3 votes
# Charcoal, ~~54~~ 49 bytes

```
1ＦθＦ⪪ιηＦ÷Ｌ§κ⁰η⊞υＥκ§⪪μηλＷ∧υ⊟υ¿№✂υ⁰⊘⊕Ｌυ¹ι≔Φυ⁻⌕υιλυ⎚

```

Try it online! Link is to verbose version of code. Takes input as an array of equal-sized two-dimensional arrays. Outputs 1 on success, nothing on failure. Explanation:

```
1

```

Assume success.

```
Ｆθ

```

Loop over the arrays.

```
Ｆ⪪ιη

```

Divide the array into `n`-sized row chunks.

```
Ｆ÷Ｌ§κ⁰η

```

Loop over each column chunk.

```
⊞υＥκ§⪪μηλ

```

Extract the column chunk for each row of the row chunk and save the resulting submatrix in a list.

```
Ｗ∧υ⊟υ

```

While the list is nonempty, remove the last chunk of the list, which under normal circumstances comes from the second array.

```
¿№✂υ⁰⊘⊕Ｌυ¹ι

```

Count the number of occurrences of that chunk in the first half of the list, which under normal circumstances contains the remaining chunks from the first array.

```
≔Φυ⁻⌕υιλυ

```

If nonzero then remove the first occurrence of that chunk from the list.

If zero then clear the output, making it falsy.

# Answer
> 3 votes
# , 55 bytes

```
[:-:/[([:/:~([*-@[)]\,@])"3(((;])@(#@]$1{.~[),;.1])&>])

```

Try it online!

A horrible solution, just made it work - I have no power to golf it...

# Answer
> 2 votes
## Haskell, ~~74~~ 73 bytes

```
import Data.Lists
i#m|c<-chunksOf i=c.transpose=<<c m
(m!n)i=i#m\\i#n==[]

```

Note: TIO hasn't installed `Data.Lists`, so I'm using `Data.List` instead an add the missing function `chunksOf`: Try it online!

```
i#m=           -- function '#' makes a list of all transposed jigsaw blocks of matrix 'm'
               -- of size 'i'
 c<-chunksOf i -- define helper function 'c' that splits it's argument into
               -- chunks of site 'i'
         c m   -- split the matrix into chunks of size 'i'
      =<<      -- for each chunk
   transpose   --   transpose
 c.            --   and split into chunks of size 'i', again
               -- flatten one level of nesting ('=<<' is concatMap)

(m!n)i=        -- main function
    i#m\\i#n   -- remove every element of i#n from i#m
      ==[]     -- and check if it results in an empty list

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 178 bytes

```
(a,b,n)=>{string[]s(int[][]c){int i=0,l=a.Length,m=l/n;var r=new string[m*m];for(;i<l*l;)r[i/l/n*m+i%l/n]+=c[i/l][i++%l];Array.Sort(r);return r;}return s(a).SequenceEqual(s(b));}

```

Try it online!

-1 thanks to @KevinCruijssen!
-8 thanks to @ceilingcat!

Less golfed code:

```
// anonymous function
// a and b are 2d jagged arrays
// n is the size of the sub matrix
(a,b,n)=>{
  // helper function that translates
  // the sub matrices into strings
  // of digits.
  string[]s(int[][]c){
    // i and j are loop counters
    int i=0,j,
      // l is the size of a side of a matrix
      l=a.Length,
      // m is the number of sub matrices
      // per side of a matrix
      m=l/n;
    // the concatenated digits are
    // stored in a single dimension
    // array
    var r=new string[m*m];
    // flattened loop builds up
    // the digit strings
    for(;i<l*l;)
      r[i/l/n*m+i%l/n]+=c[i/l][i++%l];
    // The resulting array is
    // sorted before it is returned for
    // ease of comparison.
    Array.Sort(r);
    return r;
  }
  return s(a).SequenceEqual(s(b));
}

```

# Answer
> 1 votes
# Red, ~~148~~ ~~147~~ 142 bytes

```
func[a b n][g: func[m][
sort collect[loop k:(length? m)/ n[i: 0
loop k[keep/only
collect[loop n[keep
take/part m/(i: i + 1) n]]]]]](g a)= g b]

```

Try it online!

# Answer
> 1 votes
# PHP, ~~186~~ ~~163~~ 162 bytes

```
function($a,$b,$n){$f=function($j,$n){foreach($j as$x=>$r)foreach($r as$y=>$v)$o[count($j)*($x/$n|0)+$y/$n|0].=$v;sort($o);return$o;};return$f($a,$n)==$f($b,$n);}

```

Try it online!

Like all good challenges, I started off thinking this was fairly easy and it threw me some curves. Nicely done @Kevin Cruijssen!

Chunks the matrix into strings containing the values for each block. Arrays are then sorted and compared for equality.

Ungolfed:

```
function jigsaw_chunk( $j, $n ) {
    foreach( $j as $x => $r ) {
        foreach( $r as $y => $v ) {
            $o[ count( $j ) * floor( $x/$n ) + floor( $y/$n )] .= $v;
        }
    }
    sort( $o );
    return $o;
}

function jigsaw_test( $a, $b, $n ) {
    return jigsaw_chunk( $a, $n ) == jigsaw_chunk( $b, $n );
}

// Test 6
var_dump( jigsaw_test( [[1,2],[3,4]], [[2,3],[1,1]], 1 ) );

```

Output

```
bool(false)

```

---
Tags: code-golf, number, integer, matrix
---