title: Overlapping String-Blocks

text:
# Question
Title: Overlapping String-Blocks
## Challenge:

Given a list of multi-line strings, overlap them (in the top-left) and output the result.

**Example:**

Input: `["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]`
Output:

```
cbaa
bbaa
bbaa
aaaa

```

## Challenge rules:

* Input-format is flexible. You are allowed to get the input as a 2D list of lines (i.e. `[["aaaa","aaaa","aaaa","aaaa"],["bb","bb","bb"],["c"]]`) or 3D list of characters (i.e. `[[["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"]],[["b","b"],["b","b"],["b","b"]],[["c"]]]`). You are allowed to take all the inputs one by one through STDIN. Etc.
* Output format is strict. You can choose to print or return the multi-line string. (If your language doesn't have any strings, outputting as a 2D list of characters is allowed as alternative. But only if your language doesn't have strings at all.)
* The order of the input-list is of course important (but you are allowed to take the input in reverse if you choose to).
* Inputs will only contain printable ASCII in the unicode range \\$\[33,126\]\\$ (`!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~`).
* Inputs will only be rectangles (so no weird shapes). The output aren't necessary rectangles, though.
* Trailing spaces and a single trailing newline is allowed. Leading spaces and/or newlines not.

## 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: `["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]`
Output:

```
cbaa
bbaa
bbaa
aaaa

```

Input: `["12345\n54321","00\n00\n00\n00","001\n011\n012"]`
Output:

```
00145
01121
012
00

```

Input: `["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]`
Output:

```
this%^
is_a_+
testty
uiopas
t!
h_
i_
n_
g_

```

# Answer
# Jelly, 3 bytes

```
a/Y

```

Try it online!

Hadn't used Jelly in a while but I thought the challenge in the comments was beatable. Very directly uses logical and (`a`) to perform the stacking operation between each element of the input (`/`). `Y` is used to print in the required format.
> 6 votes

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

*Saved 2 bytes thanks to @Grimy*

Assumes that the returned string is printed on a terminal that supports ANSI escape codes. Contains the unprintable character `ESC`, which is escaped (no pun intended) as `\x1B` below.

```
a=>`\x1B[2J\x1B[H`+a.join`\x1B[H`

```

This doesn't work on TIO, but you can Try it online! to see the raw output instead.

### How?

The CSI sequences used are:

* ED (Erase in Display):

`ESC``[``2``J`

where \\$2\\$ means *"clear entire screen"*
* CUP (Cursor Position):

`ESC``[``H`

which means *"moves the cursor to row \\$n\\$, column \\$m\\$"* where both \\$n\\$ and \\$m\\$ are omitted and implicitly set to \\$1\\$ (top-left corner of the screen).

### Example output
> 12 votes

# Answer
# , ~~120~~, ~~111~~ ~~110~~ 107 bytes

```
function(x,`!`=ncol,M=array('',Reduce(pmax,Map(dim,x)))){for(m in x)M[1:!t(m),1:!m]=m
write(t(M),1,!M,,'')}

```

Try it online!

A function accepting a list of matrix of characters (3D input is accepted).

(as you can notice from the byte count, this is not very easy to do in R...)

* -9 bytes thanks to @Giuseppe
* -4 bytes thanks to @RobinRyder
> 7 votes

# Answer
# Python 2, 88 bytes

```
n,f=None,filter
for l in map(n,*input()):print''.join(f(n,x)[-1]for x in map(n,*f(n,l)))

```

Try it online!

---

### Explanation (with example):

Takes a 2D list as input.

```
Input: [["12345","54321"],["00","00","00","00"],["001","011","012"]]

```

First the input list is zipped, to get the rows of each input rectangle (`map(None,l)` is the same a zip longest):

```
map(n,*input())   gives:

('12345', '00', '001')
('54321', '00', '011')
(None, '00', '012')
(None, '00', None)

```

Each of these rows are then filtered to removed `None`s, and zipped again:

```
map(None,*filter(None,l))

filter(None,l) for each l gives:

('12345', '00', '001')
('54321', '00', '011')
('00', '012')
('00',)

map*... gives:

[('1', '0', '0'), ('2', '0', '0'), ('3', None, '1'), ('4', None, None), ('5', None, None)]
[('5', '0', '0'), ('4', '0', '1'), ('3', None, '1'), ('2', None, None), ('1', None, None)]
[('0', '0'), ('0', '1'), (None, '2')]
['0', '0']

```

Which is a list of characters for each position of the desired result. These lists are filtered again, and the last one is taken:

```
filter(None,x)   gives:

[('1', '0', '0'), ('2', '0', '0'), ('3', '1'), ('4',), ('5',)]
[('5', '0', '0'), ('4', '0', '1'), ('3', '1'), ('2',), ('1',)]
[('0', '0'), ('0', '1'), ('2',)]
['0', '0']

and with [-1]:

['0', '0', '1', '4', '5']
['0', '1', '1', '2', '1']
['0', '1', '2']
['0', '0']

```

Lastly the resulting lists are joined and printed:

```
print''.join(..)

00145
01121
012
00

```
> 5 votes

# Answer
# R, ~~107~~ 97 bytes

```
function(x)for(i in 1:max(lengths(x))){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat('
')}

```

Doesn't appear to work on TIO, which might be related to the use of the `\r` carriage return character. It does work on my local installation of R.

Takes input as a list containing a vector of rows:

```
x <- list(c("aaaa","aaaa","aaaa","aaaa"),c("bb","bb","bb"),c("c"))

```

Loops over the rows of each rectangle, printing a carriage return after each, restarting the line.

If we stretch the rules a little, we can do away with checking the length of the input and just loop infinitely, printing a huge amount of newlines:

# R, 85 bytes

```
function(x)for(i in 1:8e8){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat('
')}

```
> 5 votes

# Answer
# APL (Dyalog Unicode), 22 bytesSBCS

Anonymous tacit prefix function taking list of 2D character arrays as argument. Prints.

```
(⊃{⍺@(⍳⍴⍺)⊢⍵}/)⌽,∘⊂1⌷↑

```

Try it online!

This works by creating a canvas, then appending that to the list of blocks, and reducing (folding) with a function that places blocks in the corner.

mix the 2D block to create an orthogonal 3D block, padding them with spaces as needed

`1⌷` take the first layer

enclose that
then
`⌽,` prepend the reversed list of blocks

`(``)` apply the following tacit function:

`{``}/` reduce using the following anonymous lambda:

`⊢⍵` with the right argument as canvas…

`⍺@(``)` amend with the elements of the left argument, placed **at** the following indices:

`⍴⍺` the shape of the left argument

the **ɩ**ndices of an array of that shape

disclose (because the reduction enclosed to reduce rank)
> 4 votes

# Answer
## Haskell, 66 bytes

```
unlines.foldl((const?)?)[]
(g?(a:b))(c:d)=g a c:(g?b)d;(_?a)b=a++b

```

Input is taken as a list of list of strings in reverse order, e.g. for the first test case: `[["c"],["bb","bb","bb"],["aaaa","aaaa","aaaa","aaaa"]]`.

Try it online!
> 4 votes

# Answer
# 05AB1E, 12 bytes

Port of TFeld's python solution
2 bytes saved thanks to *Grimy*

```
ζεðKζðδK€θJ,

```

Try it online!

**Explanation**

```
ζ             # transpose input with space as filler
 ε            # apply to each
  ðK          # remove spaces
    ζ         # transpose with space as filler
     ðδK      # deep remove spaces
        €θ    # get the tail of each
          J   # join each
           ,  # print

```

**Alternative 14 byte version**

```
õζεÅ»DŠg.$J}θ,

```

Try it online!

**Explanation**

```
õζ              # zip with empty string as filler
  ε             # apply to each
   Å»      }    # cumulative reduce by
     D          # duplicate second input
      Š         # move down twice on stack
       g.$      # remove len(other_copy) elements from the other input
          J     # join with other copy
            θ,  # print the last element

```
> 3 votes

# Answer
# Canvas, 5 bytes

```
Ｈ１１╋╋

```

Try it here!

If overlapping `/`+`\``X`, `-` \+ `|``+`, etc. would be fine, 2 bytes would work.
> 2 votes

# Answer
# Python 2, 77 bytes

```
for t in map(None,*input()):
 r=''
 for s in t:
	if s:r=s+r[len(s):]
 print r

```

Try it online!
> 2 votes

# Answer
# PowerShell 6, console only, 20 bytes

based on Arnauld's answer. This work with console only and doesn't work on TIO.

```
cls
$args-join"`e[H"

```

Try it online!

---

# PowerShell, 103 bytes

```
$args|%{$l=$_-split'
';$r=&{$r+($l|%{''})|%{($x=$l[$j++])+($_-replace"^.{0,$("$x"|% Le*)}")}|?{$_}}}
$r

```

Try it online!

Unrolled:

```
$args|%{
    $l=$_-split"`n"
    $r=&{                           # run this scriptblock in a new scope
        $r+($l|%{''})|%{
            $x=$l[$j++]             # a new line or $null
            $w="$x"|% Length
            $y=$_-replace"^.{0,$w}" # remove first chars from the current line
            $x+$y                   # output the new line plus tail of the overlapped line
        }|?{$_}                     # filter out not empty lines only
    }                               # close the scope and remove all variables created in the scope
}
$r

```
> 2 votes

# Answer
# C# (.NET Core), 68 + 23 = 91 bytes

```
n=>{C.Clear();n.ForEach(k=>{C.SetCursorPosition(0,0);C.Write(k);});}

```

23 bytes is for the import, `using C=System.Console;`

Does not work in TIO, since it isn't a console.

Try it online!
> 1 votes

# Answer
# Ruby, 67 bytes

Input is a list of lines. Builds a list of lines and does overwriting as it goes through the inputs, then joins them with a newline (represented by the variable `$/`) at the end to match the strict output.

```
->i,*r{i.map{|e|j=-1;e.map{|l|r[j+=1]||='';r[j][0,l.size]=l}};r*$/}

```

Try it online!
> 1 votes

# Answer
# C (GCC, MinGW) 138 bytes

Assumes that CR puts the cursor at the start of the current line.

```
d,i,l;f(S,n,p,t)char**S,*p,*t;{for(d=i=0;i<n;d+=l)p=strchr(t=S[i],10),printf("\n%.*s\r"+!!i,l=p?p-t:strlen(t),t),S[i++]+=l+!!p;d&&f(S,n);}

```

Tested with:

```
int main()
{
    char *test1[] = {"aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"};
    char *test2[] = {"12345\n54321","00\n00\n00\n00","001\n011\n012"};
    char *test3[] = {"sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"};

    f(test1, 3);
    f(test2, 3);
    f(test3, 3);
}

```
> 1 votes

# Answer
# Octave, ~~71~~ 67 bytes

```
function y=f(x)
for k=1:size(x)
y(1:(t=size(x{k})),1:t(2))=x{k};end

```

Function that takes a vertical cell array of char matrices, and returns a char matrix.

Try it online! Or verify all test cases.
> 1 votes

# Answer
# Japt `-P`, 7 bytes

Takes input as an array of multi-line strings, outputs a single multi-line string.

```
ú y_¸¬Ì

```

Try it

```
ú y_¸¬Ì     :Implicit input of array
ú           :Right pad each line of each element with spaces to the length of the longest
  y         :Transpose
   _        :Map
    ¸       :  Split on spaces
     ¬      :  Join
      Ì     :  Last character
            :Implicitly join and output

```
> 1 votes

# Answer
# Javascript (browser), ~~216~~ ~~208~~  204 bytes

My attempt at this. I'm not happy about the size, and there must certainly be more for improvement, but I'm not that experienced at golfing.

```
var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;i++){j=a[i];if(!j)j=b[i];a[i]=b[i].padStart(j.length,j)}return a}).map(s=>x(s)).join(n)

```

Anyways, what it does is first split all the strings, then reverse all the strings, then whilst looping in a reduce operation padStart all the strings together. Then reverse all the strings again and then join them back with newlines.

Special thanks to Kevin Cruijssen for reminding me that the last part in a for loop happens at the end and a total byte savings of 8 bytes.

```
var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;a[i]=b[i++].padStart(j.length,j))if(!(j=a[i]))j=b[i];return a}).map(s=>x(s)).join(n)

console.log(f(["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]));
console.log(f(["12345\n54321","00\n00\n00\n00","001\n011\n012"]));
console.log(f(["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]));
```
> 1 votes

# Answer
# C (gcc), ~~51~~ 47 bytes

```
f(char**s){for(;*s;printf("\e[s%s\e[u",*s++));}

```

Try it online!

-4 bytes thanks to ceilingcat.

Uses the CSI sequences for save/restore cursor position. Just iterates over the passed string array (in the same format as `argv`) and prints `<save position>string<restore position>` for each.

This does leave the cursor at the top left, so when running at the terminal it is important to leave enough newlines afterwards so that the prompt doesn't clobber the input.
> 1 votes

# Answer
# T-SQL query, ~~297~~ 295 bytes

Using ¶ as separator and a table variable as input.

```
DECLARE @ table(a varchar(max),k int identity(1,1))
INSERT @ values('aaaa¶aaaa¶aaaa¶aaaa'),('bb¶bv¶bb'),('c');

WITH c as(SELECT k,row_number()over(partition
by k order by k)s,value v FROM @ CROSS APPLY
string_split(a,'¶')s),m(i,l,e)as(SELECT*FROM c
WHERE k=1UNION ALL
SELECT k,s,STUFF(e,1,len(v),v)FROM m
JOIN c ON-~i=k and s=l)SELECT
top 1with ties e FROM m
ORDER BY rank()over(partition by l order by-i)

```

**Try it online**
> 1 votes

# Answer
# Javascript (browser), ~~129~~ 124 bytes

My first attempt at code golfing. I read the links given in the rules (loopholes, standard rules...), so I hope I did anything wrong!

---

I kept the inputs as they are in the first post (flat array form).

```
_=o=>{o=o.map(i=>i.split`\n`),r=o.shift();for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b;return r.join`\n`}

```

Thanks to **Kevin Cruijssen** for saving 5 bytes.

---

**Tests:**

```
_=o=>{o=o.map(i=>i.split`\n`),r=o.shift();for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b;return r.join`\n`}

console.log(_(["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]));
console.log(_(["12345\n54321","00\n00\n00\n00","001\n011\n012"]));
console.log(_(["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]));
```
> 1 votes

# Answer
# Pyth, 18 bytes

```
L.tb0VyQsme #dy #N

```

Try it online! (note: the code itself evaluates only one block, the interpreter's test suite mode runs the program once for each line of input)

Based on TFeld's Python 2 solution.

Explanation:

```
L.tb0         # define a lambda function called y which does a transpose, padding with integer 0's
VyQ           # loop over transposed first input line (Q = eval(input()) ) (loop index = N)
   s          # concatenate array of strings (implicitly printed)
    m         # map over
         y #N # transpose of non-falsy values of N
     e        # for each item: last element of array
       #d     # relevant space at the start! filter with identity function, removes falsy values

```

for an explanation of why the algorithm itself works, see TFeld's answer.
> 1 votes

# Answer
# Charcoal, 4 bytes

```
ＦθＰι

```

Try it online (verbose) or try it online (pure).

**Explanation:**

Loop over the input-list of multi-line strings:

```
For(q)
Ｆθ

```

And print the multi-line string without moving the cursor:

```
Multiprint(i);
Ｐι

```
> 0 votes

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


# Question
Title: I see your BIDMAS and raise you a BADMIS
# I see your BIDMAS and raise you a BADMIS

## Challenge

Given a set of numbers with operators between them: "5 + 4 * 9 / 3 - 8", return all the possible results of the expression for every permutation of the order of basic operations: \[/, \*, +, -\].

## Rules

* Standard loopholes forbidden
* I/O
    + Input must be ordered with infix operations, but however that is easiest (string or array)
    + You are not required to support unary operators (e.g. "-3 * 8 / +2")
    + Integers can be replaced by floats for languages that implicitly parse type (e.g. 45 ⟶ 45.0)
    + Output must be all of the possible results of the expression, no specified format or order
* All of the inputs are valid (e.g. do not need to deal with "7 / 3 + \*"). This also means that you will never need to divide by zero.
* Operators are all left-associative so "20 / 4 / 2" = "(20 / 4) / 2"
* This is Code Golf so fewest number of bytes wins

## Test Cases (With explanation)

* "2 + 3 * 4" = \[14, 20\]
    + 2 + (3 * 4) ⟶ 2 + (12) ⟶ 14
    + (2 + 3) * 4 ⟶ (5) * 4 ⟶ 20
* "18 / 3 * 2 - 1" = \[11, 2, 6\]
    + ((18 / 3) * 2) - 1 ⟶ ((6) * 2) - 1 ⟶ (12) - 1 ⟶ 11
    + (18 / 3) * (2 - 1) ⟶ (6) * (1) ⟶ 6
    + (18 / (3 * 2)) - 1 ⟶ (18 / (6)) - 1 ⟶ (3) - 1 ⟶ 2
    + 18 / (3 * (2 - 1)) ⟶ 18 / (3 * (1)) ⟶ 6
    + 18 / ((3 * 2) - 1) ⟶ 18 / 5 ⟶ 3.6

## Test Cases (Without explanation)

* "45 / 8 + 19 / 45 * 3" = \[6.891666666666667, 18.141666666666666, 0.11111111111111113, 0.01234567901234568, 0.01234567901234568, 5.765740740740741\]
* "2 + 6 * 7 * 2 + 6 / 4" = \[112 196 23 87.5\]

# Answer
> 4 votes
# JavaScript (V8),  ~~118~~  112 bytes

Prints the results.

```
f=(s,x='',y=x,o='+-*/')=>[...o].map(v=>f(s.split(v).join(x+v+y),x+')',y+'(',o.replace(v,'')))|print(eval(y+s+x))

```

Try it online!

Or see the deduplicated results.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 285 bytes

```
x=>{int c=0,j,t=1,i;for(;c++<25;t=c){var r="*+-/".ToList();for(i=j=1;j++<4;t=t/j+1)(r[j-1],r[t%j])=(r[t%j],r[j-1]);float k(float z,int p=4){char d;int l;float m;return i<x.Count&&(l=r.IndexOf(d=x[i][0]))<p?k((m=k(x[(i+=2)-1],l))*0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,p):z;}Print(k(x[0]));}}

```

Try it online!

```
x=>{                                          //Lambda taking in a List<dynamic>
  int c=0,j,t=1,i;                            //A bunch of delcarations jammed together to save bytes
  for(;c++<25;t=c){                           //Loop 24 times (amount of permutations a set of length 4 can have)
    var r="/+*-".ToList();                    //Initialize r as list of operators
    for(i=j=1;j++<4;t=t/j+1)                    //Create the Tth permutation, saving result in r, also reset i to 1
      (r[j-1],r[t%j])=(r[t%j],r[j-1]);
    float k(float z,int p=4) {                //Define local function 'k', with z as current value accumalated and p as current precedence
      char d;int l;float m;                   //Some helper variables
      return i<x.Count                        //If this is not the last number
        &&(l=r.IndexOf(d=x[i][0]))<p?         //  And the current operator's precedence is higher than the current precedence
      k(                                      //  Recursive call with the accumalative value as
        (m=k(x[(i+=2)-1],l))                  //    Another recursive call with the next number following the current operator as seed value,
                                              //    And the next operator's precedence as the precedence value, and store that in variable 'm'
        *0+d<43?z*m:d<44?z+m:d<46?z-m:z/m,    //    And doing the appropriate operation to m and current value ('z')
        p)                                    //  Passing in the current precedence
    :z;                                       //Else just return the current number
    }
    Print(k(x[0]));                           //Print the result of calling k with the first number as starting value
  }
}

```

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

```
a=>(w=[],F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):w.push(a))("+-*/",a)&&w

```

Try it online!

This allows duplicated outputs.

# JavaScript (Node.js), ~~165~~ ~~161~~ ~~155~~ ~~153~~ ~~152~~ 137 bytes

```
a=>Object.keys((F=(b,a)=>b?[...b].map(q=>F(b.replace(q,""),a.replace(eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`),eval))):F[a]=1)("+-*/",a)&&F)

```

Try it online!

Takes a string with spaces between operators and numbers.

```
a=>                                             // Main function:
 Object.keys(                                   //  Return the keys of the -
  (
   F=(                                          //   Index container (helper function):
    b,                                          //    Operators
    a                                           //    The expression
   )=>
    b                                           //    If there are operators left:
    ?[...b].map(                                //     For each operator:
     q=>
      F(                                        //      Recur the helper function -
       b.replace(q,""),                         //       With the operator deleted
       a.replace(                               //       And all -
        eval(`/[\\d.-]+( \\${q} [\\d.-]+)+/g`), //        Expressions using the operator
        eval                                    //        Replaced with the evaluated result
       )
      )
    )
    :F[a]=1                                     //     Otherwise - set the result flag.
  )(
   "+-*/",                                      //    Starting with the four operators
   a                                            //    And the expression
  )
  &&F
 )

```

# Answer
> 2 votes
# Perl 6, ~~92 90~~ 88 bytes

```
{map {[o](@_)($_)},<* / + ->>>.&{$^a;&{S:g{[\-?<[\d.]>+]+%"$a "}=$/.EVAL}}.permutations}

```

Try it online!

Takes a string with a space after any operators and returns a set of numbers. This mostly works by substituting all instances of `n op n` with the eval'ed result for all permutations of the operators.

### Explanation:

```
{                                                                                }  # Anonymous code block
                    <* / + ->>>.&{                                    } # Map the operators to:
                                  $^a;&{                             }  # Functions that:
                                        S:g{                }      # Substitute all matches of:
                                            \-?<[\d.]>+]+        # Numbers
                                                         %$a     # Joined by the operator
                                                              =$/.EVAL   # With the match EVAL'd
 map {           },                                                    .permutations   # Map each of the permutations of these operators
      [o](@_)        # Join the functions
             ($_)    # And apply it to the input

```

# Answer
> 2 votes
# Python 3, 108 bytes

```
f=lambda e,s={*"+-*/"}:[str(eval(p.join(g)))for p in s for g in zip(*map(f,e.split(p),[s-{p}]*len(e)))]or[e]

```

Try it online!

The function takes a single string as input and returns a list of possible results.

# Ungolfed

```
def get_all_eval_results(expr, operators={*"+-*/"}):
    results = []
    for operator in operators:
        remaining_operators = operators - {operator}

        # Split expression with the current operator and recursively evaluate each subexpression with remaining operators
        sub_expr_results = (get_all_eval_results(sub_expr, remaining_operators) for sub_expr in expr.split(operator))

        for result_group in zip(*sub_expr_results):   # Iterate over each group of subexpression evaluation outcomes
            expr_to_eval = operator.join(result_group)  # Join subexpression outcomes with current operator
            results.append(str(eval(expr_to_eval)))   # Evaluate and append outcome to result list of expr
    return results or [expr]  # If results is empty (no operators), return [expr]

```

Try it online!

# Answer
> 1 votes
# Jelly, 30 bytes

```
œṡ⁹¹jṪḢƭ€jŒVɗßʋFL’$?
Ḋm2QŒ!çƒ€

```

Try it online!

A pair of links. The second one is the main link, and takes as its argument a Jelly list of floats/integers interspersed with the operators as characters. This is a flattened version of the way Jelly takes its input when run as a full program with command line arguments. The return value of the link is a list of list of single member lists, each of which is a possible value for the expression.

## Explanation

### Helper link

Takes a list of floats/integers alternating with operators (as characters) as its left argument and an operator as a character as its right argument; returns the input list after evaluating numbers separated by the relevant operator, working left to right.

```
œṡ⁹                  | Split once by the right argument (the operator currently being processed)
                   ? | If:
                  $  | - Following as a monad
                L    |   - Length
                 ’   |   - Decremented by 1
              ʋ      | Then, following as a dyad:
   ¹                 | - Identity function (used because of Jelly’s ordering of dyadic links at the start of a dyadic chain)
    j       ɗ        | - Join with the following as a dyad, using the original left and right arguments for this chain:
     ṪḢƭ€            |   - Tail of first item (popping from list) and head from second item (again popping from list); extracts the numbers that were either side of the operator, while removing them from the split list
         j           |   - Joined with the operator
          ŒV         |   - Evaluate as Python (rather than V because of Jelly’s handling of decimals with a leading zero)
            ß        | - Recursive call to this helper link (in case there are further of the same operator)
               F     | Else: Flatten

```

### Main link

Takes a list of floats/integers alternating with operators (as characters)

```
Ḋ         | Remove first item (which will be a number)
 m2       | Every 2nd item, starting with the first (i.e. the operators)
   Q      | Uniquify
    Œ!    | Permutations
      çƒ€ | For each permuted list of operators, reduce using the helper link and with the input list as the starting point

```

# Answer
> 1 votes
# Python 2, ~~182~~ 172 bytes

```
import re
def f(s,P=set('+-/*')):
 S=[eval(s)]
 for p in P:
	t=s
	while p+' 'in t:t=re.sub(r'[-\d.]+ \%s [-\d.]+'%p,lambda m:`eval(m.group())`,t,1)
	S+=f(t,P-{p})
 return S

```

Try it online!

Takes input with ints formatted as floats, as per "Integers can be replaced by floats for languages that implicitly parse type".

# Answer
> 1 votes
# Julia 1.2, 88 (82) bytes

```
f(t)=get(t,(),[f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2)...;])

```

```
julia> f([2, +, 3, *, 4])
2-element Array{Int64,1}:
 20
 14

julia> f([18, /, 3, *, 2, -, 1])
6-element Array{Float64,1}:
 11.0
  6.0
  2.0
  3.6
  6.0
  6.0

```

Takes a tape in the form of a vector of numbers and infix functions, evaluates each single function call and recursively passes each resulting tape back to itself until only a single number is left. Unfortunately, `get(t, (), ...)` doesn't work properly in Julia 1.0, so a newer version is needed.

Six bytes can be saved, if a bunch of nested arrays is acceptable as an output:

```
f(t)=get(t,(),f.([t[1:i-1];t[i+1](t[i],t[i+2]);t[i+3:end]] for i=1:2:length(t)-2))

```

Output:

```
julia> f([18, /, 3, *, 2, -, 1])
3-element Array{Array{Array{Float64,1},1},1}:
 [[11.0], [6.0]]
 [[2.0], [3.6]]
 [[6.0], [6.0]]

```

# Answer
> 0 votes
# Perl 5 (`-alp`), 89 bytes

```
my$x;map{$x.=$`.(eval$&.$1).$2.$"while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=$x;/[-+*\/]/&&redo

```

TIO

or unique values, 99 bytes

```
my%H;map{$H{$`.(eval$&.$1).$2}++while/\d+[-+*\/](?=(\d+)(.*))/g}@F;$_=join$",keys%H;/[-+*\/]/&&redo

```

---
Tags: code-golf, permutations
---


title: Wrong keyboard position

text:
# Question
Title: Wrong keyboard position
You are in fact writing an interpreter for the language "Wrong keyboard position". You can pretend that you are not doing this and just follow the instructions below.

---

I typr re;atively accuratrly, but so,etimes I made a whole nlock of text illegible by shifting a key right. So I need a program that corrects my text back to its original meaning.

## Rules

* You have to *left* shift on a standard English QWERTY keyboard.
* Whitespace do not count for the procedure before left-shifting and are kept as-is in a standard left-shifting procedure. If the key is the leftmost letter/symbol on a keyboard(i.e. `The ~key, Q key, A key, Z key.`), the key is kept as-is. If you reach a control character while left-shifting (`Caps lock and Shift`), their effects will not be triggered and the character before left-shifting is kept.
* This is a contest; the shortest answer wins.
* Both the input and the output shall be given via our default methods.

## Representation of a subset of the QWERTY keyboard that you will need

The two lines connected are possible values of the key: shifted/unshifted.

```
~!@#$%^&*()_+
`1234567890-=

QWERTYUIOP{}|
qwertyuiop[]\

ASDFGHJKL:"
asdfghjkl;'

ZXCVBNM<>?
zxcvbnm,./

(Space)
(Space)

```

## Input

The input will always be a non-empty string conforming the rules above.

## Output

The output will be the input string corrected to the originally intended meaning.

## Examples:

```
Yjod ,sfr yjr, imjsppu/ -> This made them unhaooy.
vpfr hp;g -> code golf

```

# Answer
> 2 votes
# 05AB1E, 59 bytes

*-1 byte thanks to Kevin Cruijssen*

```
žVDu«1ú`žhÀ“~!@#$%^&*()_+ `ÿ-=ÿ<>?ÿ:"ÿ{}|ÿ,./ÿ;'ÿ[]\“#vy¦y‡

```

Try it online!

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


title: Solve the Halting Problem for Befinge

text:
# Question
Title: Solve the Halting Problem for Befinge
Let's define a simple 2D language, which we'll give the incredibly original name *befinge*. Befinge has 5 instructions:

* `<>^v`, as in most 2D esolangs, redirect the instruction pointer in their respective directions.
* `.` is a no-op.

The instruction pointer starts out at the top-left corner going right. If the instruction pointer gets to an edge, the program halts. Every Befinge program will obviously either halt or go into an infinite loop which does nothing. Here are two examples:

Halting:

```
>.v
..<

```

Non-Halting:

```
>....v
..v..<
..>v..
^..<..

```

The halting problem is not solvable for a Turing-complete language, but it is for this one. Your task is to write a program (or function) that takes as input a string representing the *befinge* program and returns a truthy or falsey value depending on whether it halts or not.

* You can assume that the input will consist only of these characters and will be padded with spaces to form a rectangle.
* You can use any set of five characters for the instructions (e.g. `adws` ).

## Test Cases

### Halting:

```
.

```

```
v>
>^

```

```
....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.

```

```
v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<

```

### Non-Halting:

```
>..v
^..<

```

```
>v<
v<.
>v.
v<.
>.^

```

```
>.>.>.v
.><.<.<

```

This is , so the shortest program (in bytes) wins.

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

*EDIT:* changed output values to *true* and *false*, instead of *Y* and *N*, to shave off 10 bytes more

**Golfed**

```
F=(I,M=[...I],c=0,i)=>(i={j:v=I.search`\n`+1,k:-v,h:-1,l:1,q:i,0:0}[M[c]])?F(I,M,c+i+(M[c]=0),i):i!=0

```

**Test**

```
F=(I,M=[...I],c=0,i)=>(i={j:v=I.search`\n`+1,k:-v,h:-1,l:1,q:i,0:0}[M[c]])?F(I,M,c+i+(M[c]=0),i):i!=0

//Alphabet Map
tr={
'<':'h',
'>':'l',
'^':'k',
'v':'j',
'.':'q',
'\n':'\n'
};

//Test
T=(I,A)=>{
console.log({"Y":"#Halting","N":"#Non-Halting"}[A]);
console.log("I=\n",I,"\nF(I)=",O=F([...I].map(s=>tr[s]).join('')));
console.log('NY'[O*1] == A ? "OK !" : "NOT OK !");
}

//Halting
T(
`>.v
..<`
,'Y');

//Non-Halting
T(
`>....v
..v..<
..>v..
^..<..`
,'N');

//Halting
T(
`.`
,'Y')

//Halting
T(
`v>
>^`
,'Y');

//Halting
T(
`....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.`
,'Y');

//Halting
T(
`v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<`
,'Y');

//Non-Halting
T(
`>..v
^..<`
,'N');

//Non-Halting
T(
`>v<
v<.
>v.
v<.
>.^`
,'N');

//Non-Halting
T(
`>.>.>.v
.><.<.<`
,'N');

```

**Sample Output**

```
#Halting
I=
>.v
..<
F(I)= true
OK !

#Non-Halting
I=
>....v
..v..<
..>v..
^..<..
F(I)= false
OK !

#Halting
I=
 .
F(I)= true
OK !

#Halting
I=
v>
>^
F(I)= true
OK !

#Halting
I=
....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.
F(I)= true
OK !

#Halting
I=
v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<
F(I)= true
OK !

#Non-Halting
I=
>..v
^..<
F(I)= false
OK !

#Non-Halting
I=
>v<
v<.
>v.
v<.
>.^
F(I)= false
OK !

#Non-Halting
I=
>.>.>.v
.><.<.<
F(I)= false
OK !

```
> 4 votes

# Answer
# Befunge-98 (PyFunge), ~~217~~ ~~209~~ 200 bytes

```
#v10dpf1dp12dp3dpk
 >#v~:a-#v_$10dp1dg1+1dp >
v  >10dp;>0dg1dgp0dg1+0dp^;f1dp
>0dg1dgg:'^-#v_n1-v
^<v01_v#!->':<
  <   >:'<-#v_01-0>   v
v^pd1+gd3gd1[:'v-#v_01>3dp2dpndg1dgp
>0dg2dg+0dp ^ @.!;>:'.-#;_

```

Try it online!

A befinge halting problem needs a befunge solution. Returns 0 for truthy and 1 for falsey. Puts the input on the grid starting from 1,15 and then moves on top, replacing the arrows with zeros. As soon as we hit a zero, we know it loops. Anything besides \>\<^v. and zero is considerd to halt the program, which includes the border of spaces we get around the program by placing it on the grid slightly offset.

One easy way to shave off a few bites would be to use numbers instead of \>\<^v. but I don't feel like that's worth it.
> 4 votes

# Answer
# Python 2, ~~116~~ 105 bytes

```
x=1
X=Y=y=0
H=[]
G=input()
while(X,Y,x,y)not in H:H+=[(X,Y,x,y)];C=ord(G[Y][X]);x=C%3-1;y=C%5-1;X+=x;Y+=y

```

Try it online!

The challenge is old, but I figured since this is the shortest Python, I will post it. Input is a list of strings, but the characters used are unusual.

```
> G
< B
v C
^ F
. L

```

For example, the third halting example turns into `['LLLLCLLLL', 'LLLLGLLLC', 'LFLLBLLLL', 'LLLLLLLCB', 'LLLLLLLCL', 'LLLLFLLBL']`. Output is via exit code, 0 (success) for non-halting, and 1 (error) for halting. Any tips or tricks appreciated.
> 3 votes

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

```
f=(a,v=1,x=0,[t,...u]=a,n=1+a.search`
`,c=a[x])=>t?f(a,v=+c?c-2||v:c+n,x-v,u):!c

```

Try it online!

# JavaScript (Node.js), 86 bytes

```
f=(a,v=1,x=0,[t,...u]=a,n=1+a.search`
`,c=a[x])=>t?c>' '<=f(a,v=+c?c-2||v:c+n,x-v,u):0

```

Try it online!
> 2 votes

# Answer
# Turtlèd, 146 bytes

```
!u[*.[ r+.]l[ l]dr_+]#*#[ u]d[ (.r)(>.r{.r}@>)(v.d{.d}@v)(<.l{.l}@<)(^.u{.u}@^)(*@0' )],@1(0@0)(v' d)(<' r)(>' l)(^' d)[ u]d[ l]r[ [ r]l[ ' l]dr],

```

This program takes I/O differently: please terminate each line with a space, including the last one. Turtlèd doesn't like newlines, as it uses a grid for it's second dimension of characters.

### Try it online!

0 for loops forever, 1 for halts.

## General explanation:

It writes the input on the grid, then it actually follows the path the arrows make around the grid, replacing each arrow with a * as it goes, also saving the direction in the char var. If it encounters an \*, an arrow it hit before, the program would not halt, so it sets the char var to `0`, exit the loop. Otherwise, it will hit the end of the grid and exit the loop. It will write the char var. If it hit the end of grid, it uses the direction stored in the char var to get back to the grid, and sets the char var to `1`, for halts. If the char var was actually 0, not a direction, it does not need to get back, as it is still there, and it sets it back to `0`. It clears the grid off, then writes the char var, `1` for halts, else `0`.
> 1 votes

# Answer
## JavaScript (ES6), ~~158~~ 127 bytes

```
f=(a,x=0,y=0,d=1,e=0,c=a[y]&&a[y][x])=>c<'~'?(c>'.'&&(a[y][x]='~',d=(c=='>')-(c=='<'),e=(c=='v')-(c=='^')),f(a,x+d,y+e,d,e)):!c

```

Takes input as a two-dimensional character array and returns `true` for halting and `false` for an infinite loop. Works by setting visited direction characters to `~`s as it recursively traverses them. Edit: Saved 31 bytes by updating my direction vector before recursing.

Abusing the instruction characters (`1=^ 4=< 5=. 6=> 9=v`) takes me down to 101 bytes:

```
f=(a,x=0,y=0,d=1,e=0,c=a[y]&&a[y][x])=>+c?(c-5&&(a[y][x]='0',d=~-c%4,e=~-(c>>2)),f(a,x+d,y+e,d,e)):!c

```
> 1 votes

# Answer
# SmileBASIC, ~~158~~ 145 bytes

If the same arrow is encountered more than once, the program will never halt. When the instruction pointer passes an arrow, it's replaced with a different symbol, which will cause the function to return 0 if it's reached again. If the IP goes out of bounds, it returns 1.

```
DEF H P@L
C=VAL(P[Y][X])IF C>8THEN?0RETURN
IF C THEN D=C-1P[Y][X]="9
X=X+!D-(D==1)Y=Y+(D==2)-(D>2)IF X+1&&Y+1&&Y-LEN(P)&&X-LEN(P[0])GOTO@L
?1
END

```

Takes input as an array of strings. `<any non-digit chracter>`,`1`,`2`,`3`,`4` = `.`,`>`,`<`,`v`,`^`
> 1 votes

# Answer
## Python 2, 182 bytes

```
m,v,d,x,y=input(),[],'>',0,0
try:
 while 1:
  if[x,y]in v:print 0;break
  c=m[y][x]
  if c!='.':d=c;v+=[[x,y]]
  if d in'><':x+=[-1,1][d=='>']
  else:y+=[-1,1][d=='v']
except:print 1

```

Takes a string array as input. I have to golf this more but for now it's time to stress over the election.

Ungolfed:

```
input = input()

visited = [  ]

dir = ">"
x=0
y=0

try:
    while True:
        if[x,y]in visited:print False;break
        char=input[y][x]
        if char!=".":
            dir=char
            visited+=[[x,y]]

        if dir==">":
            x+=1
        if dir=="<":
            x-=1
        if dir=="v":
            y+=1
        if dir=="^":
            x-=1
except:
    print True

```
> 0 votes

# Answer
## Clojure, 143 bytes

```
#((fn[p v i s](if-let[v({\> 1\< -1\^(- s)\. v\v s}(get % p))](if(neg? i)1(recur(+ p v)v(dec i)s))))0 1 1e9(+(count(take-while(set"<>v^.")%))1))

```

A function with 4 state arguments: position `p`, velocity `v`, step index `i` and size of one line `s`. Returns `1` if we didn't go out of bounds in 10^9 steps and `nil` otherwise. Actually how many steps do we need to check to be sure, `(count %)`? I think it is more than that as same NOP can be traversed horizontally and vertically.

Can be called like this (takes normal strings as arguments, `get` returns `nil` when out of bounds):

```
(def f #( ... ))
(f ">....v\n..v..<\n..>v..\n^..<..")
(f "v>\n>^")
(f "....v....\n....>...v\n.^..<....\n.......v<\n.......v.\n....^..<.")

```

State transitions (+1, -1, +s, -s) are encoded in the dictionary `{\> 1\< -1\^(- s)\. v\v s}`.
> 0 votes

# Answer
# Python 2/3, ~~201~~ 192 bytes

```
def f(x):
 X=Y=b=0;a=1;D={}
 while len(x)>Y>-1<X<len(x[Y]):
  try:
   a,b={'>':(1,0),'^':(0,-1),'<':(-1,0),'v':(0,1)}[x[Y][X]]
   if(X,Y)in D:return 0
  except:0
  D[X,Y]=0;X+=a;Y+=b
 return 1

```

Try it online!

Gives correct answer for `["<>"]`
> 0 votes

# Answer
## Java, 477

I know that this is not winning, n=and can probably be golfed more, but it implments a similar method as to what the other answers use, but this one uses hashmap to perform lookups. The input is using the symbols \>\<^v and anything other than that for the no op. Input comes through args.

**GOLFED**

```
import java.util.*;interface B{static void main(String[]a){HashMap<String,Byte>h=new HashMap<>();int x,y=0;for(String s:a){x=0;for(char c:s.toCharArray()){if("><^v".indexOf(c)>-1)h.put(x+","+y,(byte)c);x++;}y++;}x=0;y=0;int d=0;int D=0;while(x>-1&&x<a[0].length()&&y<a.length&&y>-1){Byte v=h.get(x+","+y);if(v!=null){if(v==0){System.out.print(0);return;}d=(v<85)?"<>".indexOf(v)*2-1:0;D=(v>84)?"^v".indexOf(v)*2-1:0;}h.replace(x+","+y,(byte)0);x+=d;y+=D;}System.out.print(1);}}

```

**UNGOLFED**

import java.util.\*;

```
interface B{
    static void main(String a[]) {
        HashMap<String, Byte> h = new HashMap<>();
        int x, y = 0;
        for(String s : a) {
            x = 0;
            for(char c : s.toCharArray()) {
                if ("><^v".indexOf(c) > -1) h.put(x + "," + y, (byte) c);
                x++;
            }
            y++;
        }
        x = 0;
        y = 0;
        int d = 0;
        int D = 0;
        while(x > -1 && x < a[0].length() && y < a.length && y > -1) {
            Byte v = h.get(x + "," + y);
            if(v != null) {
                if(v == 0) {System.out.print(0); return;}
                d = (v < 85) ? "<>".indexOf(v)*2-1 : 0;
                D = (v > 84) ? "^v".indexOf(v)*2-1 : 0;
            }
            h.replace(x + "," + y, (byte) 0);
            x += d;
            y += D;
        }
        System.out.print(1);
    }
}

```

Explanation coming soon!
> 0 votes

---
Tags: code-golf, interpreter, halting-problem
---


title: All the k-mers/n-grams

text:
# Question
Title: All the k-mers/n-grams
### Intro

We have had histograms and counting, but not listing all of them.

Every year, Dyalog Ltd. holds a student competition. The challenge there is to write *good* APL code. This is a language agnostic edition of this year's sixth problem.

I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.

### Problem

The term k-mer typically refers to all the possible substrings of length *k* that are contained in a string. In computational genomics, k-mers refer to all the possible subsequences (of length *k*) from a read obtained through DNA Sequencing. Write a function/program that takes a string and *k* (the substring length) and returns/outputs a vector of the k-mers of the original string.

### Examples

`[4,"ATCGAAGGTCGT"]``["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]`

*k* \> string length? Return nothing/any empty result:
`[4,"AC"]``[]` or `""` or `[""]`

# Answer
> 15 votes
# Jelly, 1 byte

Jelly has a single byte dyadic atom for this very operation

**Try it online!** (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.)

# Answer
> 8 votes
# Octave, 28 bytes

```
@(N,s)s((1:N)+(0:nnz(s)-N)')

```

Try it online!

For k \> string length works in Octave 4.2.1-windows but in tio (Octave 4.0.3) doesn't work.

Creates numeric indexes of consecutive elements and index the string by it.

```
s= "ATCGAAGGTCGT"
N = 4
idx = (1:N)+(0:nnz(s)-N)'
 =
    1    2    3    4
    2    3    4    5
    3    4    5    6
    4    5    6    7
    5    6    7    8
    6    7    8    9
    7    8    9   10
    8    9   10   11
    9   10   11   12

s(idx) =

ATCG
TCGA
CGAA
GAAG
AAGG
AGGT
GGTC
GTCG
TCGT

```

# Answer
> 7 votes
# C (GCC on POSIX), ~~67~~ ~~66~~ 63 bytes

*-3 bytes thanks to @LeakyNun!*

```
f(i,s,j)char*s;{for(;j+i<=strlen(s);puts(""))write(1,s+j++,i);}

```

Try it online!

# Answer
> 7 votes
# 05AB1E, 2 bytes

Code:

```
Œù

```

Explanation:

```
Œ      # Get all substrings of the input
 ù     # Only keep the substrings of length the second input

```

Uses the **05AB1E** encoding.

Try it online!

# Answer
> 6 votes
# Python 3,  ~~47 45~~ 42 bytes

-3 bytes thanks to ovs (use Python 3's unpacking to reuse `a[n-1:]` at the tail.)

```
f=lambda a,n:a[n-1:]and[a[:n],*f(a[1:],n)]

```

A recursive function taking the string, `a`, and the slice length, `n`, and returning a list of the slices or an empty string.

`a[n-1:]` takes a slice of the current string from the n-1th (0-indexed) element onward to test whether there are enough elements remaining (an empty string is falsey in Python) - this is shorter than the equivalent `len(a)>=n`.

* If there are enough elements a list is constructed, `[...]`, with the first `n` elements of the string, `a[:n]`, and the unpacked result of calling the function again, `*f(...)`, with a dequeued version of the current input (without the first element), `a[1:]`.
* If there are not enough elements the tail of the recursion is reached when `a[n-1:]` is returned (in this case an empty string).

**Try it online!**

---

**45** for Python 2 or 3 with:

```
f=lambda a,n:a[n-1:]and[a[:n]]+f(a[1:],n)or[]

```

# Answer
> 5 votes
# Brachylog, 3 bytes

```
s₎ᶠ

```

Try it online!

## Specs:

* Input: `["ATCGAAGGTCGT",4]`
* Argument: `Z`
* Output: `Z = ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]`

## How it works

```
s₎ᶠ
s    Output is a substring of first element of input,
 ₎   with length specified by second element of input.
  ᶠ  Find all solutions.

```

# Answer
> 4 votes
# , 2 bytes

```
,\

```

It is not a complete program, but a function with an operator.

Call it as such:

```
echo 4 ,\ 'ATCGAAGGTCGT'

```

Try it online!

## How it works

The operator (called "conjunction") `\` (named "infix") is used as such:

> `(x u\ y)` applies verb `u` to successive parts of list `y` (called infixes).

The function (called "verb") `u` in this case is the function `,` which is a simple "append" function:

> Creates an array containing the items of `x` followed by the items of `y`.

# Answer
> 3 votes
# Mathematica, 21 bytes

```
##~StringPartition~1&

```

Anonymous function. Takes a string and a number (in that order) as input and returns a list of strings as output.

# Answer
> 3 votes
# R, ~~65~~ 61 bytes

*-2 bytes thanks to MickyT*

*-2 bytes by changing the indexing*

returns an anonymous function.

```
function(s,n,x=nchar(s))`if`(n>x,'',substring(s,x:n-n+1,n:x))

```

`substring` cycles through the indices (as opposed to `substr` which does not), and if the starting index is less than 1, it defaults to `1` instead, so it checks and returns the empty string.

`x:n-n+1` is equivalent to `1:(x-n+1)` since `:` takes precedence over sums/differences

Try it online!

# Answer
> 2 votes
# Pyth, 2 bytes

```
.:

```

It is not a complete program, but a built-in function.

Call it as such:

```
.:"ATCGAAGGTCGT"4

```

Try it online!

Full program:

```
.:.*

```

Try it online!

(The `.*` is splat.)

# Answer
> 2 votes
# Jellyfish, 7 bytes

```
p
_I
\i

```

Try it online!

## How it works

In linear: `p(\(I,i))`, where `p` is print and `\` gets the required substrings.

`I` is the raw first input while `i` is the evaluated second input.

In Jellyfish, every function and operator gets two arguments, one from the right, and one from the bottom. Here, the function `p` gets the argument from the output of `_`, which is required if we are to use the operator `\` to get substrings.

# Answer
> 2 votes
# Java (OpenJDK 8), 92 bytes

```
void f(String s,int n){for(int i=n;i<=s.length();)System.out.println(s.substring(i-n,i++));}

```

Try it online!

# Answer
> 2 votes
# Retina, ~~41~~ 38 bytes

```
.*$
$*
!&`(.)+(?=.*¶(?<-1>.)+(?(1)¶)$)

```

Try it online!

Takes the string and count on separate lines. The first two lines are used to convert the count from decimal to unary, so if unary input is acceptable then the byte count would be reduced to ~~34~~ 31. Edit: Saved 3 bytes thanks to @FryAmTheEggman. Or, if you prefer, a 48-byte version that handles newlines in the string, although that does produce confusing output:

```
.*$
$*
!&`(\S|\s)+(?=[\S\s]*¶(?<-1>.)+(?(1)$.)$)

```

# Answer
> 2 votes
# Octave with Image Package, 29 bytes

```
@(s,n)[im2col(+s, [1 n])' '']

```

Try it online!

### Explanation

The function `im2col(m,b)` takes a matrix `m`, extracts blocks of size `b` from it, and arranges them as columns. By default blocks are sliding (as opposed to distinct). Here the matrix `m` is a row vector of the ASCII codes of the input string `s` (this is done as `+s`, which is shorter than the standard `double(s)`), and the size `b` is `[1 n]` to obtain horizontally sliding blocks of `n` elements.

The result is transposed (using complex-conjugate transpose `'`, which is shorter than transpose `.'`) to turn the columns into rows, and then it is converted back to char (`[... '']`, which is shorter than the standard `char(...)`).

# Answer
> 2 votes
# Python 2, 54 bytes

```
lambda x,n:map(''.join,zip(*[x[b:]for b in range(n)]))

```

Try it online!

# Answer
> 2 votes
## Clojure, 19 bytes

Well this is handy:

```
#(partition % 1 %2)

```

Examples:

```
(def f #(partition % 1 %2))
(println [(f 4 "ATCGAAGGTCGT")
          (f 4 "abc")])

[((A T C G) (T C G A) (C G A A) (G A A G) (A A G G) (A G G T) (G G T C) (G T C G) (T C G T))
 ()]

```

# Answer
> 2 votes
# CJam, 4 bytes

```
{ew}

```

Anonymous block that expects the arguments on the stack and leaves the result on the stack after.

Try it online!

`ew` is a built-in that does exactly what is required.

# Answer
> 2 votes
# oK, 2 bytes

```
':

```

oK has a sliding window operator!

# Answer
> 1 votes
# Python 3, 49 bytes

```
f=lambda a,n:[a[i:i+n]for i in range(len(a)-n+1)]

```

Try it online!

A non-recursive solution, albeit not shorter.

Compatible with Python 2.

# Answer
> 1 votes
## JavaScript (Firefox 30-57), 51 bytes

```
(s,n,t='')=>[for(c of s)if((t+=c)[n-1])t.slice(-n)]

```

64 bytes in ES6:

```
(s,n,t=s.slice(0,--n))=>[...s.slice(n)].map(c=>(t+=c).slice(~n))

```

# Answer
> 1 votes
# PHP, 75 Bytes

Online Version

```
for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[]=substr($s,$i++,$n);print_r($r);

```

80 Bytes without double values

```
for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[$p=substr($s,$i++,$n)]=$p;print_r($r);

```

# Answer
> 1 votes
## Haskell, 39 bytes

```
n#s|length s<n=[]|1<2=take n s:n#tail s

```

Usage example: `4 # "ABCDEF"` -\> `["ABCD","BCDE","CDEF"]`. Try it online!

A simple recursion that keeps the first `n` chars of the input string an continues with the tail of the string as long as its length is not less than `n`.

# Answer
> 1 votes
**Microsoft Sql Server, 199 bytes**

```
create function dbo.f(@s nvarchar(max),@ int)returns table as return
with v as(select 2 p,left(@s,@)g where len(@s)>=@ union all
select p+1,substring(@s,p,@)from v where len(@s)>p-2+@)select g from v

```

Check it.

# Answer
> 1 votes
**PowerShell, 70 bytes**

```
$b={$c,$s=$args;[regex]::matches($s,"(?=(.{$c}))")|%{''+$_.groups[1]}}

```

Try it online!

# Answer
> 1 votes
# Stacked, 7 bytes

```
infixes

```

Try it online!

Pretty standard. Without this builtin, it becomes 20 bytes:

```
{%x#'y-#+:>y#-#>x\#}

```

Which is:

```
{%x#'y-#+:>y#-#>x\#}
{%                 }   dyad; first arg: x, second arg: y
  x#'                  length of x (the array)
     y-                minus y (the skew)
       #+              plus 1
         :>            range [x, y]
           y#-         y minus 1
              #>       range from [[x, y], [x, y] + y]
                x\#    get indices from x

```

# Answer
> 1 votes
# MATL, 3 bytes

```
YC!

```

Try it online!

### Explanation

```
YC   % Sliding blocks of input string with input size, arranged as columns
!    % Transpose

```

# Answer
> 1 votes
# C# 89 bytes

```
void a(string s,int n){for(int i=n;i<=s.Length;)Console.WriteLine(s.Substring(i++-n,n));}

```

Try it online!

Best method I could find in C# is basically the same as Java

# Answer
> 1 votes
# Ruby, ~~48~~ 46 bytes

```
->(s,k){0.upto(s.size-k).map{|i|s[i..i+k-1]}}

```

No particular tricks, just a stabby-lambda defining a function that pulls the required substring from each valid starting point.

Saved two bytes, since there doesn't seem to be a need to store the lambda.

# Answer
> 1 votes
# , 16 bytes

```
òÀ|ly0Ïp
"_xòkVp

```

Not terribly well golfed I'm afraid, struggling with "delete the string if k \> len(str)". Input is in the file, k is an argument. Golfing before explanation

Try it online!

# Answer
> 1 votes
# Dyalog APL, ~~13~~ 11 bytes

```
⊢,/⍨⊣⌊1+∘⍴⊢

```

It does exactly as intended *now*. Stupid errors. Thanks to Adám for giving me the hint that there is an 11 byte solution, even though this isn't the one he was looking for.

# Answer
> 1 votes
# Standard ML (mosml), ~~109~~ ~~65~~ 61 bytes

```
fun f(n,x)=if n>length(x)then[]else List.take(x,n)::f(n,tl x)

```

Takes a number and a character list (quite a common alternative to strings in the SML world). (Really works on all lists of course.)

Usage:

```
- f(3,explode("ABCDEFGH"));
> val it =
    [[#"A", #"B", #"C"], [#"B", #"C", #"D"], [#"C", #"D", #"E"],
     [#"D", #"E", #"F"], [#"E", #"F", #"G"], [#"F", #"G", #"H"]] :
  char list list
- f(7, explode("ABCD"));
> val it = [] : char list list

```

Changelog:

* Right, there is a standard library.. (-44 bytes)
* Change comparison and nil to \[\] as suggested (-4 bytes)

# Answer
> 0 votes
# Standard ML, 68 bytes

```
fun f$n=List.tabulate(size$ -n+1,fn m=>substring($,m,n))handle _=>[]

```

Try it online! Example usage: `f "abcdef" 3` returns `["abc", "bcd", "cde", "def"]`.

### Explanation:

For two bytes more we can replace the identifier `$` by `s` to get better readable code:

```
fun f s n=List.tabulate(size s-n+1,fn m=>substring(s,m,n))handle _=>[]

```

The function takes a string `s` and an integer `n` as arguments. `List.tabulate(m,g)` takes an integer `m` and some function `g` and builds the list `[g 0, g 1, ..., g(m-1)]`. In this case, we give for `m` the size of the string `s` minus the n-gram length `n` (+1 to avoid off-by-one-errors). For each such `m` we return the substring of `s` at position `m` with length `n`.

In case of `n > size s`, an exception is thrown. `handle _=>[]` catches the exception and returns the empty list.

# Answer
> 0 votes
# brainfuck, 52 bytes

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

```

Try it online!

Takes K as the value on the starting cell and the string as input.

# Answer
> 0 votes
# q/kdb+, 19 bytes

**Solution:**

```
{(0-x)_x#'next\[y]}

```

**Example:**

```
q){(0-x)_x#'next\[y]}[4;"ABCDEFGHIJ"]
"ABCD"
"BCDE"
"CDEF"
"DEFG"
"EFGH"
"FGHI"
"GHIJ"
q){(0-x)_x#'next\[y]}[4;"AC"]
q)

```

**Explanation:**

Use `next` and scan over the input string, then take the first 'x' (sliding window size), then drop off the extras from the end:

```
{(0-x)_x#'next\[y]} / the solution
{                 } / anonymous lambda with implicit args x and y
          next\[y]  / take 'next' element of y until exhausted
       x#'          / x take-each (take first x chars of each)
 (0-x)              / negate x
      _             / drop (negative drops from the end rather than front)

```

# Answer
> 0 votes
# Japt, 2 bytes

Straightforward, built-in solution.

```
ãV

```

Try it

---
Tags: code-golf, string, subsequence, generation
---


# Question
Title: Given an input, move it along the keyboard by N characters
# The Challenge:

Given any input that can be typed on a keyboard, move the text along by N chars.

Here is the QWERTY keyboard to be used. You can ignore the modifier keys (Shift, Caps, Enter, Delete and Tab). Once you reach one side (for example `|`) loop back round, so `|` goes to `Q` if `N = 1`.

Spaces do not have to be moved along (they go back round to space as you skip modifiers). If shift was used to type the character (e.g. `!` and `@`) the changed character should also be typed using shift (i.e. `!` goes to `@` not `2` if `N = 1`).

UK keyboards are different to this, but please use this so that we can compare.

# Input:

Any sentence that can be typed on the above keyboard followed by a positive integer. There is no maximum to the size of this integer.

# Output:

The same sentence, shifted along by N.

# Examples:

```
My name is Tim 3
?o .f/y [g I[/

```

```
Hello World 7
Spgge Oe[g;

```

```
I Wi5h I h4d b3773r C@d3ing ski{{s 3
{ T[8l { l7h ,6006u N%h6[.k g'[QQg

```

This is code golf, so shortest code wins.

# Answer
> 2 votes
## C, 217 bytes

```
char*t=" @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";l,d,k;f(char*s){for(l=strlen(s);s[--l]-32;);d=atoi(s+l);for(s[l]=0;d--;)for(k=l;k--;s[k]=t[s[k]-32]);puts(s);}

```

Readable version with whitespace, includes, etc:

```
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char* t = " @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";
int l, d, k;

void f(char* s) {
    l = strlen(s);
    for( ; s[--l] - 32; );
    d = atoi(s + l);
    s[l] = 0;
    for ( ; d--; ) {
        for (k = l; k--; s[k] = t[s[k] - 32]);
    }
    puts(s);
}

```

The code pretty much speaks for itself. Just a lookup table that maps from each character to the next character, which is applied the given number of times. Much of the code is actually for parsing the number out of the input.

# Answer
> 2 votes
# 05AB1E, 61 bytes

*-1 byte thanks to Kevin Cruijssen*

```
žVDu«1ú`žhÀ“~!@#$%^&*()_+ `ÿ-=ÿ<>?ÿ:"ÿ{}|ÿ,./ÿ;'ÿ[]\“#vyy¹._‡

```

Try it online!

# Answer
> 1 votes
# Pyth, 126 bytes

```
XjdPczdsJc"~!@#$%^&*()_+ `1234567890-= qwertyuiop[]\ QWERTYUIOP{}| asdfghjkl;, ASDFGHJKL:\" zxcvbnm,./ ZXCVBNM<>?")sm.<dvecz)J

```

Try it online: Demonstration or Test Suite

### Explanation:

```
    czd                       split input by spaces
   P                          remove the last element
 jd                           join by spaces (=#1)

          "..."               string with the chars of each row
         c     )              split by spaces
        J                     assign to J
       sJ                     sum of J (=#2)

                       cz)    split input by spaces
                      e       take the last element
                     v        and evaluate it
                 m        J   map each row d of J to:
                  .<d           rotate the row d by value
                s             sum (=#3)

X                             Take #1, and replace the chars in #2 by the chars in #3

```

# Answer
> 1 votes
## Python 3, 311 bytes

```
*i,s=input().split()
r=["`1234567890-=","qwertyuiop[]\\","asdfghjkl;'","zxcvbnm,./","~!@#$%^&*()_+","QWERTYUIOP{}|",'ASDFGHJKL:"',"ZXCVBNM<>?"]
print("".join([[x[int(s):]+x[:int(s)]for x in r][r.index([x for x in r if c in x][0])][([x for x in r if c in x][0]).index(c)]if c!=" "else " " for c in " ".join(i)]))

```

# Answer
> 0 votes
# Python 3, ~~271~~ 255 bytes

Baseline, almost ungolfed, used to create the shifted words in the question.

```
x=input().split()
n=int(x[-1])
x=' '.join(x[:-1])
l=['`1234567890-=','qwertyuiop[]\\',"asdfghjkl;'",'zxcvbnm,./', '~!@#$%^&*()_+','QWERTYUIOP{}|','ASDFGHJKL:"','ZXCVBNM<>?',' ']
y=''
for i in x:
 for q in l:
  if i in q:y+=q[(q.index(i)+n)%len(q)]
print(y)

```

Explanation:

```
x=input().split()    # Get input
n=int(x[-1])         # Get N from input
x=' '.join(x[:-1])   # Get the words from input
                     # Create list of letters

l=['`1234567890-=', 'qwertyuiop[]\\',
   "asdfghjkl;'",   'zxcvbnm,./',
   '~!@#$%^&*()_+', 'QWERTYUIOP{}|',
   'ASDFGHJKL:"',   'ZXCVBNM<>?',
   ' ']

y=''                 # Blank string
for i in x:          # Loop through letters in input
    for q in l:      # Loop through items in list
        if i in q:   # Is letter of input in item of list?
            y+=q[                          # Append letter to y
                 (q.index(i)+n)            # locate the letter in item, and add N
                               %len(q)]    # % is modulus, loop to beginning if big
print(y)             # Print out the offset word.

```

# Answer
> 0 votes
# JavaScript (ES6), 200 ~~216~~

Using template strings, the newlines are significant and counted.

Note about `replace`: the two snippets `string.split('x').map(w=>...)` and `string.replace(/[^x]+/g,w=>...)` are equally valid ways to execute a function for each part in a string, using a separator. Using a newline as a separator is handy as the replace regexp becomes `/.+/g`, because the dot match any non-newline. And using templated strings the newlines have no extra cost.

```
f=(t,d)=>[for(c of t)`~!@#$%^&*()_+
1234567890-=
QWERTYUIOP{}|
qwertyuiop[]\\
ASDFGHJKL:"
asdfghjkl;'
ZXCVBNM<>?
zxcvbnm,./`.replace(/.+/g,r=>(p=r.indexOf(c))<0?0:q=r[(p+d)%r.length],q=c)&&q].join('')

// less golfed
x=(t,d)=>
  [for(c of t)
    '~!@#$%^&*()_+ 1234567890-= QWERTYUIOP{}| qwertyuiop[]\\ ASDFGHJKL:" asdfghjkl;\' ZXCVBNM<>? zxcvbnm,./'
    .split(' ')
    .map(r=>(p=r.indexOf(c))<0?0:q=r[(p+d)%r.length],q=c)&&q
  ].join('')

// TEST

out=x=>O.innerHTML+=x+'\n'

;[['Hello World',7,],['My name is Tim',3],['I Wi5h I h4d b3773r C@d3ing ski{{s', 3]]
.forEach(p=>out(p+' -> '+f(p[0],p[1])))
```

```
<pre id=O></pre>
```

# Answer
> 0 votes
# CJam, 107 bytes

```
lS/)~\S*\",./ ;'  <>? :\"  _+~!@#$%^&*() -=`"A,s(++S/"zxcvbnm
asdfghjkl
[]\qwertyuiop"N/_32ff^+.+_@fm>s\ser

```

Try it online in the CJam interpreter.

### How it works

```
lS/)   e# Read one line from STDIN, split at spaces and pop the last chunk.
~\S*\  e# Evaluate the popped chunk and join the remaining ones back together.
",./ ;'  <>? :\"  _+~!@#$%^&*() -=`"
       e# Push that string.
A,s(++ e# Concatenate it with "1234567890".
S/     e# Split at spaces.
"zxcvbnm asdfghjkl []\qwertyuiop"
       e# Push that string.
S/     e# Split at spaces. (`N/' would split at linefeeds.)
_32ff^ e# XOR each character of a copy with 32.
+      e# Concatenate the copies.
.+     e# Perform vectorized concatenation. This pushes the following array:
          [ ",./zxcvbnm" ";'asdfghjkl" "[]\qwertyuiop" "<>?ZXCVBNM"
           ":\"ASDFGHJKL" "{}|QWERTYUIOP" "_+~!@#$%^&*()" "-=`1234567890" ]
_@fm>  e# Rotate each chunk by the number of character specified in the input.
s\s    e# Flatten this array and the original.
er     e# Perform transliteration.

```

# Answer
> 0 votes
# Jelly, 67 bytes

```
ØDṙ1ṭØQ;Øq;"“{}|“:"“<>?“-=`“[]\“;'“,./“~!@#$%^&*()_+“ ”
¢œiⱮ+2¦€œị¢

```

Try it online!

A dyadic link taking the string as its left argument and the number of places to shift as its right argument.

# Answer
> 0 votes
# Python 2, 194 bytes

```
f=lambda s,n:n and f(''.join(B[B.find(c)+1]for c in s),n-1)or s
A='qwertyuiop%sqasdfghjkl%sazxcvbnm%sz'
B='`1234567890-=`~!@#$%^&*()_+~'+A%('[]\\',";'",',./')+(A%('{}|',':"','<>?')).upper()+'  '

```

Try it online!

---
Tags: code-golf, keyboard
---


title: Count rook moves 1D

text:
# Question
Title: Count rook moves 1D
Given a position with a row of rooks and/or empty spaces, output how many different rook moves are possible. A rook can move left or right to an empty space, but not to one that requires passing over another rook. When a rook moves, the other rooks remain in place.

For example, from this position, **6 moves** are possible:

```
.R..RRR.

```
* The first (leftmost) rook can move 1 space left, or 1 or 2 spaces right (3 moves)
* The next rook can only move 1 or 2 spaces left (2 moves)
* The third rook cannot move at all because it's squeezed between two other rooks (0 moves)
* The last rook can only move 1 space right (1 move)

Note that a position might have no rooks at all, or no empty spaces at all.

**Input:** A non-empty list (string, array, etc..) of rooks and empty spaces. You can represent them as `True`/`False`, `1`/`0`, `'R'`/`'.'`, or any two consistent distinct single-byte characters or one-digit numbers of your choice. It's up to you which one means rook and which means empty space.

**Output:** A non-negative integer. Whole-number floats are also fine.

**Test cases**

The output is the number on the left.

```
6 .R..RRR.
0 .
0 R
4 R..RR
3 ...R
8 ..R..R..
0 ......

```

For more test cases, here are all inputs up to length 5.

```
0 .
0 R
0 ..
1 .R
1 R.
0 RR
0 ...
2 ..R
2 .R.
1 .RR
2 R..
2 R.R
1 RR.
0 RRR
0 ....
3 ...R
3 ..R.
2 ..RR
3 .R..
3 .R.R
2 .RR.
1 .RRR
3 R...
4 R..R
3 R.R.
2 R.RR
2 RR..
2 RR.R
1 RRR.
0 RRRR
0 .....
4 ....R
4 ...R.
3 ...RR
4 ..R..
4 ..R.R
3 ..RR.
2 ..RRR
4 .R...
5 .R..R
4 .R.R.
3 .R.RR
3 .RR..
3 .RR.R
2 .RRR.
1 .RRRR
4 R....
6 R...R
5 R..R.
4 R..RR
4 R.R..
4 R.R.R
3 R.RR.
2 R.RRR
3 RR...
4 RR..R
3 RR.R.
2 RR.RR
2 RRR..
2 RRR.R
1 RRRR.
0 RRRRR

```

# Answer
> 9 votes
# Retina, ~~14~~ 9 bytes

```
w`_+R|R_+

```

Try it online! Link includes test cases. Uses `_` for empty space as it's the most pleasant non-regex character. Works by counting the number of substrings that correspond to a valid Rook move. A substring is a valid Rook move if it contains at least one `_` plus a single `R` at either the beginning or the end.

# Answer
> 9 votes
# Python 3, ~~30~~ 29 bytes

```
lambda s:sum((s+s).strip())/9

```

Try it online!

*-1 byte thanks to @JoKing*

The function takes a Python byte string as input. Each empty space is encoded as a tab and each rook is encoded as a byte `b'\x00'` having value `0`.

The computation is equivalent to `lambda s:(s+s).strip().count(b'\t')` while having a lower byte count.

# Answer
> 6 votes
# JavaScript (ES6),  ~~38~~  33 bytes

*Saved 5 bytes thanks to @JoKing*

Takes input as a string. Expects a space for an empty square and any other character for a rook.

```
s=>(s+s).trim().split` `.length-1

```

Try it online!

### Commented

```
s =>          // s = input, e.g. " R  RRR "
  (s + s)     // double -> " R  RRR  R  RRR "
  .trim()     // remove leading and trailing spaces -> "R  RRR  R  RRR"
  .split` `   // split on spaces -> [ 'R', '', 'RRR', '', 'R', '', 'RRR' ]
  .length - 1 // return the length - 1 -> 6

```

---

# Python 2,  ~~40~~  33 bytes

*Saved 7 bytes thanks to @Grimy*

```
lambda s:(s+s).strip().count(' ')

```

Try it online!

# Answer
> 5 votes
# Japt, 5 bytes

```
²x èS

```

Try it

```
²x èS        Implicit input string of U
²            U + U
 x           Remove trailing and leading whitespace
   èS        Number of spaces

```

# Answer
> 4 votes
# Perl 6, 16 bytes

```
{+m:ex/s+R|Rs+/}

```

Try it online!

A regex that matches all exhaustive instances of rooks followed by spaces, or spaces followed by a rook and returns the number of matches.

# Answer
> 4 votes
# 05AB1E, 5 bytes

```
«ðÚð¢

```

Try it online!

```
«       # concatenate the input with itself
 ðÚ     # remove leading and trailing spaces
   ð¢   # count spaces

```

# Answer
> 3 votes
# Retina, ~~23~~ 15 bytes

Double the number of spaces between rooks, grep lines with at least one rook, then count the number of spaces.

```
R.+R
$0$0
G`R

```

**Try it online!**

Though the program uses spaces instead of periods, I added prefix code so that the test cases provided may be easily pasted in and used.

I was hoping I could use overlapping matches with `(?<=R.*) | (?=.*R)`, but overlaps aren't quite that aggressive. It would need to count all possible ways a match could be obtained in order to return the correct result with that method.

# Answer
> 2 votes
# Jelly, 5 bytes

```
ḲẈ+ƝS

```

Try it online!

-1 thanks to Jonathan Allan.

`0` represent a rook, `1` represents an empty space.

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~43~~ 38 bytes

```
Count[Subsequences@#,{0,1..}|{1..,0}]&

```

Try it online!

Port of Neil's Retina solution. Uses 1 for spaces and 0 for rooks.

# Answer
> 2 votes
# Jelly, 6 bytes

```
t1;ḟẠS

```

Try it online!

A monadic link taking a list of `0` for rook and `1` for space and returning an integer with the number of moves. The TIO link takes the pasted list of possible boards given in the question, converts to the right format and then outputs the calculated and correct answers.

## Explanation

```
t1     | Trim 1s from end
  ;    | Concatenate to input
   ḟẠ  | Filter out 1s if all input were 1s, otherwise filter out 0s
     S | Sum

```

# Answer
> 2 votes
# Japt, 6 bytes

Spaces for spaces, any other character for rooks.

```
²x ¸ÊÉ

```

Try it

# Answer
> 2 votes
# Snails, 7 bytes

At least it beats Retina :)

```
o
\.+\R

```

Try it online!

# Answer
> 2 votes
# Stax, 7 6 5 bytes

```
àσQ█ε

```

Run and debug it

Use tab for empty square and any other character for rook.

# Answer
> 2 votes
# C (clang), 57 bytes

```
i,r,o;g(*n,z){for(o=r=i=0;z--;i=-~i*!*n++)o+=*n?r=1,i:r;}

```

Try it online!

* Saved 1 thanks to @ceilingcat

I realized it didn't worked for empty lists.. Now it works! Plus saved some bytes!

1=rook. 0=space.

for(.. i+=*n++?-i:1)// counts spaces or reset extra moves =\> i=-~i*!\*n++ ( @ceilingcat )

o+=\*n?r=1,i:r; // adds to output -i-(extra moves) when a rook is met plus sets -r-(rook met), -i- will be cleared in for increment sentence.

adds -r- for every space(rook met guaranteed )

# Answer
> 2 votes
# Haskell, 36 bytes

```
f s=sum$snd.span(>0)=<<[s,reverse s]

```

Try it online!

Uses 1 for empty space, 0 for rook. Counts the number of 1's not in an initial block of ones, and adds that to the result for the reversed string.

# Answer
> 2 votes
# Haskell, 33 bytes

```
sum.(t.reverse<>t)
t=snd.span(>0)

```

Try it online!

Anonymous function that takes input as a list of 1s (spaces) and 0s (rooks). This trims spaces from the start and the end of the list, then concatenates the two versions of the list and sums them.

This uses GHC 8.4.1 or later to have access to the `<>` operator without importing it.

# Answer
> 1 votes
# Python 2, 59 bytes

```
def f(r):S=map(len,r.split('R'));return sum(S)*2-S[0]-S[-1]

```

Try it online!

# Answer
> 1 votes
# Japt, 6 bytes

```
²x ¸ÊÉ

```

Try it online

# Answer
> 1 votes
# Stax, ~~7~~ 6 bytes

-1 byte thanks to recursive

```
╣ë|óêπ

```

Run and debug it

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 27 bytes

```
x=>(x+x).Trim().Sum(d=>d)/9

```

Saved a byte thanks to @someone

Try it online!

# Answer
> 1 votes
# Haskell, ~~68~~ ~~58~~ 54 bytes

```
(n#y)(a:x)|a<1=n+(0#1)x|m<-n+1=y+(m#y)x
(_#_)x=0
f=0#0

```

Try it online!

# Answer
> 1 votes
## , 183 156 151 ~~137~~ ~~96~~ 91 bytes

Thanks to ceilingcat for 91 bytes.

```
c,e;char*z,b[9];main(d){for(gets(z=b);e=*z>81?c-=e*~!d,d=0:e+1,*++z;);printf("%i",d?:c+e);}

```

R is a rook, everything else is a space.

TIO

# Answer
> 1 votes
# Perl 5 `-MList::Util=sum -pF/R/`, 40 bytes

```
$\=2*sum map$_=y///c,@F}{$\-="@F"+$F[-1]

```

Try it online!

# Answer
> 1 votes
# Red, 46 bytes

```
func[s][length? next split trim append s s sp]

```

Try it online!

Just a Red port of Arnauld's JavaScript/Python solutions. Takes a space as an empty square.

# Answer
> 1 votes
# Java 11, ~~35~~ 32 bytes

```
s->(s+s).strip().chars().sum()/9

```

Port of *@Joel*'s Python 3 answer.
-3 bytes thanks to *@Joel* as well.

Uses NULL-bytes (`\0`) for Rooks and tabs (`\t`) for spaces.

Try it online.

I tried using `s->(s+s).trim().chars().sum()/9` at first as 31-byter, but this doesn't work because the `String#trim` builtin not only removes leading and trailing spaces/tabs/newlines, but also all other bytes that are smaller than or equal to `U+0020` (unicode 32; a space), so it'll remove the NULL-bytes as well..
Thanks to *Joel* for recommending me the new Java 11+ `String#strip` builtin (which I forgot they added) as alternative. This one also removes trailing/leading portions, but in this case only whitespaces, so the NULL-bytes are retained.

**Explanation:**

```
s->                              // Method with String as parameter & integer return-type
  (s+s)                          //  Concatenate the input to itself
       .strip()                  //  Then trim all leading and trailing tabs
               .chars().sum()    //  Sum the unicode values of the remaining characters
                             /9  //  And divide it by 9 to get the amount of remaining tabs

```

# Answer
> 1 votes
# Befunge-98 (PyFunge), 73 bytes

```
#;ep10fp#;>#v~:'.-#v_$1+0k
v0+ge0*gf0$_v#!-R':<
>ep20fp   v >0fg1-*0eg+.@

```

Try it online!

# Answer
> 0 votes
# Pyth, 7 bytes

```
/r6*2Qd

```

Try it online!

Takes a string of `R` for rooks,  (space) for empty spaces

```
/     d  # Count spaces in
 r6      #  Strip spaces from
   *2Q   #   2 * input() (= concatenation)

```

# Answer
> 0 votes
# x86-64 - 26 Bytes

Input is an array of up to 32 bits and an integer representing number of squares, 1 representing rook, 0 representing empty.

```
C4 E2 69 F7 C1       shlx        eax,ecx,edx
0B C1                or          eax,ecx
F3 0F BC C8          tzcnt       ecx,eax
D3 E8                shr         eax,cl
F3 0F BD C8          lzcnt       ecx,eax
F7 D0                not         eax
F3 0F B8 C0          popcnt      eax,eax
2B C1                sub         eax,ecx
C3                   ret

```

Copies the bits so that it is added to the left of it and removes the trailing zero bits. Then gets number of leading zero bits and subtracts it from the total number of zero bits.

# x86-64 Machine Code - 22 Bytes - regular length chess ranks only.

Input is a 32-bit integer with the least significant byte made of 8 bits representing the rooks. 1 is a rook, 0 is empty.

```
8A E9                mov         ch,cl
91                   xchg        eax,ecx
F3 0F BC C8          tzcnt       ecx,eax
D3 E8                shr         eax,cl
F3 0F BD C8          lzcnt       ecx,eax
F7 D0                not         eax
F3 0F B8 C0          popcnt      eax,eax
2B C1                sub         eax,ecx
C3                   ret

```

Copies the bits into the next significant byte and removes the trailing zero bits. Then gets number of leading zero bits and subtracts it from the total number of zero bits.

---
Tags: code-golf, counting, chess
---


# Question
Title: 1 character typo generating most error messages from C++ compilation
It seems that simple changes to a C++ file, especially with templates, can generate pages of errors. This contest is to see what the largest "bang of the buck" is, that is the more verbose error output with the smallest change to the source code (1 character addition).

Because other languages are more sane, this will be limited to C++ and gcc version 4.x.

Rules

1. Original source file must compile with gcc 4.9.2 to object code without error.
2. One ASCII character is added to source code to create a typo, increasing file size by 1 byte.
3. Compiler is run with default options. Necessary options like `-c` and `-std=c++11` are allowed, options like `-Wall` are not.
4. Metric is

```
    number of bytes of generated error messages
    -----------------------------------------------------------------------
    (bytes of source code with typo) (length of filename passed to compiler)

```
5. Answers will be validated with http://ideone.com/ C++ 4.9.2.

Example:

Filename is `a.cpp`, which is 5 bytes long.

```
int foo();

```

Working Compilation

```
 gcc -c a.cpp

```

Corrupted source code:

```
in t foo();

```

Failing Compilation

```
$ gcc -c a.cpp
a.cpp:1:1: error: ‘in’ does not name a type
in t foo();
  ^
$ gcc -c a.cpp |& -c wc
64
$ wc -c a.cpp
12 a.cpp

```

Score: 64/12/5 = **1.0666**

Better attempt: Insert `{` between parens of `foo()`

```
$ gcc -c a.cpp |& wc -c
497

```

New score: 497/12/5 = **8.283**

Good Luck!

UPDATE

I encourage people to ignore the recursive implementation. That technically wins but is not in the spirit of the contest.

UPDATE 2

As many people have noted, the contest probably would have been more interesting if the C pre-processor was not allowed. So I would like to encourage people to post solutions that do not use pre-processor commands at all. That implies no use of any header files at all, since `#include` is not allowed!

As far as using IDEONE to validate, you are allowed to either use the IDEONE output directly (and the source name as `prog.cpp`), or you can run the IDEONE output through a global search and replace (`s/prog.cpp/a.cc/` for example) and pretend that you were able to set the file name directly.

UPDATE 3

As people pointed out, Ideone is a little too restrictive, requiring linkage not just object file creation. As this contest is purely in the name of fun, please be honest and specify what you used to get your score. Either use ideone, or use the most vanilla build (all defaults) of gcc 4.9.2 as you can muster. The contest is intended to bring awareness to the awfulness of C++ error messages.

# Answer
> 47 votes
**gcc 4.5.2, Score: 8579.15** (or **14367.49** for filename "a.C", may update later)

Original file, 29 bytes, compiles clean (a.cpp):

```
#if 0
#include"a.cpp"
#endif

```

Modified file, 30 bytes:

```
#iff 0
#include"a.cpp"
#endif

```

Errors:

```
$ gcc -c a.cpp 2>&1 | wc -c
1286873

```

Score:

1286873 / (30 * 5) = 8579.15

Head and tail of error output:

```
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:

... And so on, backing out with second error after max include depth:

a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0:
a.cpp:3:2: error: #endif without #if
a.cpp:3:2: error: #endif without #if

```

Note:
\- If `.C` ends up qualifying as a valid extension then score is 1,206,869 / (28 * 3) = 14,367.49.
\- If Dennis' suggested second #include is added, file name "a.cpp", score is 80,797,292,934 / (46 * 5) = 351,292,578.97

# Answer
> 31 votes
# gcc 4.9.2, score: ~~222,898,664~~ 663,393,783

This is heavily based on @JasonC's answer, but he said he didn't want to take credit for this improvement.

The error output of the code below is 126,044,818,789 bytes long. The score should be much higher in theory (and tend to infinity as the number of include statements increases), but it decreases in practice by adding more include statements.

### Original file (37 bytes)

```
/*#
#include"w.cpp"
#include"w.cpp"*/

```

```
$ gcc -c w.cpp
$

```

### Modified file (38 bytes)

```
/
*#
#include"w.cpp"
#include"w.cpp"*/

```

```
$ gcc -c w.cpp
w.cpp:2:2: error: stray ‘#’ in program
 *#
  ^
In file included from w.cpp:3:0:
w.cpp:2:2: error: stray ‘#’ in program
 *#
  ^
In file included from w.cpp:3:0,
                 from w.cpp:3:
w.cpp:2:2: error: stray ‘#’ in program
 *#
  ^
In file included from w.cpp:3:0,
                 from w.cpp:3,
                 from w.cpp:3:
w.cpp:2:2: error: stray ‘#’ in program
 *#
  ^
In file included from w.cpp:3:0,
                 from w.cpp:3,
                 from w.cpp:3,
                 from w.cpp:3:
⋮
w.cpp:2:2: error: stray ‘#’ in program
 *#
  ^
w.cpp:3:0: error: #include nested too deeply
 #include"w.cpp"
 ^
w.cpp:4:0: warning: extra tokens at end of #include directive
 #include"w.cpp"*/
 ^
w.cpp:4:0: error: #include nested too deeply
w.cpp:2: confused by earlier errors, bailing out
The bug is not reproducible, so it is likely a hardware or OS problem.

```

# Answer
> 25 votes
**gcc, 4.9.2, Score: 22.2**

Original file: 0 bytes (a.cpp)

Compiles clean:

```
$ gcc -c a.cpp |& wc -c
0

```

Modified file:

```
(

```

Errors:

```
$ gcc -c a.cpp |& wc -c
111

```

Score

111/1/5 = **22.2**

# Answer
> 24 votes
# 11,126.95 ~~9,105.44~~ ~~2,359.37~~ ~~1,645.94~~ ~~266.88~~ points

More preprocessor abuse! This time, we're making the standard library cry.

Without typo:

```
#define typedf
#include<fstream>

```

With typo:

```
#define typedef
#include<fstream>

```

Errors:

```
In file included from /usr/include/c++/4.9/iosfwd:39:0,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/istream:38,
                 from /usr/include/c++/4.9/fstream:38,
                 from a.C:2:
/usr/include/c++/4.9/bits/stringfwd.h:62:33: error: aggregate ‘std::basic_string<char> std::string’ has incomplete type and cannot be defined
   typedef basic_string<char>    string;
                                 ^
/usr/include/c++/4.9/bits/stringfwd.h:68:33: error: aggregate ‘std::basic_string<wchar_t> std::wstring’ has incomplete type and cannot be defined
   typedef basic_string<wchar_t> wstring;
                                 ^
/usr/include/c++/4.9/bits/stringfwd.h:78:34: error: aggregate ‘std::basic_string<char16_t> std::u16string’ has incomplete type and cannot be defined
   typedef basic_string<char16_t> u16string;
                                  ^
/usr/include/c++/4.9/bits/stringfwd.h:81:34: error: aggregate ‘std::basic_string<char32_t> std::u32string’ has incomplete type and cannot be defined
   typedef basic_string<char32_t> u32string;
                                  ^
In file included from /usr/include/wchar.h:36:0,
                 from /usr/include/c++/4.9/cwchar:44,
                 from /usr/include/c++/4.9/bits/postypes.h:40,
                 from /usr/include/c++/4.9/iosfwd:40,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/istream:38,
                 from /usr/include/c++/4.9/fstream:38,
                 from a.C:2:
/usr/include/stdio.h:48:25: error: aggregate ‘_IO_FILE FILE’ has incomplete type and cannot be defined
 typedef struct _IO_FILE FILE;
                         ^
/usr/include/stdio.h:64:25: error: aggregate ‘_IO_FILE __FILE’ has incomplete type and cannot be defined
 typedef struct _IO_FILE __FILE;
                         ^
In file included from /usr/include/c++/4.9/cwchar:44:0,
                 from /usr/include/c++/4.9/bits/postypes.h:40,
                 from /usr/include/c++/4.9/iosfwd:40,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/istream:38,
                 from /usr/include/c++/4.9/fstream:38,
                 from a.C:2:
/usr/include/wchar.h:106:9: error: ‘__mbstate_t’ does not name a type
 typedef __mbstate_t mbstate_t;
         ^
/usr/include/wchar.h:151:38: error: ‘size_t’ is not a type
     const wchar_t *__restrict __src, size_t __n)
                                      ^
/usr/include/wchar.h:159:38: error: ‘size_t’ is not a type
     const wchar_t *__restrict __src, size_t __n)
                                      ^
/usr/include/wchar.h:166:63: error: ‘size_t’ is not a type
 extern int wcsncmp (const wchar_t *__s1, const wchar_t *__s2, size_t __n)
                                                               ^
/usr/include/wchar.h:176:4: error: ‘size_t’ is not a type
    size_t __n) __THROW;
    ^
In file included from /usr/include/wchar.h:180:0,
                 from /usr/include/c++/4.9/cwchar:44,
                 from /usr/include/c++/4.9/bits/postypes.h:40,
                 from /usr/include/c++/4.9/iosfwd:40,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/istream:38,
                 from /usr/include/c++/4.9/fstream:38,
                 from a.C:2:
/usr/include/xlocale.h:42:9: error: ‘__locale_t’ does not name a type
 typedef __locale_t locale_t;
         ^
In file included from /usr/include/c++/4.9/cwchar:44:0,
                 from /usr/include/c++/4.9/bits/postypes.h:40,
                 from /usr/include/c++/4.9/iosfwd:40,
                 from /usr/include/c++/4.9/ios:38,
                 from /usr/include/c++/4.9/istream:38,
                 from /usr/include/c++/4.9/fstream:38,
                 from a.C:2:
/usr/include/wchar.h:183:5: error: ‘__locale_t’ is not a type
     __locale_t __loc) __THROW;
     ^
/usr/include/wchar.h:186:6: error: ‘size_t’ is not a type
      size_t __n, __locale_t __loc) __THROW;
      ^
/usr/include/wchar.h:186:18: error: ‘__locale_t’ is not a type
      size_t __n, __locale_t __loc) __THROW;
                  ^
/usr/include/wchar.h:196:8: error: ‘size_t’ does not name a type
 extern size_t wcsxfrm (wchar_t *__restrict __s1,
        ^
/usr/include/wchar.h:207:9: error: ‘__locale_t’ is not a type
         __locale_t __loc) __THROW;
         ^
/usr/include/wchar.h:212:8: error: ‘size_t’ does not name a type
 extern size_t wcsxfrm_l (wchar_t *__s1, const wchar_t *__s2,
        ^
/usr/include/wchar.h:252:8: error: ‘size_t’ does not name a type
 extern size_t wcscspn (const wchar_t *__wcs, const wchar_t *__reject)
        ^
/usr/include/wchar.h:256:8: error: ‘size_t’ does not name a type
 extern size_t wcsspn (const wchar_t *__wcs, const wchar_t *__accept)
        ^
/usr/include/wchar.h:287:8: error: ‘size_t’ does not name a type
 extern size_t wcslen (const wchar_t *__s) __THROW __attribute_pure__;
        ^
/usr/include/wchar.h:306:8: error: ‘size_t’ does not name a type
 extern size_t wcsnlen (const wchar_t *__s, size_t __maxlen)
        ^

```

\[SNIP\]

```
/usr/include/c++/4.9/bits/fstream.tcc:934:35: error: ‘cur’ is not a member of ‘std::ios_base’
    __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
                                   ^
/usr/include/c++/4.9/bits/fstream.tcc:934:50: error: ‘_M_mode’ was not declared in this scope
    __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
                                                  ^
/usr/include/c++/4.9/bits/fstream.tcc:941:25: error: ‘_M_state_last’ was not declared in this scope
    + _M_codecvt->length(_M_state_last, _M_ext_buf,
                         ^
/usr/include/c++/4.9/bits/fstream.tcc:944:15: error: ‘streamsize’ does not name a type
         const streamsize __remainder = _M_ext_end - _M_ext_next;
               ^
/usr/include/c++/4.9/bits/fstream.tcc:945:13: error: ‘__remainder’ was not declared in this scope
         if (__remainder)
             ^
/usr/include/c++/4.9/bits/fstream.tcc:949:35: error: ‘__remainder’ was not declared in this scope
         _M_ext_end = _M_ext_buf + __remainder;
                                   ^
/usr/include/c++/4.9/bits/fstream.tcc:951:25: error: ‘_M_state_cur’ was not declared in this scope
         _M_state_last = _M_state_cur = _M_state_beg;
                         ^
/usr/include/c++/4.9/bits/fstream.tcc:951:40: error: ‘_M_state_beg’ was not declared in this scope
         _M_state_last = _M_state_cur = _M_state_beg;
                                        ^
/usr/include/c++/4.9/bits/fstream.tcc:960:2: error: ‘_M_codecvt’ was not declared in this scope
  _M_codecvt = _M_codecvt_tmp;
  ^
/usr/include/c++/4.9/bits/fstream.tcc:960:15: error: ‘_M_codecvt_tmp’ was not declared in this scope
  _M_codecvt = _M_codecvt_tmp;
               ^
/usr/include/c++/4.9/bits/fstream.tcc:962:2: error: ‘_M_codecvt’ was not declared in this scope
  _M_codecvt = 0;
  ^

```

On my Ubuntu machine, `g++-4.9 -std=c++11 -c a.C` generates 1,101,568 glorious bytes of errors, for a score of 1101568/33/3 = 11,126.95.

# Answer
> 11 votes
# 62.93 points

Just some C++ meta black magic, compiled with `g++-4.8 -c -std=c++11 a.cc`:

```
#include<memory>
template<int n>class B:std::unique_ptr<B<n-1>>{};template<>class B<0>{};B<-1>x;

```

Ungolfed:

```
#include <memory>

template<int n>
class B: std::unique_ptr<B<n-1>> {};

template<>
class B<0> {};

B<-1>x;

```

G++ has a recursion limit of 900, so changing `B<1>` to `B<-1>` with a 31-bit range has an... interesting effect.

* 96 bytes of code (not counting the final `\n` some text editors automatically add, `vim` doesn't).
* 4-letter filename, `a.cc`
* 24165 bytes of error message, and it's truncated. The full error message has a whopping 1235889 bytes of content. It would require the `-ftemplate-backtrace-limit=0` switch. It would also mean 3185 points for me!

`std::unique_ptr` is just the template class that manages to emit the longest error message, found by trial and error and knowledge of the STL and cats and stuff.

# Answer
> 7 votes
## Score 7.865

Strictly speaking, the 0-byte-Answer is NOT correct, as ideone.com will refuse to compile the file without error. The same is true with the example `int foo();` \- it won't compile on ideone.com (I'm unable to comment because of missing reputation...)

So the smallest possible program to compile without any `#includes` is this:

```
int main(){}

```

If you change this to the following code, it will fail with 409 bytes of error code (after renaming prog.cpp to a.cc from the ideone.com output):

```
int main(){[}

```

409 / ( 13 * 4 ) = 7.865

Please update the question accordingly, as the examples given don't respect the given rules...

# Answer
> 1 votes
# C, named as `.cc`

```
main(){constexprs a(){*(int*)0=f;}a(0)}

```

Error code:

```
.code.tio.cpp: In function ‘int main()’:
.code.tio.cpp:1:8: error: ‘constexprs’ was not declared in this scope
 main(){constexprs int a(f){*(int*)0=f;}a(0);}
        ^~~~~~~~~~
.code.tio.cpp:1:8: note: suggested alternative: ‘__cpp_constexpr’
 main(){constexprs int a(f){*(int*)0=f;}a(0);}
        ^~~~~~~~~~
        __cpp_constexpr
.code.tio.cpp:1:40: error: ‘a’ was not declared in this scope
 main(){constexprs int a(f){*(int*)0=f;}a(0);}

```

# Answer
> 1 votes
# Score 12.xx (error by DELETING a character)

Please forgive the breaking of Rule 2 (IMHO adding OR deleting one character would be in the spirit of the rule), but this happened to me accidentally (thus doesn't use any 'intentionally' abusive tricks) while writing Real Code (TM) - both the working and error-causing code are (or look) simple and straightforward, so I thought it neat enough to include here. Original code

```
#include <iostream>
using namespace std;
int main ()
{
cout<<"test"<<endl;
}

```

Code generating the error (last '\<' deleted so it looks like a less-than comparison, but noooooooooooo ...)

```
#include <iostream>
using namespace std;
int main ()
{
cout<<"test"<endl;
}

```

It's 'only' 8241 bytes of compiler error messages in ideone.com g++ 4.3.2.

ETA: Added a couple of lines to make it fit the rules. I knew these silly macros would come in handy someday. Ashamed it took so long because I've known C very well for a very long time. This code compiles and runs:

```
#include <iostream>
using namespace std;
#define a <<
#define aa <
int main ()
{
    cout<<"test" a endl;
}

```

Add another letter a after "test" a to make it fail:

```
#include <iostream>
using namespace std;
#define a <<
#define aa <
int main ()
{
    cout << "test" aa endl;
}

```

---
Tags: code-challenge, compile-time, error-message
---


title: Write an interpreter for simplified 33

text:
# Question
Title: Write an interpreter for simplified 33
33 is a simple esolang I created. You may have seen me use it in a few questions. You're not going to be writing a full interpreter. The interpreter you will be writing is for a simplified version of 33.

This simplified 33 has two numeric registers: the accumulator and the counter. The accumulator holds all the post-arithmetic values, the counter is where numbers in the program come from. Both registers are initialized to 0.

```
0-9 | Appends the digit to the counter
a   | Adds the counter to the accumulator
m   | Subtracts the counter from the accumulator
x   | Multiplies the accumulator by the counter
d   | Divides the accumulator by the counter
r   | Divides the accumulator by the counter, but stores the remainder in the accumulator
z   | Sets the counter to 0
c   | Swaps the accumulator and counter
-----
p   | Outputs the current value of the accumulator as an ASCII character
o   | Outputs the current value of the accumulator as a formatted decimal number
i   | Outputs a newline character (0x0a)
-----
P   | Stores the ASCII value of the next character read in the accumulator
O   | Stores the next integer read into the accumulator
-----
n   | Skips the next instruction if the accumulator is not 0
N   | Skips the next instruction if the accumulator is 0
g   | Skips the next instruction if the accumulator is less than or equal to 0
G   | Skips the next instruction if the accumulator is greater than 0
h   | Skips the next instruction if the accumulator is greater than or equal to 0
H   | Skips the next instruction if the accumulator is less than 0

```

## Test cases

```
Program / Input -> Output
2o          -> 0
25co        -> 25
1a0aoi      -> 11 (trailing newline)
Oo / 42     -> 42
Op / 42     -> *
1cNoo       -> 11
no          -> 0
Ogo / 2     -> 2
Ogoi / -4   -> (newline)
50a         -> (no output)
On12co / 12 -> 2

```

## Clarifications

* The input to your interpreter will be a valid simplified 33 program.
* The input may be given in any acceptable format.
* The output may be given in any acceptable format.
* When dividing, truncate any decimal places.
* A trailing newline is acceptable, but it must be consistent; as in, if there's an `i` at the end of the program, it should have two trailing newlines.
* The accumulator and counter must be able to hold at least a signed byte (-128 to 127)
* You may assume that the `p` instruction will never be given when the accumulator has an invalid ASCII character in it.
* You may assume the `O` instruction will never be given unless there is a valid integer string (such as `3`, `-54`, `+23`) left in the input.

# Answer
> 1 votes
# JavaScript (Node.js), 264 bytes

```
S=>I=>[...S].map(s=>K?K=0:1/s?C=+(C+s):eval("A*=C;[A,C]=[C,A];K=!A;;K=A;K=A>0;A%=C;K=A<=0;A=A/C|0;I=I.replace(/-?\\d+/,n=>(A=+n,''));K=A>=0;O+=A;K=A<0;A+=C;C=0;;[A]=B(I[0]),I=I.slice(1);O+=`\n`;O+=B([A]);A-=C".split`;`[B(s)[0]*73%378%22]),A=C=K=0,O='',B=Buffer)&&O

```

Try it online!

Saved ~20 bytes, thanks to Arnauld's magic integer modulus.

# Answer
> 0 votes
### Lua 5.3, 342 bytes

Code is provided as a cmdline argument, input is provided via stdin.

```
H=string.char R=io.read A=0 C=0 i=1 s=...while i<=#s do
b=s:byte(i)d=H(b)i=i+(({H=A<0,G=A>0,N=A==0,g=A<=0,h=A>=0,n=A~=0})[d]and 2or
1)io.write(({i='\n',o=A|0,p=H(A%255)})[d]or'')A,C=d=='O'and R'n'or d=='P'and
R(1):byte()or d=='d'and A//C or d=='r'and A%C or({a=A+C,c=C,m=A-C,x=A*C})[d]or
A,b>=48 and b<58 and b-48+C*10or({c=A,z=0})[d]or C end

```

# Answer
> 0 votes
# Julia 1.0, 355 bytes

```
p=print
function f(s,a=0,c=0,i=1)
for x=s
z=findfirst(==(x),"amxdrzcpoiPOnNgGhH0123456789")
y=z-9
i<1&&(i=1;continue)
z<6 ? a=(+,-,*,÷,%)[z](a,c) :
z<7 ? c=0 :
z<8 ? ((a,c)=(c,a)) :
z<9 ? p(Char(a)) :
y<1 ? p(a) :
y<2 ? p("\n") :
y<3 ? a=0+read(stdin,UInt8) :
y<4 ? a=parse(Int,readline()) :
y<10 ? (!=,==,<=,>,>=,<)[y-3](a,0)&&(i=0) :
c=10c+y-10
end
end

```

Program provided as an argument, eg `f("2o")`, input taken from `stdin`.

Try it online!

---
Tags: code-golf, interpreter
---