title: Output a binary path from a number

text:
# Question
Title: Output a binary path from a number
For an integer `n` that satisfies `n > 0`, write its value as a right-descending path based on its binary representation.

# Rules

* The first (most significant) set bit is always in the top-left corner.
* When the next bit is set (a `1`), draw a character ("filled") on the next line in the same column as the previous character drawn. Try to use spaces ("empty") to fill, but any character will do as long as it's always the same.
* When the next bit is unset (a `0`), draw a character ("filled") on the same line immediately to the the right of the previous character drawn.
* Your code must support numbers with at least 20 significant bits.
* Write a full program, a function, a lambda, etc. but no snippet.
* No leading spaces (or "empty" char) / lines allowed
* Any number of trailing spaces (or "empty" char) / lines allowed
* Any kind of 1D input is accepted: number, string, array of booleans, etc. Keep the order of bits untouched though.
* Any kind of visual 2D output is accepted: on stdout, a string (with any two distinct values representing "filled" and "empty"), you can even output a matrix if you want. A list of numbers seems hard to reconcile with the "no heading spaces" rule, but I'm open to it if you find a way to use it. Note: if you chose to print or return a string, the characters used must be ASCII characters in the codepoints range \[32-126\].
* Standard loopholes are banned.
* This is codegolf so the shortest code wins.

# Examples

Input: 1

```
*

```

Input: 2

```
**

```

Input: 3

```
*
*

```

Input: 4

```
***

```

Input: 5

```
**
 *

```

Input: 6

```
*
**

```

Input: 7

```
*
*
*

```

Input: 25

```
*
***
  *

```

Input: 699050

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

```

Input: 1047552

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

```

Input: 525311

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

```

# Answer
# Jelly, 8 bytes

```
¬œṗ+\Ṭz0

```

A monadic link accepting a number as a list of ones and zeros (e.g. `13` is `[1,1,0,1]`) returning a list of lists of ones and zeros where the first list is the first row.

**Try it online!** or see a formatted test-suite

### How?

```
¬œṗ+\Ṭz0 - Link: list L           e.g. [1,1,0,0,1,1,0,1] (i.e. 205)
¬        - logical NOT L               [0,0,1,1,0,0,1,0]
    \    - cumulative reduce L by:
   +     -   addition                  [1,2,2,2,3,4,4,5]
 œṗ      - partition @ truthy indices  [[1,2],[2],[2,3,4],[4,5]]
     Ṭ   - un-truth (vectorises)       [[1,1],[0,1],[0,1,1,1],[0,0,0,1,1]]
      z0 - transpose with filler 0     [[1,0,0,0],[1,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1]]
         -                        i.e.  1000
                                        1110
                                        0010
                                        0011
                                        0001

```
> 7 votes

# Answer
# MATL, 14 bytes

```
J_iB^YsJ+'o-'&XG

```

Produces graphical output as a path starting at coordinates (0,0). Try it at **MATL Online!** Or see some offline examples below:

* Input `7`:

Output:

* Input `699050`:

Output:

If you prefer, you can see the path as complex coordinates for **9 bytes**:

```
J_iB^YsJ+

```

**Try it online!**

###Explanation

```
J_      % Push -1j (minus imaginary unit)
i       % Push input number
B       % Convert to binary. Gives an array of 0 and 1 digits
^       % Power, element-wise. A 0 digit gives 1, a 1 digit gives -1j
Ys      % Cumulative sum. Produces the path in the complex plane
J+      % Add 1j, element-wise. This makes the complex path start at 0
'o-'    % Push this string, which defines plot makers
&XG     % Plot

```
> 11 votes

# Answer
# MATL, 10 bytes

```
YsG~YsQ1Z?

```

Inputs an array of binary digits. Outputs a matrix.

Try it online!

### Explanation

```
Ys    % Implicit input: array of binary digits. Cumulative sum. This gives the
      % row coordinates
G     % Push input again
~     % Negate: change 0 to 1 and 1 to 0
Ys    % Cumulative sum
Q     % Add 1. This gives the column coordinates
1Z?   % Matrix containing 1 at those row and column coordinates and 0 otherwise.
      % Implicit display

```
> 7 votes

# Answer
# Python 2, ~~100~~ ~~99~~ ~~81~~ ~~78~~ ~~73~~ 66 bytes

```
a='';x=0
for c in input():a+=('\n'+' '*x)*c+'*';x+=1-c
print a[1:]

```

Try it online!

Recursive version:

# Python 2, ~~71~~ ~~69~~ 67 bytes

```
f=lambda n,x=0:n and('\n'[:x]+' '*x)*n[0]+'*'+f(n[1:],x+1-n[0])or''

```

Try it online!
> 6 votes

# Answer
# 05AB1E, ~~18~~ ~~17~~ 14 bytes

```
γ€gć¸s>«1IÔ·ÌΛ

```

Try it online!

**Explanation**

```
γ€g             # Push the input as the array as chuncks of consecutive elements, map with length
   ć¸s>«        # Increment each value except the first one
        1I      # Push 1 and the input
          Ô     # Push connected uniquified input (first elements of each chunck of consecutive elements in the input)
           ·Ì   # Map each with 2 * a + 2
             Λ  # Draw canvas :-)

```
* 3 bytes thanks to @Emigna

05AB1E canvas's explanation
> 6 votes

# Answer
# C# (.NET Core), ~~155~~ ~~123~~ ~~120~~ ~~113~~ 101 bytes

Saved 32 bytes due to input being able to be received as an array of bits.
Saved 7 bytes thanks to @auhmaan.
Saved 10 bytes thanks to @KevinCruijssen.

```
n=>{var m="";for(int i=0,c=1;i<n.Length;)m+=n[i++]<1?c++%1+"":(i>1?"\n":"")+"0".PadLeft(c);return m;}

```

Try it online!
> 6 votes

# Answer
# Charcoal, ~~22~~ ~~20~~ ~~19~~ ~~11~~ 10 bytes

```
Ｆ⮌Ｓ¿Ｉι↑*←*

```

Only my second Charcoal answer thus far.

Takes the input as binary-String (i.e. `699050` as `10101010101010101010`).

-9 bytes thanks to *@Neil* suggesting to loop backwards.

Try it online.

**Explanation:**

Read STDIN as string in reversed order:

```
Reverse(InputString())
⮌Ｓ

```

Loop over its binary digits as strings `ι`:

```
For(Reverse(InputString()))
Ｆ⮌Ｓ

```

If `ι` casted back to a number is 1, print the `*` upwards, else print the `*` towards the left.

```
If(Cast(i)) Print(:Up,"*"); Else Print(:Left,"*");
¿Ｉι↑*←*

```
> 6 votes

# Answer
# Haskell, 65 bytes

```
f(a:b)|a="*":f b|(x:y)<-f b=('*':x):map(' ':)y
f[]=["*"]
f.tail

```

Try it online!

Takes input as a list of booleans.

# Curry PAKCS, 70 bytes

```
u(a:b)=('*':a):map(' ':)b
f(a:b)|a="*":f b|1>0=u$f b
f[]=["*"]
f .tail

```

Port of the Haskell answer, but because `<-` doesn't work in Curry we need to make a helper function `u`. We also need to add a space between `f` and `.` so that Curry parses it as a compose rather than a dot.

This also works in MCC Curry, but doesn't work in Sloth Curry (which is the only one supported by TIO).
> 4 votes

# Answer
# Haskell, ~~74~~ ~~70~~ ~~67~~ 62 bytes

```
tail.("\n"%)
s%(x:r)=([1..x]>>s)++'*':(s++[' '|x<1])%r
s%[]=""

```

Try it online! Takes a list of zeros and ones as input and returns a newline separated string.

Inspired by xnor's answer.
> 3 votes

# Answer
# Python 2, 59 bytes

```
s=p='\n'
for x in input():s+=p*x+'*';p+=' '[x:]
print s[2:]

```

Try it online!

Based off TFeld's solution.
> 3 votes

# Answer
# Emojicode, 251 bytes

```
b2c*eykbi ki1y eyyye cyy ce  ey

```

Try it online!

This is definitly not a golfed solution, but there isn't a person alive that would consider Emoji-code a golfing language. However, in the process of subjecting myself to the horrors that are emoji-code's syntax in an effore to teach myself this monstrosity of a language, I've been pleasantly surprised by just how powerful and efficient it can be

**Explaination:**

```
       Define Class
     Define Method
b2    Convert Input integer to binary string
c*     asterisk string
e     Spacing string
y     output string
kb     translate to iteratable
i k     for-in loop to iterate over each digit
i1     if digit is 1:
y e     don't print initial newline
y     print spaces + asterisks
y     reset output string
ye c     add correct number of spaces and one asterisk
     if digit is 0:
yy c     add an asterisk to the output string
e  e     add another space to the space string

y     print one last output string

     Start Program
  699050     Call Method

```
> 3 votes

# Answer
# JavaScript (ES6), 48 bytes

Same I/O format and same logic as the recursive version below.

```
a=>a.map((n,i)=>n?i&&p+0:+(p+=' '),p=`
`).join``

```

Try it online!

Or **42 bytes** if this format is acceptable.

---

# Recursive version, 56 bytes

Takes input as an array of integers (0 or 1). Uses `0` for filled and space for empty.

```
f=([n,...a],p=`
`,x=0)=>1/n?(n?x+0:+(p+=' '))+f(a,p,p):a

```

Try it online!

### Commented

```
f = (               // f = recursive function taking:
  [n, ...a],        //   n = current bit; a[] = remaining bits
  p = `\n`,         //   p = padding string, initialized to a linefeed
  x = 0             //   x = 0 on the 1st iteration / equal to p after that
) =>                //
  1 / n ?           // if n is defined:
    ( n ?           //   if n = 1:
        x + 0       //     append x + 0 --> either the integer 0 on the first iteration
                    //                      or the padding string followed by a '0'
      :             //   else:
        +(          //     append the integer 0 (whitespace coerced to a number)
          p += ' '  //     and append a space to the padding string
        )           //
    ) + f(a, p, p)  //   append the result of a recursive call with x = p
  :                 // else:
    a               //   append the empty array a[], forcing coercion to a string

```
> 2 votes

# Answer
# Java 10, ~~100~~ 106 bytes

```
b->{var s="";int i=0,j;for(var c:b){if(c)for(s+="\n",j=i;j-->0;)s+=0;else++i;s+=1;}return s.substring(1);}

```

Takes an array of booleans and returns a String (`0`s are empty, `1`s are filled). Try it online here.

Thanks to Olivier Grégoire for helping me golf it a bit more and alerting me to the fact that my output format was not up to the spec.

Ungolfed version:

```
b -> { // lambda taking an array of booleans as argument
    var s = ""; // the output String
    int i = 0,  // the number of "empty" characters to output
    j;          // iterator variable for outputting the "empty" characters
    for(var c : b) { // iterate over the boolean array (the binary digits)
        if(c) // if it's a '1'
            for(s += "\n", // output a newline
            j = i; j-- > 0;) s += 0; // output the "empty" characters
        else // if it's a '0'
            ++i; // move one to the right on the next line
        s += 1; // output the "filled" character
    }
    return s.substring(1); // output the constructed String, minus the leading newline
}

```
> 2 votes

# Answer
# Bash + GNU utilities, 38

```
dc -e?2op|sed 's/\B1/^K^H*/g;s/[10]/*/g'

```

Here `^K` and `^H` are literal vertical-tab and backspace control characters. These don't render well on browsers, so this script may be recreated as follows:

```
base64 -d <<< ZGMgLWU/Mm9wfHNlZCAncy9cQjEvCwgqL2c7cy9bMTBdLyovZyc= > binpath.sh

```

Run in a terminal. Input is via STDIN.

This answer may stretch the specifications too far - there are in fact no leading characters on each line of output - all positioning is done with control characters. If this is too much of a stretch, then the output may be piped to `|col -x|tac` for an extra 11 bytes.
> 2 votes

# Answer
## Batch, 113 bytes

```
@set s=
:l
@shift
@if %1.==0. set s=%s%+&goto l
@echo %s%+
@if not %s%.==. set s=%s:+= %
@if %1.==1. goto l

```

Takes a list of bits as command-line arguments. Uses `+` instead of `*` because `*` has a special meaning inside `%s:...=...%` expansions.
> 2 votes

# Answer
# Java (JDK 10), 83 bytes

```
a->{int m[][]=new int[20][20],r=0,i=0;for(int b:a)m[r+=i<1?0:b][i++-r]=1;return m;}

```

Try it online!

* Supports at most 20 bits.
* Input as `int[]`
* Output as `int[][]`
> 2 votes

# Answer
# Japt, ~~19~~ 17 bytes

```
Ë?R+Tî +Q:°T©QÃ¬x
Ë?                 // Map over the input and if the current value is 1:
  R+               // Return a new line and
    Tî +           // a space repeated T (with initial value 0) times and
        Q          // a \".
         :         // If the current value is 0:
          °T       // Increment T
            ©Q     // and return \".
              Ã    // When all of that is done,
               ¬   // turn the array into a string
                x  // and trim it, removing the excess new line at the start.

```

Takes input as an array of bits, for example `[1,0,1]`, outputs `"` instead of `*`.
Shaved two bytes off thanks to Oliver.

Try it online!
> 1 votes

# Answer
# Haskell, 126 bytes

```
(#)n=maximum.map(!!n)
f l|s<-scanl1(zipWith(+))$(\a->[1-a,a])<$>l=unlines[[last$' ':['#'|elem[x,y]s]|x<-[0..0#s]]|y<-[1..1#s]]

```

Input as a list of zeroes and ones. Transforms number into offset by `x↦[1-x,x]` and calculates the partial sums. Final output is done with two nested list comprehensions.

Try it online!
> 1 votes

# Answer
# APL+WIN, 65 or 46 bytes

Prompts for input of the integer

```
n←+/i←((1+⌊2⍟n)⍴2)⊤n←⎕⋄m←(n,n)⍴' '⋄m[⊂[2](+\i),[1.1]1++\~i]←'*'⋄m

```

or for numerical vector of the binary representation of the integer

```
m←(2⍴+/n←⎕)⍴' '⋄m[⊂[2](+\i),[1.1]1++\~i]←'*'⋄m

```

assuming I have read the comments to certain answers correctly and the latter input is allowed.
> 1 votes

# Answer
# , 59 bytes

```
function(n,x=sum(n|1))matrix(1:x^2%in%cumsum((n-1)%%x+1),x)

```

Try it online!

Takes input as an array of bits.

Returns a boolean matrix of `TRUE` and `FALSE` representing a `*` and a , respectively.

Also has some stuff in the footer to print a matrix corresponding to the specs above, for ease of testing.
> 1 votes

# Answer
# Pyth, 23 bytes

```
p\*VtQINp+b*Zd.?=hZ)p\*

```

Try it here

### Explanation

```
p\*VtQINp+b*Zd.?=hZ)p\*
p\*                       Print the leading *.
   VtQ                    For each bit (excluding the leading 1)...
      IN      .?   )      ... If the bit is set...
        p+b*Zd            ... Print a newline and a bunch of spaces...
                =hZ       ... Otherwise, increase the count of spaces...
                    p\*   ... Then print the next *.

```
> 1 votes

# Answer
# Perl 5 `-p`, ~~54~~ 36 bytes

```
s/./$&?"
".$"x$i.1:++$i&&1/ge;s/.//s

```

Try it online!

Cut it way down after I realized that the input could be a bit string.
> 1 votes

# Answer
# SmileBASIC, ~~64~~ ~~59~~ 57 bytes

```
INPUT N@L
GPSET X,Y
B=N<0X=X+B
Y=Y+(X>B)N=N<<1ON!N GOTO@L

```

The highest bit (sign bit) is checked, and if it's 1, the X position increases. If the sign bit is less than the X position (that is, the sign bit is 0 and X is not 0) the Y position increases.

The first movement will always be horizontally, so Y movement is blocked until after the first X movement. This ensures that the Y position doesn't increase during the leading 0 bits.

Then N is shifted left, and this repeats until N reaches 0.
> 1 votes

# Answer
# Ruby, 63 bytes

```
->n{s=""
n.to_s(2).gsub(/./){$&==?1?"
"+s+?*:(s+=" ";?*)}[1,n]}

```

Try it online!
> 1 votes

# Answer
# Python 2, 113 Bytes

```
def f(a):
 o='*';r=[o]
 for i in bin(a)[3:]:
  if'0'<i:r+=[' '*len(r[-1][1:])]
  r[-1]+=o
 print'\n'.join(r)

```

Not sure if this one counts (it outputs an array of each of the lines), but if so then I'll change my byte count to 103:

```
def f(a):
 o='*';r=[o]
 for i in bin(a)[3:]:
  if'0'<i:r+=[' '*len(r[-1][1:])]
  r[-1]+=o
 print r

```
> 1 votes

# Answer
# TI-Basic (TI-84 Plus CE), 85 bytes

```
Prompt L
1→X
1→Y
DelVar [A]
sum(<sub>L</sub>L
{Ans,1-Ans+dim(<sub>L</sub>L→dim([A]
1→[A](Y,X
For(I,2,dim(<sub>L</sub>L
Y+<sub>L</sub>L(I→Y
X+not(<sub>L</sub>L(I→X
1→[A](Y,X
End
[A]

```

Prompts for a boolean list, returns a matrix of 0 and 1.

Goes through the list, incrementing X if the next 'bit' is 0, changing Y otherwise, then adding a 1 to the matrix at that location, and returns the matrix at the end.

TI-Basic is a tokenized lanugage.

* 1 byte: `Prompt` , `L`\*6, (newline)\*12, `1`\*5, \*7, `X`\*5, `Y`\*5, `sum(`, `<sub>L</sub>`\*5, `{`, `Ans`\*2, `,`\*5, `-`, `+`\*3, `dim(`\*3, `(`\*4, `For(`, `I`\*3, `2`, `not(`, `End` = 73 bytes
* 2 bytes: `Delvar` , `[A]`\*5 = 12 bytes
* Total: 85 bytes

---

# TI-Basic (TI-84 Plus CE), 56 bytes

```
Prompt L
1→X
1→Y
Output(Y,X,"*
For(I,2,dim(<sub>L</sub>L
Y+<sub>L</sub>L(I→Y
X+not(<sub>L</sub>L(I→X
Output(Y,X,"*
End

```

Same processs as above, but using graphical output (limited by screen size: 10 rows, 26 columns, so max 10 1s and 25 0s) as it goes, instead of adding to a matrix.
> 1 votes

# Answer
## Pyth, 30 bytes

```
JZFG.BQIsGIJk)p+*ZdN.?pN=hZ)=J

```

Try it online!

Uses `"` instead of `*`.

Python 3 translation:
```
Q=eval(input())
Z=0
J=Z
for G in "{0:b}".format(Q):
    if int(G):
        if J:
            print()
        print(Z*' '+'"',end='')
    else:
        print('"',end='')
        Z+=1
    J=Q

```
> 1 votes

# Answer
# x86 .COM, 32 bytes

```
00h: 66 D1 E6 66 0F BD CE BF 24 AD 8E DF 41 66 0F A3
10h: CE 19 DB 81 E3 9E 00 8D 79 02 C6 05 2A E2 EE C3

fun:
shl esi, 1
bsr ecx, esi
mov di, $ad24
mov ds, di
inc cx
lab2:
bt esi, ecx
sbb bx,bx
and bx,158
lea di,[di+2+bx]
mov [di],byte '*'
lab1:loop lab2
ret

```
> 1 votes

# Answer
# APL (Dyalog Classic), 18 bytes

```
+⌿↑1↑¨⍨-+\,¨∘~⍨0,⎕

```

Try it online!
> 1 votes

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


title: Paths & Wasting Time

text:
# Question
Title: Paths & Wasting Time
## Premise

So recently I was about half an hour early to an appointment, and decided to wait outside. I also determined that it would look strange if I just stood motionlessly in front of the house. Therefore, I decided to go on a quick walk, within a limited area. I also concluded that if I started walking in circles that would make it obvious that I was loitering. So I was inspired to create my first Code Golf challenge.

## Specification

You will be given a list, a map of the area, which will contain either `" "` or `"#"`, which represent free spaces and obstacles of some sort. Free spaces can only be crossed once, and it takes 1 minute to cross it. Your initial position will be signified with a `"@"` per roguelike tradition, and the target will be represented with a `"$"` because that's what you're going to lose there. You will also be given an integer which will represent how many minutes you have to waste before not seeming as if you were intruding. When you land on the `"$"`, it will have to have been the exact amount minutes (so if you were counting down, it will have to be 1 on an adjacent tile, and be 0 on the tile). It will always be possible to reach the destination. Your program or function will have to return a list showing the shortest path with \<, \>, ^, and v to represent the four possible directions.

## Examples

**Input:**

```
[[" ", " ", " ", " "],
 ["@", " ", " ", "$"],
 [" ", " ", " ", " "],
 [" ", " ", " ", " "]]

```

and

```
5

```

**Ouput:**

```
[[">", ">", ">", "v"],
 ["^", " ", " ", "$"],
 [" ", " ", " ", " "],
 [" ", " ", " ", " "]]

```

**Input:**

```
[[" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 ["@", "#", " ", "$", " "],
 [" ", " ", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

```

and

```
7

```

**Output:**

```
[[" ", "#", " ", " ", " "],
 [" ", "#", ">", "v", " "],
 ["v", "#", "^", "$", " "],
 [">", ">", "^", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

```

**Input:**

```
[[" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 ["@", "#", " ", "$", " "],
 [" ", " ", " ", " ", " "],
 [" ", "#", " ", " ", " "],
 [" ", "#", " ", " ", " "]]

```

and

```
17

```

**Output:**

```
[[" ", "#", " ", "v", "<"],
 [" ", "#", " ", "v", "^"],
 ["v", "#", " ", "$", "^"],
 [">", ">", "v", ">", "^"],
 [" ", "#", "v", "^", "<"],
 [" ", "#", ">", ">", "^"]]

```

## Rules

* Standard loopholes apply
* Each tile must only be moved over once
* The exact amount of time must be spent on the board
* Only one path needs to be displayed in the case of multiple paths
* This is a code golfing question so shortest answer wins
* As per user202729's question in the comments, you may assume valid input.

Add a comment if any further clarification is required

# Answer
> 6 votes
# JavaScript (ES6), 171 bytes

Takes input in currying syntax `(a)(n)`. Outputs by modifying the input matrix.

```
a=>g=(n,y=a[F='findIndex'](r=>~(i=r[F](v=>v>'?'))),x=i,R=a[y])=>!n--|[-1,0,1,2].every(d=>(R[x]='<^>v'[d+1],(c=(a[Y=y+~-d%2]||0)[X=x+d%2])<1?g(n,Y,X):n|c!='$')&&(R[x]=' '))

```

Try it online!

### Commented

```
a =>                           // a[] = input matrix
g = (                          // g = recursive function taking:
  n,                           //   n = number of remaining moves
                               //   (x, y) = current coordinates, initialized as follows:
  y = a[F = 'findIndex'](r =>  //     y = index of the row containing the starting point,
    ~(i = r[F](v => v > '?'))  //         found by iterating over all rows r until we
  ),                           //         find some i such that r[i] > '?'
  x = i,                       //     x = index of the column of the starting point
  R = a[y]                     //   R[] = current row
) =>                           //
  !n-- |                       // decrement n; force failure if we're out of moves
  [-1, 0, 1, 2].every(d =>     // for each direction d, where -1 = left, 0 = up,
    (                          // 1 = right and 2 = down:
      R[x] = '<^>v'[d + 1], (  //   update the current cell with the direction symbol
        c = (                  //   c = content of the new cell at (X, Y) with:
          a[Y = y + ~-d % 2]   //     Y = y + dy
          || 0                 //     (use a dummy value if this row does not exist)
        )[X = x + d % 2]       //     X = x + dx
      ) < 1 ?                  //   if c is a space:
        g(n, Y, X)             //     we can go on with a recursive call
      :                        //   else:
        n | c != '$'           //     return false if n = 0 and we've reached the target
    ) &&                       //   unless the above result is falsy,
    (R[x] = ' ')               //   restore the current cell to a space
  )                            // end of every()

```

# Answer
> 5 votes
# Python 2, ~~310~~ 256 bytes

Thanks @cairdcoinheringaahing for `except:0` -3 bytes
Thanks @Mnemonic for -8 bytes
Thanks @JonathanAllan for -3 bytes
Thanks @ovs for -5 bytes

```
G,L=input()
R=[]
def S(x,y,G,c,R):
 try:
	if x>-1<y<G[y][x]in' @':i=0;exec"T=[r[:]for r in G];T[y][x]='<v^>'[i];S(x+~-i/2,y+~-(i^2)/2,T,c-1,R);i+=1;"*4
	R+=[G]*(0==c<'$'==G[y][x])
 except:0
for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)
print R[0]

```

Try it online!

Some explanation:

`try-except` is used to ensure, that both `x` and `y` coordinates are in boundaries. Exception will be raised upon access to `G[y][x]`. Python is too good and negative indices are acceptable, so check `x>-1<y` is added.

`T=[r[:]for r in G]` used to create copy of `G` by values

`~-i/2` and `~-(i^2)/2` are used to generate pairs `(-1, 0), (0, 1), (0, -1), (1, 0)`, that used to move in grid *(there still should be shorter way!)*

`R+=[G]*(0==c<'$'==G[y][x])` check, that `'$'` is reached in required number of steps. `R` is used to get this result from recursive function calls.

`for i,y in enumerate(G):"@"in y>S(y.index("@"),i,G,L,R)` Found `x` and `y` of `'@'` in input and call function `S`.

`print R[0]` `R` might contain more that one solution, so output just first

# Answer
> 2 votes
# Python 2, ~~264~~ ~~261~~ ~~251~~ 249 bytes

```
def f(a,n,r=-1,s=0):
 j=len(a[0]);x=1;z=y=0
 if r<0:s,r=divmod(sum(a,[]).index('@'),j)
 for c in'>v<^':
	u=r+x;v=s+y;x,y=-y,x
	if j>u>-1<v<len(a):b=[e[:]for e in a];b[s][r]=c;w=a[v][u];z=n*(w<'!')and f(b,n-1,u,v)or n==1and w=='$'and b
	if z:return z

```

Try it online!

---
Tags: code-golf, path-finding
---


title: Craptastic Program Search

text:
# Question
Title: Craptastic Program Search
A certain well-known cable company has a somewhat clumsy 'Search for Program' feature that works through the remote. It takes muchly much button pushing; so, being an admirer of economy of motion, I thought I'd seek out a programmer's help to minimize the number of finger movements I have to make.

The Craptastic Search Feature features a layout of selectable cells, 1 row of 3 cells followed by 6 rows of 6 cells, that looks like this:

```
del spa sav
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 0 1 2 3
4 5 6 7 8 9

```

There are cells for each of the letters `A-Z`, and `spa` which is used to add a space to the search string. `del` is supposed to be used to delete a character; and `sav` is meant to be used to save the search string. We'll ignore these actual functions for this challenge; but the cells are otherwise still selectable for our purposes.

We start with an empty search string and the `A` cell selected; and we use left, right, up and down arrow buttons to change the selected cell. When the central 'OK' key is pushed, the character in the selected cell is added to the search string. For convenience, we'll use `<`,`>`,`^`,`v` and `_` for left,right,up,down and OK, respectively.

For the letters and numbers, the action of the directional buttons is straightforward. There is no 'wrap-around'; for example, if the current cell is `G`, then `<` has no effect.

So to enter the search string `BIG`, we could use the sequence

`>_>v_<<_`

(the initial `>` is required to move us from the default starting cell `A` to the cell `B`). Alternatively, we could of course instead use `>_v>_<<_`; but note there is no *shorter* sequence than 8 keys that can do the job.

Now since the top row has only three cells, the action there is slightly different and complicates things a little:

First, if the selected cell is in the top letter row `A-F`, the `^` key moves the selected cell directly above; so `A,B` go to `del`, `C,D` go to `spa` and `E,F` go to `sav`.

One the other hand, if the selected cell is 'del', the `v` key moves the selected cell to `A`, and the `>` key makes the selected cell `spa`. Similarly `v` key moves the selected cell from `spa` to `C`, and `sav` to `E`.

This means that for example, if you are currently at the `B` cell, the sequence `^v` does not return you to the `B` cell; instead it takes you to the `A` cell.

And starting at the `A` cell, the sequence `v>>^`moves us to the `C` cell; while the sequence `^>>v` moves us to the the `E` cell.

## The Challenge

Given a TV show or movie title `s`, consisting solely of characters in `A-Z`, `0-9` and `space`, your program/function should output one of the sequences of keypresses of minimal length to enter `s` as the search string from the starting state in Craptastic fashion.

Your output should be a string or a list of distinct values representing a sequence of up, down, right, left, and OK; so you are not restricted to the charset `<>^v_` (e.g., `udrl*` or a list with integer elements 0,1,2,3,4 would be acceptable alternatives, so long as you articulate what your schema is).

This is ; the usual loophole taboos apply. May the odds be ever in your favor for each language.

## Test Cases

Below are inputs and an example acceptable answer (other different sequences will be correct as well, but must be of at most the length of the examples provided).

*(I re-post the keypad here so one can more easily play along visually, if that is one's wont...)*

```
del spa sav
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 0 1 2 3
4 5 6 7 8 9

BIG         >_>v_<<_
THE OFFICE  >vvv_^^_>>>^_^<_vvv_>>>^^__<<<v_^_>>_
FARGO       ^>>v>_^<<v_^>>v>vv_<<<<<^_>>v_
BUFFY       >_>vvv_>>>^^^__^<<vvvvv_
DALLAS      >>>_<<<_^>>v>v__^^<<v_vvv_
THX1138     >vvv_^^_>>>>vv_<<v__>>_<v_
ON DEMAND   >>vv_<_^^^>_v>_>_<<<<vv_^^_>vv_>>^^_
NEWS RADIO  >vv_>>>^^_vvv_<<<<_^^^^>_>vvv>_^^^<<v_>>>_<v_v_
ROOM 909    ^>>v>vv_<<<__<<_^^^>_>vvvvvv>_<<<^_>>>v_

```

# Answer
# JavaScript (ES6), 196 bytes

Golfing this code below 200 bytes was basically a nightmare (but it was fun). I'm really looking forward a simpler and shorter implementation.

```
f=(s,p=(i=0,6),x=(p-=p&(p<6))%6,X=(P=(parseInt(c=s[i],36)+26)%36+6||2)%6)=>c?'^<>v_'[(d=p-P?p<6?x<(X&6)?40:X-1&&x^X&6?20:60:P<6+(x>4)|p==11&!X?0:x<X?39:x>X?21:p<P&&60:++i&&70)>>4]+f(s,p+d%16-6):''

```

Try it online!

## How?

### Variables

* **s** is the input string
* **i** is a pointer in **s**, initialized to **0**
* **c** is the next target character (aka **s\[ i \]**)
* **p** is the current position on the keypad according to the following mapping and initialized to **6** (the **"A"** key)

```
del spa sav      00 -- 02 -- 04 --
A B C D E F      06 07 08 09 10 11
G H I J K L      12 13 14 15 16 17
M N O P Q R  ->  18 19 20 21 22 23
S T U V W X      24 25 26 27 28 29
Y Z 0 1 2 3      30 31 32 33 34 35
4 5 6 7 8 9      36 37 38 39 40 41

```
* **P** is the position of the target character **c**
* **x** is the column of the current character (**p % 6**)
* **X** is the column of the target character (**P % 6**)

### Move encoding

There are 7 possible moves. We encode each of them as a 7-bit integer. The 4 least significant bits hold the displacement value **V + 6** and the 3 most significant bits hold the symbol ID **S**.

```
move                       | symbol | S |  V | V + 6 | S << 4 | (V + 6)
---------------------------+--------+---+----+-------+-----------------
one position to the left   |   <    | 1 | -1 |   5   |       21
two positions to the left  |   <    | 1 | -2 |   4   |       20
one position to the right  |   >    | 2 |  1 |   7   |       39
two positions to the right |   >    | 2 |  2 |   8   |       40
upwards                    |   ^    | 0 | -6 |   0   |        0
downwards                  |   v    | 3 |  6 |  12   |       60
don't move (press the key) |   _    | 4 |  0 |   6   |       70

```

### Alignment with function keys

At the beginning of each iteration, we execute the following code to make sure that **p** is aligned with the current function key if we're located in the first row:

```
p -= p & (p < 6)

```

### Move logic

The move is chosen with a (too) long chain of ternary operators which is detailed below.

```
p - P ?               // if we're not yet located over the target character:
  p < 6 ?             //   if we're currently located in the first row:
    x < (X & 6) ?     //     if x is less than the column of the function key holding the target character:
      40              //       move 2 positions to the right
    :                 //     else:
      X - 1 &&        //       if the target character is not located in the 2nd column
      x ^ X & 6 ?     //       and x is not equal to the column of the function key holding the target character:
        20            //         move two positions to the left
      :               //       else:
        60            //         move downwards
  :                   //   else:
    P < 6             //     if the target key is space (P is either greater than 5 or equal to 2)
          + (x > 4) | //     or the target key is A and we're currently in the rightmost column
    p == 11 & !X ?    //     or we're currently over F and the target key is in the leftmost column:
      0               //       move upwards
    :                 //     else, this is a standard move:
      x < X ?         //       if x is less than X:
        39            //         move one position to the right
      :               //       else:
        x > X ?       //         if x is greater than X:
          21          //           move one position to the left
        :             //         else:
          p < P && 60 //           move either upwards or downwards
:                     // else:
  ++i && 70           //   don't move and advance the pointer in s

```
> 4 votes

# Answer
# Python 2, ~~294~~ ~~293~~ 289 bytes

```
r='';l=[(ord(c)-59)%43-14*(c<'0')for c in input()]
for a,b in zip([6]+l,l):x,y,X,Y=a%6,a/6,b%6,b/6;A=(a<6)*(X!=1);x=[x,X/2*2][A];r+='< >'[X/2]*A+('^'*y+['<<'+'v'*Y,'> <'[x/2]][b<6]if(b,x)in[(6,5),(2,x)]or(a,X)==(11,0)else('^v'[Y>y]*abs(y-Y)+'<>'[X>x]*abs(x-X)))+'_'
print r.replace(' ','')

```

Try it online!
> 3 votes

# Answer
# JavaScript, 311 bytes

```
f=n=>(parseInt(n,36)+26)%36+1||'S'
g=n=>(t=+n)?[t-(t%6!=1),t%6?t+1:t,t>30?t:t+6,t<7?' DDSSVV'[t]:t-6]:{D:'DS1',S:'DV3',V:'SV5'}[n]||[]
h=(p,q,t={[p]:''})=>([...g(p)].map((n,i)=>n in t&&t[n].length<t[p].length+1||h(n,q,t,t[n]=t[p]+'<>v^'[i])),t[q])
F=s=>[...s].map(f).map((c,i,a)=>h(a[i-1]||1,c)+'_').join``
```

```
<input id=i oninput=o.value=F(i.value)><br><output id=o>
```

Not sure how to golf this...

* `f`: convert 'A-Z0-9' to 1-36, space to "S"
* `g`: get 4 sibling of given key
* `h`: find shortest path from p to q
* `F`: the answer
> 1 votes

---
Tags: code-golf
---


title: Binning in time

text:
# Question
Title: Binning in time
The task in this challenge is to put elements of an array into time bins. The input will be a non-decreasing array of positive integers representing the time of events, and an integer which represents the size of each bin. Let us start with an example. We call the input array `A` and the output array `O`.

```
`A = [1,1,1,2,7,10]` and `bin_size = 2`.

`O = [4,0,0,1,1]`.

```

**Why**? With a `bin_size = 2`, we'll have the following intervals: `(0,2], (2,4], (4,6], (6,8], (8,10]`, where four items `(1,1,1,2)` are within the first interval `(0,2]`, none in the second and third intervals, one `7` in the interval `(6,8]`, and one `10` in the interval `(8,10]`.

Your code should consider every interval of length `bin_size` starting from `0` and count how many numbers in `A` there are in each. You should always include the right hand end of an interval in a bin so in the example above `2` is included in the count of `4`. Your code should run in linear time in the sum of the lengths of the input and output.

More examples:

```
`A = [1,2,7,12,15]`  and `bin_size = 5`.

`O = [2, 1, 2]`.

`A = [1,2,7,12,15]`  and `bin_size = 3`.

`O = [2,0,1,1,1]`.

```

You can assume that input and output can be given in any format you find convenient. You can use any languages and libraries you like.

# Answer
# , 48 bytes

```
function(n,s)table(cut(n,0:ceiling(max(n)/s)*s))

```

Try it online!

Once again, `table` and `cut`ting to a `factor` do the trick for the binning. Outputs a named `vector` where the `names` are the intervals, in interval notation, for instance, `(0,5]`.

EDIT: Revert back to earlier version that works when `s` doesn't divide `n`.
> 9 votes

# Answer
# Octave, 36 bytes

```
@(A,b)histc(A,1:b:A(end)+b)(1:end-1)

```

Try it online!

Out hunting Easter eggs and making a bonfire. I'll add an explanation when I have the time.
> 6 votes

# Answer
# Python 2, 62 bytes

```
I,s=input()
B=[0]*(~-I[-1]/s+1)
for i in I:B[~-i/s]+=1
print B

```

Try it online!
> 3 votes

# Answer
# Perl 5 `-a` `-i`, ~~32~~ 28 bytes

Give count after the -i option. Give each input element on a separate line on STDIN

```
$G[~-$_/$^I]--}{say-$_ for@G

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 18 bytes

```
θs/Å0¹vDyI/î<©è>®ǝ

```

Try it online!
> 3 votes

# Answer
# APL+WIN, 23 bytes

Prompts for screen input of bins then vector of integers:

```
+⌿<\v∘.≤b×⍳⌈⌈/(v←⎕)÷b←⎕

```

Explanation:

```
⎕ Prompt for input

⌈⌈/(v←⎕)÷b←⎕ divide the integers by bin size, take maximum and round up for number of bins

b×⍳ take number of bins from previous step and create a vector of bin upper boundaries

v∘.≤ apply outer product to generate boolean matrix where elements of vector ≤ boundaries

<\ switch off all 1's after first 1 in each row to filter multiple bin allocations

+⌿ sum columns for the result

```
> 2 votes

# Answer
# Java 8, 75 bytes

```
a->b->{var r=new int[~-a[a.length-1]/b+1];for(int i:a)r[~-i/b]++;return r;}

```

Port of @DeadPossum's Python 2 answer, so make sure to upvote his answer!

**Explanation:**

Try it online.

```
a->b->{          // Method with integer-array and integer parameters and no return-type
  var r=new int[~-a[a.length-1]/b+1];
                 //  Result integer-array of size `((last_item-1)/bin_length)+1`
  for(int i:a)   //  Loop over the input-array
    r[~-i/b]++;  //   Increase the value at index `(i+1)/bin_length` by 1
  return r;}     //  Return the result-array

```
> 2 votes

# Answer
# C++ (gcc), ~~90~~ 83 bytes

```
auto f(auto i,int s){typeof i j;for(auto v:i)--v/=s,j.resize(v+1),j[v]++;return j;}

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 60 bytes / O(len(a)+max(a)/n)

*Saved 5 bytes thanks to @Neil*

Takes input in currying syntax `(a)(n)`.

```
a=>n=>[...a.map(x=>o[x=~-x/n|0]=-~o[x],o=[])&&o].map(n=>~~n)

```

Try it online!

Or just **43 bytes / O(len(a))** if empty elements are allowed.
> 2 votes

# Answer
# Ruby, 60 bytes

```
->a,b{(b...a[-1]+b).step(b).map{|i|a.count{|n|n<=i&&n>i-b}}}

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~63~~ ~~75~~ 70 bytes

```
l!n=l#[n,2*n..]
[]#_=[]
l#(b:i)|h<-length$takeWhile(<=b)l=h:drop h l#i

```

Whoops, this shorter one isn't linear but quadratic;

```
l!n=l#[n,2*n..]
[]#_=[]
l#(b:i)=sum[1|a<-l,a<=b]:[a|a<-l,a>b]#i

```

Try it online!
> 2 votes

# Answer
# C (gcc), ~~102~~ ~~90~~ ~~89~~ 86 bytes

```
#define P!printf("%d ",k)
i,j,k;f(s){for(i=s;~scanf("%d",&j);k++)for(;j>i;i+=s)k=P;P;}

```

Try it online!

Thanks to Kevin Cruijssen for slashing off 12 bytes, and ceilingcat for another 4 bytes!
> 1 votes

# Answer
# Pyth, ~~23~~ 22 bytes

```
Jm/tdeQhQK*]ZheJhXRK1J

```

Try it here

```
Jm/tdeQhQK*]ZheJhXRK1J
Jm/tdeQhQ                 Find the bin for each time and save them as J.
         K*]ZheJ          Create empty bins.
                 XRK1J    Increment the bins for each time within them.
                h         Take the first (because mapping returned copies).

```
> 1 votes

# Answer
# Ruby, ~~53~~ 50 bytes

Edit: -3 bytes by iamnotmaynard.

```
->a,b{(0..~-a.max/b).map{|i|a.count{|x|~-x/b==i}}}

```

Try it online!
> 1 votes

# Answer
This puzzle is essentially a Count-sort. We don't know the length of output without going through input first.

# C (clang), 53 bytes

```
i,j;f(*A,l,b,*O){for(j=0;j<l;O[(A[j++]+b-1)/b-1]++);}

```

Try it online!

This solution takes following parameters:
`A` input array
`l` length of A
`b` bin\_size
`O` storage for Output. Must be sufficient length
and returns output in O.

This solution has a handicap: it doesn't return the length of output array O, and so caller doesn't know how much to print.

Following version overcomes that handicap:

# C (clang), 79 bytes

```
i,j,k;f(*A,l,b,*O,*m){for(k=j=0;j<l;O[i=(A[j++]+b-1)/b-1]++,k=k>i?k:i);*m=++k;}

```

Try it online!

It takes an additional parameter `m` and returns length of `O` in it. It cost me 26 bytes.
> 1 votes

---
Tags: code-golf, restricted-complexity
---


title: The Lonely Islands

text:
# Question
Title: The Lonely Islands
### Input:

A 2D array containing two distinct (optional) values. I'll use **0** and **1** when explaining the rules. The input format is of course flexible.

---

### Challenge:

Zeros are water, and ones are islands. In order to ensure loneliness, your task is to surround all islands with water by inserting rows and columns of zeros. **You don't want to waste water, so you must minimize the amount of water added. In case there are more than one solution that requires the same amount of water added, then you should add columns of water, not rows.** I'll show this in the test cases.

---

### Output:

The new, modified 2D array. The output format is of course flexible.

---

### Test cases:

Input and output are separated by dashes. Added zeros are shown in bold font. Use one of the answers here if you want to convert the test cases to more convenient formats.

```
1
---
1
```

---

```
1 1
---
1 **0** 1
```

---

```
1 1
1 1
---
1 **0** 1
**0** **0** **0**
1 **0** 1
```

---

```
1 0
0 1
---
1 **0** 0
0 **0** 1
```

Note that we added a column of zeros, not a row of zeros. This is because the number of necessary zeros is equal, and columns should be preferred.

---

```
1 0 0 0 1
0 1 0 1 0
0 0 1 0 0
0 1 0 1 0
---
1 0 0 0 1
**0** **0** **0** **0** **0**
0 1 0 1 0
**0** **0** **0** **0** **0**
0 0 1 0 0
**0** **0** **0** **0** **0**
0 1 0 1 0
```

Note that we added rows, not columns, since that requires the least amount of extra zeros.

---

```
0 0 1 0 0
0 1 1 1 0
---
0 0 **0** 1 **0** 0 0
**0** **0** **0** **0** **0** **0** **0**
0 1 **0** 1 **0** 1 0
```

This required both columns and a row.

---

```
0 0 1 0 0
0 1 0 1 0
---
0 0 **0** 1 **0** 0 0
0 1 **0** 0 **0** 1 0
```

Better to add two columns than one row, since it requires less water.

---

```
0 0
1 0
0 1
1 0
0 0
---
0 0
1 0
**0** **0**
0 1
**0** **0**
1 0
0 0
```

Better to add two rows than one column, since it requires less water.

# Answer
# Jelly, 37 bytes

```
ṫƤ-S€ZƊ⁺FỊẠ
Z_,,WƲ€ŒpẎ€Ʋ⁺€ẎLÞFL$ÞṚÇÞṪ

```

Try it online!

Function returning a 2D array of integers. Note that naturally in Jelly singleton list displays as its value so `G` is used to format the output.

---

* Link 1: Return (validity).
* Link 2: Main program.

---

The program runs in exponential time, but so-far I could not think of any polynomial time algorithm. Uses `Ƥ` on dyadic function, that feature postdates the challenge.
> 3 votes

# Answer
# Python 2, ~~374~~ ~~346~~ ~~340~~ ~~339~~ ~~323~~ 317 bytes

```
R=range;L=len
def f(a):
 w,h=L(a[0]),L(a);W=[]
 for i in R(2**w):
	A=zip(*a)
	for c in R(w):A[-c:-c]=[[0]*h]*(i&1<<c>0)
	for j in R(2**h):
	 B=zip(*A);x=L(B[0])
	 for r in R(h):B[-r:-r]=[(0,)*x]*(j&1<<r>0)
	 y=L(B);W+=[(w*h-x*y,x,B)]*all(sum(B[i][j:j+2]+B[i+1][j:j+2])<2for i in R(y-1)for j in R(x))
 return max(W)[2]

```

Try it online!
> 2 votes

---
Tags: code-golf, array, matrix, binary-matrix
---


title: Digit Occurrences

text:
# Question
Title: Digit Occurrences
## Input:

A list of integers (which will never contain a zero)

## Output:

A list of the same size with counts based on the following:

* If the current item is negative: Look at all items before this item, and count how many times the digits occurred in those other numbers
* If the current item is positive instead: Look at all items after this item, and count how many times the digit occurred in those other numbers

There is one twist: If the size of the list is even we only count every number once (even if it matches multiple digits), and if the size is odd we count every digit of the numbers for each digit of the current item (duplicated digits are counted multiple times).

Let's give some examples to clarify this a bit:

**Example with even list:**

```
Input:  [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2,  4,  1,   2,    1,    1,   5   ]

```

Size of the list is **even**, so we only count each number once.

* `4`: It's positive, so we look forward. There are three numbers containing the digit `4` (`42`, `-942`, `8374`). So we start with a `3`.
* `10`: It's positive, so we look forward. There are two numbers containing either the digit `1` and/or `0` (`-10`, `-200`). So the second output is `2`.
* `42`: Again positive, so forward. There are four numbers containing either the digit `4` and/or `2` (`-942`, `8374`, `728`, `-200`). So the third output is `4`.
* `-10`: This time it's negative, so we look backwards. There is only one number containing the digit `1` and/or `0` (we ignore the minus sign) (`10`). So the fourth output is `1`.
* etc.

**Example with odd list:**

```
Input:  [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13,  2,   2,  4,   8,   3,  0,   11,  6 ]

```

Size of the list is **odd**, so we count every digit.

* `382`: It's positive, so we look forward. There is one `3` in the other numbers (`381`), six `8`'s in the other numbers (`-82, -8, 381, 228, 28, -28`), and six `2`'s in the other numbers (`-82, 228, 28, -28, 2`). So we start with a `13`.
* `-82`: It's negative, so backwards. There is one `3` in the other number (`382`), and one `8` in the other number (`382`). So the second output is `2`.
* ...
* `228`: It's positive, so forward. There are three `2`'s in the other numbers (`28`, `-28`, `-2`), and another three `2`'s, and two `8`'s in the other numbers (`28`, `-28`). So this output is `8`.
* etc.

## Challenge rules:

* You can assume the input will never contain `0` as item, since it's neither positive nor negative.
* You can assume the input-list will always contain at least two items.
* I/O is flexible. Input/output can be array/list of integers, delimited string, digit/character-matrix, etc.
* If the first number in the list is a negative number, or the last number in the list is a positive number, it will be 0 in the resulting list.
* With odd lists, numbers containing the same digit multiple times are counted multiple times, like the `228` in the odd example above resulting in `8` (3+3+2) instead of `5` (3+2).

## 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, 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.
* Also, please add an explanation if necessary.

## Test cases:

```
Input:  [4, 10, 42, -10, -942, 8374, 728, -200]
Output: [3, 2,  4,  1,   2,    1,    1,   5   ]

Input:  [382, -82, -8, 381, 228, 28, 100, -28, -2]
Output: [13,  2,   2,  4,   8,   3,  0,   11,  6 ]

Input:  [10, -11, 12, -13, 14, -15, 16, -17, 18, -19]
Output: [9,  1,   7,  3,   5,  5,   3,  7,   1,  9  ]

Input:  [10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20]
Output: [11, 2,   8,  4,   5,  6,   3,  8,   1,  10,  0 ]

Input:  [88, 492, -938, 2747, 828, 84710, -29, -90, -37791]
Output: [8,  9,   3,    9,    3,   4,     5,   4,   12    ]

Input:  [-1, 11, 11, 1]
Output: [0,  2,  1,  0]

Input:  [1, 11, 11, -1]
Output: [3, 2,  1,  3 ]

Input:  [-1, 11, 1]
Output: [0,  2,  0]

Input:  [1, 11, -1]
Output: [3, 2,  3 ]

```

# Answer
# 05AB1E, 30 bytes

```
vy0›iNƒ¦}ëN£}€Sþyδ¢IgÈiĀ€Ù}OOˆ

```

Try it online!
> 3 votes

# Answer
# Python 2, ~~149~~ ~~148~~ ~~121~~ ~~116~~ ~~111~~ 107 bytes

```
lambda l:[sum([any,sum][len(l)%2](map(`n`.count,`abs(v)`))for n in l[:i:2*(v<0)-1])for i,v in enumerate(l)]

```

Try it online!
> 5 votes

# Answer
# Java (JDK 10), 204 bytes

```
a->{int l=a.length,r[]=new int[l],i=0,j,x,y,b,s,t=10;for(;i<l;i++)for(j=i+(s=a[i]>0?1:-1);0<=j&j<l;j+=s)for(b=0,x=a[i];x!=0;x/=t)for(y=a[j];b<1&y!=0;y/=t)if(x%t==-y%t|x%t==y%t){r[i]++;b+=1-l%2;}return r;}

```

Try it online!

# Credits
> 4 votes

# Answer
# Perl 6, ~~100~~ 85 bytes

```
{.kv.map:{sum map (?*,+*)[$_%2],.[grep (*-$^i)*$^v>0,^$_].map:{.comb⊍$v.abs.comb}}}

```

Try it online!

Uses the baggy multiplication operator ⊍.
> 3 votes

# Answer
# Perl 5 `-n`, 92 bytes

```
($t=$&>0?$':$`)&say$q=y/ //%2?@a=$t=~/\b\d*[$&]+\d*\b/g:map$t=~/$_/g,$&=~/\d/g while/-?\d+/g

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js),164,158,140 139 bytes

```
a=>a.map((x,i)=>a.slice(x<0?0:i+1,x<0?i:l).map(b=>c+=[...b+""].map(X=>s+=X>=0&&(x+"").split(X).length-1,s=0)&&l%2?s:+!!s,c=0)|c,l=a.length)

```

Try it online!
> 1 votes

# Answer
# Jelly, ~~43~~ 42 bytes

```
>0ị"ḊÐƤżṖƤƊAṾ€€FċÐ€¥e€€³LḂ©¤?"AṾ$€SṀ€S$®?€

```

Try it online!
> 1 votes

# Answer
# Ruby, 126 bytes

```
->l{k=l.map{|i|i.abs.digits};c=-1;k.map{|n|x=k[l[c+=1]<0?0...c:c+1..-1];x.sum{|j|x=n.sum{|d|j.count d};l.size%2<1?x<1?0:1:x}}}

```

Try it online!
> 1 votes

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


title: Intron Adder Quine

text:
# Question
Title: Intron Adder Quine
In the context of quines, an intron (or payload) is a part of a quine that serves no purpose in producing output, but is still included in the data section. For example:

```
function quine() {
    const data = "function quine() {\n    const data=\"@\";\n    // Arr! This be an intron!\n    return data.replace(\"@\", JSON.stringify(data));\n}";
    // Arr! This be an intron!
    return data.replace("@", JSON.stringify(data));
}

```

My challenge is to write a quine that will *normally* run as a standard quine, but if an argument is passed in, then it returns a new quine with the argument placed somewhere in it. If that new quine is called with an argument, it should do the same. For example:

```
function quine(intron="") {
    const data = "function quine(intron=\"\0\") {\n    const data = \"%%%\";\n    //\0\n    return data.replace(/\u0000/g, intron).replace(\"%%%\", JSON.stringify(data));\n}";
    //
    return data.replace(/\u0000/g, intron).replace("%%%", JSON.stringify(data));
}

```

A few statements:

* If you have no input, then the output should be identical to the source code. If you *have* input, then the output only needs to:
    + Be in the same language
    + Contain the input
    + Be a solution to this challenge in its own right
* Quines only need to contain the latest intron. Introns from the program that generated it are optional.
* If your program already contains the input, then the same program is fine. For example, if it's called with the same input twice.
* The input can be assumed to be printable ASCII only.
* The shortest program in bytes wins.

# Answer
> 1 votes
# , 11 bytes

```
ñéÑvu"qpx:"

```

Try it online!

Hexdump:

```
00000000: f1e9 d176 7522 7170 783a 22              ...vu"qpx:"

```

This is a simple modification of the standard V quine. Given the input:

```
Hello

```

this program will output:

```
ñéÑvu"qpx:"Hello

```

Which outputs:

```
ñéÑvu"qpx:"Hello

```

This works because the input is automatically appended to the end of `ñéÑvu"qpx`, and `:"` is a comment (essentially)

# Answer
> 2 votes
# Python 2, 70 bytes

```
def f(x=''):s='def f(x=%r):s=%r;print s%%(x,s,x)#%s';print s%(x,s,x)#

```

Try it online!

A weird extension of the usual python quine `s="s=%r;print s%%s";print s%s`. This adds an extra `%s` after a comment, to output the data, and a `%r` in the default string to push the original string as default instead of an empty string.

# Answer
> 1 votes
# Python 3, 77 bytes

```
t='';s='t=input()or t;print(f"t={repr(t)};s={repr(s)};exec(s)#{t}")';exec(s)#

```

Try it online!

Full programs. Input must be terminated with a newline, and output a trailing newline.

Equivalent Python 2 would be 76 bytes (I think).

---
Tags: code-golf, quine
---


title: The house that Jack built

text:
# Question
Title: The house that Jack built
So, there's a famous children's rhyme...

```
This is the house that Jack built.

This is the malt
That lay in the house that Jack built.

This is the rat
That ate the malt
That lay in the house that Jack built.

This is the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the cow with the crumpled horn
That tossed the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog that worried the cat
That killed the rat that ate the malt
That lay in the house that Jack built.

This is the man all tattered and torn
That kissed the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog that worried the cat
That killed the rat that ate the malt
That lay in the house that Jack built.

This is the judge all shaven and shorn
That married the man all tattered and torn
That kissed the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the rooster that crowed in the morn
That woke the judge all shaven and shorn
That married the man all tattered and torn
That kissed the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the farmer sowing his corn
That kept the rooster that crowed in the morn
That woke the judge all shaven and shorn
That married the man all tattered and torn
That kissed the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

This is the horse and the hound and the horn
That belonged to the farmer sowing his corn
That kept the rooster that crowed in the morn
That woke the judge all shaven and shorn
That married the man all tattered and torn
That kissed the maiden all forlorn
That milked the cow with the crumpled horn
That tossed the dog
That worried the cat
That killed the rat
That ate the malt
That lay in the house that Jack built.

```

Obviously, it's pretty process-based, you could totally write code for this, right?

---

* Write some code which outputs the full text of "The house that Jack built".
* Standard rules and loopholes and stuff.
* Any language you like.
* Try to do it in the smallest number of bytes.
* I always like to see TIO links.
* The case must match the rhyme.
* Each line of the rhyme must be on a new line of text.
* White-space before and after the line is fine.
* No punctuation, except the full stop at the end of each verse.

---

Edit:

Earlier versions of this question contained an issue with this line

This is the rooster that crowed the morn

It was inconsistently applied.

To be clear; this should be one line on every occurrence, and should be added at once.

---

Further edit:

It's been declared that this question is a duplicate of:

We're no strangers to code golf, you know the rules, and so do I

However, while you could take the same approach, compressing the text as much as possible. There's also a chance to take a procedural approach to this rhyme, following the structure of the rhyme itself. Some of the solutions take this approach, so I'd say it is a similar, but distinct challenge for this reason.

This answer suggests that it's actually better to take the approach to this question which would not work for Rick Astley.

It is, however, a duplicate of the old lady song, and the 12 days of Christmas. I've voted to close it. (although, those two were not declared duplicate of each other).

# Answer
# JavaScript (ES6), 356 bytes

Procedural approach.

```
_=>`house th5 Jack built.
|malt6lay in|r565e|c56kill2dog6worri2cow with0crumpled h16toss2maiden3forl16milk2man3t5tered4 t16kiss2judge3shaven4 sh16marri2rooster6crowed in0m16woke|farmer sowing his c16kept|horse40hound40h16belonged to`.replace(/\d/g,n=>` the ,orn,ed|, all , and,at,
That `.split`,`[n]).split`|`.map(s=>`This is`+(p=' the '+s+p),p='').join`
`

```

Try it online!

---

# Simple compression, 429 bytes

Using RegPack.

```
_=>[...'IKLMNOPQRSUVWXYZ[]^_0qxz{}~'].reduce((s,c)=>(l=s.split(c)).join(l.pop()),`TNis_ZOlt }{rQ z^}{cQ Sz^ }KM}]M}xI[I~Z0ZYZLrseULundU{hWbelongV toY~{judgeRshavenU shWmarriV[MP}PZ{ the z
ThQ xOidenRforlWmilkV]qworriV{cQS 0{rooster XcrowV in{mWwoke~_Luse XJack built.^QeOlt]{cow with{crumplV hWtossVK[OnRtQterVU tWkissVxZ

TNisY{farmer sowing NcWkept0XthQ WornzVedU andSzkillV{rQR all QatPzlay in_O{maNhis Mzqz^L{hoK{dog IXqX^}`)

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~398~~ 397 bytes

```
for i in range(12):print'\nThis is the',''.join(dict(zip('012345','\nThat , the ,orn,ed, all , and'.split(','))).get(c,c)for c in'1'.join('horse51hound51h20belong3 to|farmer sowing his c20kept|rooster that crow3 in1m20woke|judge4shaven5 sh20marri3|man4tatter35 t20kiss3|maiden4forl20milk3|cow with1crumpl3 h20toss3|dog0worri3|cat0kill3|rat0ate|malt0lay in|house that Jack built.'.split('|')[~i:]))

```

Try it online!

---

# Python 2, ~~401~~ 398 bytes

```
for i in range(12):print'\nThis is the',' the '.join('horse and the hound and the horn?belonged to|farmer sowing his corn?kept|rooster that crowed in the morn?woke|judge all shaven and shorn?married|man all tattered and torn?kissed|maiden all forlorn?milked|cow with the crumpled horn?tossed|dog?worried|cat?killed|rat?ate|malt?lay in|house that Jack built.'.split('|')[~i:]).replace('?','\nThat ')

```

Try it online!

---

Saved

* -3 bytes, thanks to Jonathan Frech
> 2 votes

# Answer
# 05AB1E, ~~256~~ ~~245~~ 241 bytes

```
“x´ž€†0ƒé€Š Jackíš.xâì0íàltx¨Ù0ÄŠxÜ³0—Äx€„ssed0‹·x«Ëed0Ð§€Ž0 crumpledÑÛx·—ed0ì›€Ÿ€‡lornx¢¢0…Ž€Ÿ»ättered€ƒ€„rnx woke0¡Ë€Ÿ shaven€ƒ shornx¤°0ÝËoster€Š crowed€†0›árnxÊÂed€„0ÃË€Êwing€ËÃÅx0î€€ƒ0 hound€ƒ0ÑÛ“0’ €€’:'x¡'€Š™ìηʒRćD'€€kG¦}„€Œ€ˆªì¸ì»¶«,

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~666~~ ~~649~~ ~~640~~ ~~636~~ 625 bytes

```
$->{String y="This is",x="That ",w="orn\n",A="~house that Jack built.\n\n",B="~malt\n",D="~rat\n",F="~cat\n",H="~dog\n",J="~cow with~crumpled h"+w,L="~maiden all forl"+w,N="~man all tattered and t"+w,P="~judge all shaven and sh"+w,R="~rooster that crowed in~m"+w,T="~farmer sowing his c"+w,r=y+A,a[]={B,"lay in"+A,D,"ate"+B,F,"killed"+D,H,"worried"+F,J,"tossed"+H,L,"milked"+J,N,"kissed"+L,P,"married"+N,R,"woke"+P,T,"kept"+R,"~horse and~hound and~h"+w,"belonged to"+T};for(int i:"123425642786429:8642;<:8642=><:8642?@><:8642AB@><:8642CDB@><:8642EFDB@><:8642".getBytes())r+=(i%2>0?y:x)+a[i-49];return r.replace("~"," the ");}

```

Well..

NOTE: It's just like every other (non-encoded) answer incorrect for the verses about the `maiden` and `man`, where the lines of the dog and cat, as well as rat and malt are on a single line, instead of new-line separated.. I'm just too lazy to fix it, since it's closed as a dupe anyway.

**Explanation:**

Try it online.

```
$->{                  // Method with empty unused parameter and String return-type
  String y="This is", //  Temp-String "This is"
         x="That ",   //  Temp-String "That "
         w="orn\n",   //  Temp-String "orn\n"
                      //  " the ...\n" temp Strings:
  A="~house that Jack built.\n\n",
  B="~malt\n",
  D="~rat\n",
  F="~cat\n",
  H="~dog\n",
  J="~cow with~crumpled h"+w,
  L="~maiden all forl"+w,
  N="~man all tattered and t"+w,
  P="~judge all shaven and sh"+w,
  R="~rooster that crowed in~m"+w,
  T="~farmer sowing his c"+w,
  r=y+A,              //  Result-String, starting at:
                      //   This is the house that Jack built.\n\n
  a[]={               //  String-array, containing:
    B,                //   the malt\n
    "lay in"+A,       //   lay in the house that Jack built.\n\n
    D,                //   the rat\n
    "ate"+B,          //   ate the malt\n
    F,                //   the cat\n
    "killed"+D,       //   killed the rat\n
    H,                //   the dog\n
    "worried"+F,      //   worried the cat\n
    J,                //   the cow with the crumpled horn\n
    "tossed"+H,       //   tossed the dog\n
    L,                //   the maiden all forlorn\n
    "milked"+J,       //   milked the cow with the crumpled horn\n
    N,                //   the man all tattered and torn\n
    "kissed"+L,       //   kissed the maiden all farlorn\
    P,                //   the judge all shaven and shorn\n
    "married"+N,      //   married the man all tattered and torn\n
    R,                //   the rooster that crowed in the morn\n
    "woke"+P,         //   woke the judge all shaven and shorn\n
    T,                //   the farmer sowing his corn\n
    "kept"+R,         //   kept the rooster that crowed in the morn\n
    "~horse and~hound and~h"+w,
                      //   the horse and the hound and the horn\n
    "belonged to"+T}; //   belonged to the farmer sowing his corn\n
  for(int i:"123425642786429:8642;<:8642=><:8642?@><:8642AB@><:8642CDB@><:8642EFDB@><:8642".getBytes())
                      //  Loop over the bytes of the String above
    r+=(i%2>0?y       //   If `i` is odd: Append "This is "
        :x)           //   Else (`i` is even): Append "That " instead
       +a[i-49];      //   And also append the string from the array at index `i-49`
  return r.replace("~"," the ");}
                      //  Return the result, with all "~" replaced with " the "

```
> 2 votes

# Answer
# Retina, ~~322~~ 308 bytes

```

0horse20hound20h3belonged to0farmer sowing his c3kept0rooster that crowed in0m3woke0judge all shaven2 sh3married0man all tattered2 t3kissed0maiden all forl3milked0cow with0crumpled h3tossed0dog1worried0cat1killed0rat1ate0malt1lay in0house that Jack built.
3
orn1
1
¶That
L^$`0.*
This is$&$'¶
2
 and
0
 the

```

Try it online!
> 1 votes

# Answer
# Jstx, 293 bytes

```
↕Δ"▌ÇÇÉÇ◙ëÇÇÇÇÇÇÇ¬ÜëºΣ£•☼▀2.─&│E╧=▒√║∙►ybⁿ☯╫QΔ(☺¥ë2↕☯k`u3xò6┘[↨:ªh°♀êΔ╘δ‼δ@W$A⌐ΘsΘ↕║∞Φ⌡▌b⌐M±uc9╖#→δ¡9¼▀Ö╪♠¬╢æ¥.≈ëzTH♂⌡Q┐àÿî♥τ◄≈«‼û4_≤╛─◄→♂U┌█2Üüà╓ªçδ»Aÿ▄╜9■q▒iö♦4s⌐±[╗:áxÿº•╗.é÷╫╙σG¼╧[]┌>5←◙÷ö╣↨>≤±Bøz→▲√┐•♫◘╚←<∟⌡₧o?PB|Å╩↔Θ↨Γ»H☻▒╩z`6_ⁿ#∩⌂ε╦╬SNΦ9└├↓¥n-d┴≤α┐'F+~<,+╒↑│░»|M☯½☺E}°]dπ☻Ñö°á╠üdhP▼{Bßë

```

Try it online!
> 1 votes

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


title: Return closest to zero

text:
# Question
Title: Return closest to zero
# Description :

You are given a string of numbers (positive and negative but not decimals) along with the number of entries like so.

Like so

`8
'1 2 5 0 7 -9 12 -8'`

# Task :

Your job is to return the number closest to zero be it +ve or -ve. Your input will be separated by spaces only. You are free to return the answer in any way you like namely :

1. A string
2. A float (Why would you though)
3. An array (One digit array I guess)
4. A number (preferred)

Since this is code golf the answer with the shortest will be the winner. I guess?

Have fun.

### code snippets :

```
console.log(`6
'1 -2 -8 4 3 5'`) // should return 1
console.log(`3
'-12 -5 -137'`) // should return -3
console.log(`8
'1 2 5 0 7 -9 12 -8'`) // should return 0
```

### Note :

This is my first attempt at this. Apologies in advance for any mistakes, do tell so I can correct them. Thanks

# Answer
> 0 votes
# Python 2, 41 bytes

```
lambda n:min(map(abs,map(int,n.split())))

```

Try it online!

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


title: Good Old Suffix Vector

text:
# Question
Title: Good Old Suffix Vector
Inspired by an old manual...

### The challenge

I define the *a*th suffix vector of *b* as the boolean list of length *a* with *b* trailing truthy values.

Write a program or function that, given *a* and *b* by any means, returns the *a*th suffix vector of *b* by any means.

Now this may seem trivial, but here is the catch: Your score is the byte count plus the earliest year your solution would have worked.

### Rules

All standard rules apply, except that languages and language versions that were released after this challenge, may also be used.

Output using whatever representation of boolean values that your language uses, e.g. `1`/`0`, `True`/`False`, `TRUE`/`FALSE`, `"True"`/`"False"`, etc.

Output using whatever representation of lists that your language uses, e.g. `0 0 1`, `[False,False,True]`, `(FALSE;FALSE;TRUE)`, `{"False","False","True"}`, etc.

You may assume that *a**b* is always true and that they are of an appropriate data type.

### Test cases

Given *a* = 7 and *b* = 3, return `0 0 0 0 1 1 1`

Given *a* = 4 and *b* = 4, return `[True,True,True,True]`

Given *a* = 2 and *b* = 0, return `(FALSE;FALSE)`

Given *a* = 0 and *b* = 0, return `{}`

### Example solution and scoring

I might want to submit the solution `{⌽⍺↑⍵⍴1}` using Dyalog APL. That would be a bytecount of 8. This is a dynamic function, which works from version 8.1 of Dyalog APL, released in 1998, so my total score is 2006. My submitted answer should look something like:

```
# Dyalog APL 8.1, 1998 + 8 = 2006
    {⌽⍺↑⍵⍴1}

Optional explanation...
Recommended: Link to documentation showing when the features you used were released.

```

Lowest score wins!

# Answer
> 7 votes
## APL\360, 1968 + 3 bytes = 1971

```
⎕⍵⎕

```

A builtin from the tutorial @NBZ linked to. I don't know why @NBZ said it would score 1970, because APL\360 wasn't implemented until 1968, and earlier APLs like APL\1130 didn't have the suffix vector function (see page 208 of here).

# Answer
> 8 votes
# Forth, 1970 + 38 = 2008

```
:s tuck +do 0 . loop 0 +do -1 . loop ;

```

usage: `7 3 s` prints "0 0 0 0 -1 -1 -1"

# Answer
> 8 votes
# SAS, 1966 + 45 = 2011

```
data;a=;b=;do i=1to a;c=a-i<b;put c@;end;run;

```

Time for SAS to shine!

SAS wasn't first published until 1972, but this data step only uses very basic features that I'm fairly confident would have been available even in the earliest pre-release versions from 1966 onwards, so I believe it would have worked then. Input goes after `a=` and `b=`, and output is printed to the log.

I would be amazed if anyone still had an IBM System/360 with the right version of SAS to actually verify this!

# Answer
> 8 votes
## APL, 1968+5=1973

Down to 5 chars:

```
⌽⎕≥⍳⎕

```

---

Older version:

```
⌽⎕↑⎕⍴1

```

Well, you actually already gave the answer, i just removed the dynamic function definition and checked that this one worked in 1968. For reference here is the manual:

http://www.softwarepreservation.org/projects/apl/Books/APL360ReferenceManual

# Answer
> 5 votes
# Mouse-1979, 1979 + 19 = 1998

```
??&TUCK (0.a)0(1-.)

```

Translation of: Forth.

The spec is really cryptic to me but I think this does the right thing.

# Answer
> 4 votes
# TI-Basic, 1990 + 21 = 2011

The first TI calculator that this program works on is the TI-81, introduced in 1990.

```
Prompt A,B:"{}
seq(I>A-B,I,1,A

```

**Edit:** noticed that I must support an empty list... increased code by 4 bytes

# Test Cases

```
A=?7
B=?3
{0 0 0 0 1 1 1}

A=?4
B=?4
{1 1 1 1}

A=?2
B=?0
{0 0}

A=?0
B=?0
{}   * throws an error but still returns successfully

```

# Answer
> 4 votes
# Mathematica 1.0, 1988+22 bytes=2010

```
Array[#>m&/.m->#-#2,#]&

```

I'm not sure if this works, just went through the documentation on 10.3 and looked for things that said *Introduced in 1988 (1.0)*

# Answer
> 4 votes
# 68k TI-Basic, 1995 + 25 = 2020

The first TI calculator that this program works on is the TI-92, introduced in 1995.

```
define f(a,b)=seq(x>a-b,x,1,a)

```

Unlike the TI-83 series, 68k TI-Basic supports the empty list.

# Answer
> 3 votes
# Python 1.0, 1994 + 26 = 2020

Saved 2 bytes thanks to DSM.

Lambda was introduced with the first major release, 1.0

```
lambda a,b:[0]*(a-b)+[1]*b

```

# Answer
> 3 votes
# MATL, 2015 + 1 + 4 = 2020

```
:P<~

```

This works since release 6.0.0 of the language (it uses implicit input, which was introduced in that release), dated December 31, 2015.

I've added `1` to the score in accordance with @drolex comment on possibly different locales.

**Try it online!**

### Explanation

```
:    % take first input implicitly. Generate inclusive range from 1 to that
P    % flip that array
<~   % take second input implicitly. True for elements of flipped array that
     % exceed second number. Display implicitly

```

# Answer
> 3 votes
# J, 1990 + 8 = 1998

```
|.a{.b#1

```

Argh. Was researching this answer and someone got to APL before I could hope to understand the language. Here's my J solution instead.

# Answer
> 2 votes
# Prolog, 1972 + 57 = 2029

```
a(0,_,[]).
a(A,B,[H|L]):-Z is A-1,a(Z,B,L),(Z<B,H=1;H=0).

```

**Usage:** `a(7,3,L).` will unify `L` with `[0,0,0,0,1,1,1]`.

I'm really not quite sure when `is` was implemented in the language, and I doubt you can actually find the exact date. It's a pretty basic built-in though so I assume it was already existing when the language first appeared in 1972.

Not that it really matters though, I'm far from winning with this answer.

# Answer
> 2 votes
# SMP, 1983+28 bytes=2011

```
Map[S[$1>x,x->$1-$2],Ar[$1]]

```

I think I got this right... `S`:2.10, page 48 `Ar`:7.1, page 102 `Map`:7.2, page 106 `$1`:7.1, page 104

And if you're familiar with Mathematica, no, `Ar` doesn't work like *that*. More like `Range`+`Select`.

# Answer
> 2 votes
# Vim, 1991 + 21 = 2012

```
"adwj<c-x>"bdw@ai0<esc>v@bhr1

```

Input looks like this:

```
7
3

```

And output looks like this:

```
0000111

```

Explanation:

```
"adw                            'Delete a word into register a
    j<c-x>                      'Go down a line, and decrement the next number to occur
          "bdw                  'Delete a word into register b
              @ai0<esc>         'Insert a '0' "a" times
                       v        'Enter visual mode
                        @bh     'Move "b" characters left
                           r1   'Replace the whole selection with the character '1'

```

# Answer
> 2 votes
# , 1971 + 54 = 2025

```
s(l,t){while(t<l--)printn(0,8);while(t--)printn(1,8);}

```

See "The User's Reference to B" for the manual for this typeless C precursor.

# Answer
> 2 votes
# Pyth, 2015 + ~~9~~ 4 = ~~2024~~ 2019

Thanks to @FryAmTheEggman for his help!

```
gRQE

```

Try it here!

## Explanation

```
gRQE    # Q = amount of trailing truthy values
        # E = length of the vector
 R E    # map over range(E)
g Q     # d >= Q

```

# Answer
> 2 votes
## \>\<\>, 2009 + 14 + 3 for -v = 2026

`b` and `a` should be provided directly on the stack with `-v`, in reverse order.

The output isn't space separated as in the examples, but that does not seem to go against any stated rule. It uses 0 and 1 to represent false and true, as used by the language.

```
:?!;{:0(n1-}1-

```

It doesn't work with the current version since `?` now pops its test value from the stack.

I'm not confident every feature was implemented from day 1, `-v` for example could have been provided later as a commodity. I'll try to make sure my answer is correct this weekend.

# Answer
> 1 votes
# 05AB1E, 2016 + 9 = 2025

This can definitely be golfed further, but here's a start :p. Code:

```
-0s×1¹×«S

```

Try it online! The input is given as *b, a*.

Also 9 bytes: `0×1I×0ñRS`.

# Answer
> 1 votes
## PowerShell v1, 2006 \+ 28 = 2034

```
param($a,$b),0*($a-$b)+,1*$b

```

Uses the comma operator to construct the array(s), which has been in PowerShell since the beginning.

# Answer
> 1 votes
# Mathcad, 1998 + 42 = 2040

"bytes" are interpreted as number of distinct keyboard characters (eg, 'for' operator (including one programming line) is a single character ctl-shft-#, or a click on the Programming toolbar)).

The above byte count assumes that the a and b definitions don't count towards the total; add 4 bytes for definitions if this assumption is invalid.

The function version shown below adds 5 bytes for the definition and a further 3 bytes for each use (assuming the a and b values are directly typed in).

As my Mathcad solution should clearly be playing off the red tees and not the competition ones, I've added a table of solutions. Note that as Mathcad has no empty array, I've used an empty string ("") instead; I've used 0 to indicate where I haven't calculated the b\>a pairs.

# Answer
> 1 votes
# (kona), 1993 + 15 = 2008

```
((a-b)#0b),b#1b

```

Creates list of b True values, and concatenates it to a list of (a-b) False values.

# Answer
> 1 votes
## PHP, 1995 + 56 bytes = 2051

```
function s($a,$b){while($i++<$a)$v[]=$i>$a-$b;return$v;}

```
**Exploded view**
```
function s($a,$b) {
  while ($i++ < $a) $v[] = $i > $a - $b;
  return $v;
}

```

# Answer
> 1 votes
# Javascript ES6, 2015 + 46 = 2061

Returns array of 0 and 1

```
(a,b)=>Array(a-b).fill(0).concat(Array(b).fill(1))

```

# Javascript ES6, 2015 + 50 = 2065

Returns a string of `0` and `1` chars

```
(a,b)=>Array(a-b+1).join(0)+Array(b+1).join(1)

```

# Javascript, 1995 + 61 = 2056

Returns a string of `0` and `1` chars

```
function(a,b){return Array(a-b+1).join(0)+Array(b+1).join(1)}

```

# Answer
> 0 votes
# , 20 bytes + 1993 = 2013

```
function(a,b)1:a>a-b

```

Try it online!

Possibly this might work in S, which would drop the score to 2008, but I haven't been able to verify it.

# Answer
> 0 votes
# SmileBASIC 3, 2014 + 25 = 2039

The first publicly available version of SmileBASIC 3 launched in Japan with the SmileBASIC app for Nintendo 3DS in November 2014.

Prints a string where 0 is false and 1 is true (as they are in the language itself.)

```
INPUT A,B?"0"*(A-B)+"1"*B

```

---
Tags: code-challenge
---


title: Conway's game of life

text:
# Question
Title: Conway's game of life
# Description :

Given an array of strings representing a grid of cells

With the key :

`0 = 'dead cell'
1 = 'live cell'`

write a function that returns the next iteration following the rules of **Conway's Game of Life** .

# Rules

1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

### Examples :

```
["111" , "110" , "100"] //input
["101" , "001" , "110"] // output
/**
  * There will be other tests so no hardcoding.
**/
```

This is code golf shortest code wins. Good luck and have fun

# Answer
> 1 votes
# Jelly,  ~~40~~  38 bytes

```
z0j@€0,0µ⁺ṡ3Z€ṡ€3S€€⁺Ḥ
L€ḣ@"Ç+e€€7,9,6

```

A monadic link accepting and returning lists of lists of ones and zeros

**Try it online!**

### How?

Cells will be alive in the next generation if:

1. it was alive in a neighbourhood (including itself) of three or four
2. it was dead in a neighbourhood of exactly three

Therefore if double the neighbourhood plus "was alive" is seven or nine (case 1) or six (case 2) then it will be alive next generation.

(For all other possible cases the sum of double the neighbourhood and "was alive" are *other* integers in the range \[0,19\])

```
z0j@€0,0µ⁺ṡ3Z€ṡ€3S€€⁺Ḥ - Link 1, neighbourhood counts * 2: board
        µ⁺             - perform this monadic link twice:
z0                     -   transpose with filler zero
     0,0               -   list [0,0]
  j@€                  -   join €ach with swapped arguments (surround each with zeros)
          ṡ3           - all overlapping sub-lists of length three (i.e. lists of rows)
            Z€         - transpose €ach
              ṡ€3      - all overlapping sub-lists of €ach of length three (i.e. 3x3 neighbourhoods)
                 S€€⁺  - repeated sum for €ach for €ach (neighbourhood sum)
                     Ḥ - double
                       - Note: the result includes counts of off-board areas filling right

L€ḣ@"Ç+e€€7,9,6 - Main link: board
     Ç          - call the last link (1) as a monad (get 2 * neighbourhood counts)
L€              - length of each row of the input board
  ḣ@"           - zip with head to index with swapped arguments
                - (i.e trim the neighbourhood counts to the shape of the input board)
      +         - add (vectorises) (i.e. 2 * neighbourhood count + was alive)
          7,9,6 - list = [7,9,6]
       e€€      - exists in? for €ach for €ach

```

---
Tags: code-golf, string, math, cellular-automata, game-of-life
---


title: Sequence splitting

text:
# Question
Title: Sequence splitting
Given an arbitrary sequence consisting of 1 and A split this sequence up so that A is at the beginning of each sub sequence. Sequences without a leading A and Sequences without 1 before the next A will be self contained.

Example

Input

```
111A11A1111111A1A1AA

```

should result in

```
111
A11
A1111111
A1
A1
A
A

```

Above already contains the edge cases * sequence of 1 without prior A * subsequent A's without 1 between

*Update* Open to all programming languages (functional / non-functional)

# Answer
# APL (Dyalog Unicode), 12 bytes

Anonymous tacit function. Returns a list of strings.

```
⊢⊂⍨1⊣@1=∘'A'

```

Try it online! ( is just to display the list of strings as separate lines.)

`=∘'A'` Boolean list (1s and 0s) indicating As

`1⊣@1` replace with a 1 at the first position

`⊢⊂⍨` begin partitions of the argument at each 1 in that
> 3 votes

# Answer
# Retina, ~~6~~ 5 bytes

*1 byte saved thanks to @Neil!*

```
L`.1*

```

Try it online!

### Explanation

```
L`      Configure the stage as "list", so that it outputs all matchings
.1*     Regex to be matched: any character followed by zero or more "1"

```
> 2 votes

# Answer
## Retina, 6 bytes

```
\BA
¶A

```

Try it online!

An alternative to Luis's solution. Finds all `A` which are preceded by another character and inserts a linefeed in front of them.
> 2 votes

# Answer
# Haskell, ~~54~~ 37 bytes

```
import Data.List
groupBy(\_ x->x<'A')

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~10~~ 8 bytes

```
'A"
A".:

```

Try it online!

Can probably be golfed further, but first submission and attempt at this.

**Explanation**

```
'A"           Push A character, Push string "(new line) A"
 A"           close string
.:            Replace all. Replace "A" with "(new line) A" in input

```

~~If you want code to match output like in original post then 11 bytes~~

~~```
I'A" A".:#»

```~~

-2 bytes thanks to Soaku!
> 2 votes

# Answer
# Befunge-98 (FBBI), ~~14~~ 12 bytes

-2 bytes thanks to Jo King

```
#@~:d%5/ja,,

```

Try it online!

```
#@            # skips @
  ~           push a byte of input
   :          duplicate it
    d%        modulo 13, 'A':0, '1':10
      5/      divided by 5, 'A':0, '1':2
        j     jump this number of blocks, skips the next two instructions for '1'
         a,   push 10 to the stack and output as a byte (\n)
           ,  output the byte of input

```

If there is no input left, `~` reflects the pointer and `@` terminates the program
> 2 votes

# Answer
# Jelly, 5 bytes

1 The slooooow but shorter method which gets all ways\* to partition the list and then finds the maximal as measured by its transpose:

```
ŒṖZÞṪ

```

**Try it online!**

* that is all **2length(input)-1** ways!

2 The speedy method using the "partition at truthy indices" atom (the five byte `=”Aœṗ` fails for inputs starting with `A`):

```
Ḋ=”A0;œṗ

```

**Try the speedy one!**
> 2 votes

# Answer
# Japt, 6 bytes

```
d'A_iR

```

Try it online!

### Explanation:

```
d'A_iR
d       // Replace:
 'A     //   "A" with
   _iR  //   newline + "A"

```

Alternative 6-byte solution

```
r'A"
A

```

Try it online!

These would be 5-byte solutions if we could take `a` instead of `A`.
> 1 votes

# Answer
# Standard ML (MLton), 40 bytes

```
String.translate(fn#"A"=>"\nA"|x=>str x)

```

Try it online!

Unfortunate that `String.translate` is so long...
> 1 votes

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

```
s/A/
A/g

```

Try it online!
> 1 votes

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

```
z=>z.split(/(?=A)/).join`
`

```

Try it online!

---

# Explanation :

```
z =>                   // lambda function taking z as input
    z.split(           // convert z to an array by splitting at
            /(?=A)/    // all `A's`
    ).                 // end split
        join`\n`       // join all via new line

```

---

# Alternate :

If printing an array is okay, then :

# JavaScript (Node.js), 19 bytes

```
z=>z.split(/(?=A)/)

```

Try it online!
> 1 votes

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

```
s=>s.match(/A1*|^1+/g)

```

Try it online!
> 0 votes

# Answer
# Scala, 20 bytes

```
_.replace("A","\nA")

```

Try it online!

(Not sure if putting the types in the header is allowed, I'll change it if not.)
> 0 votes

# Answer
# JavaScript (Node.js), ~~20~~ 19 bytes

```
s=>s.split(/(?=A)/)

```

Try it online!

Thanks Pandacoder for 1 byte
> 0 votes

# Answer
# JavaScript, ~~26~~ 23 bytes

*-3 bytes thanks to caird coinheringaahing*

```
s=>s.replace(/A/g,`
A`)

```

Try it online!
> 0 votes

# Answer
# Pyth, ~~8~~ 7 bytes

```
:Q\A"
A

```

Try it here

### Explanation

```
:Q\A"\nA
:Q         Replace in the input...
  \A       ... every instance of "A"...
    "\nA   ... with a newline followed by "A".

```
> 0 votes

# Answer
# Python 2, 29 bytes

```
lambda I:I.replace('A','\nA')

```

Try it online!
> 0 votes

# Answer
## Batch, 44 bytes

```
@set/pa=
@for %%a in (%a:A= A%)do @echo %%a

```

Takes input on STDIN.
> 0 votes

# Answer
# Java (JDK 10), 19 bytes

```
s->s.split("(?=A)")

```

Try it online!
> 0 votes

# Answer
# Pepe, 59 bytes

```
rEEeREeEeeeeeEREeeeeeeeeREEreeEREEeeREEreEeREEeEReEREEeeRee

```

Try it online!

That was hard... Outputs with leading newline.

```
rEEe           # r - Get input               Take the string

REeEeeeeeE     # R - Push A                  A - splitter
REeeeeeeee     # R - Push \0                 \0 - end
REE            # R - Create label A          label A: Next + newline

 reeE          # Output newline              Output newline

 REEee         # R - Forward
 REE           # R - Create label \0         label \0: Next without newline

 reEe          # r - Output                  Output the current letter and pop it

 REEeE         # R - Rewind
 ReE           # r pointer == A, goto A      Output newline, next letter

 REEee         # R - Forward                 Else
 Ree           # r pointer != \0, goto \0    If stack isn't empty, next letter

```
> 0 votes

# Answer
# Haskell, 29 bytes

```
f s=do c<-s;['\n'|c>'1']++[c]

```

Try it online!
> 0 votes

# Answer
# R, 26 bytes

Not a whole lot to explain with this one.

```
cat(gsub("A","\nA",scan()))

```
> 0 votes

# Answer
# sed, 9 bytes

```
s/A/\nA/g

```

Try it online!
> 0 votes

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


title: ;# without resetting

text:
# Question
Title: ;# without resetting
`;#` is a very simple language. It has 2 commands:

* `;` will increment the accumulator
* `#` outputs the accumulator modulo 127, and then resets the accumulator

`;$` is also very simple and is very similar (and also does not yet exist). It has 2 commands:

* `;` will increment the accumulator
* `$` outputs the accumulator modulo 127. However, it does not reset the accumulator.

# Challenge

Create a program that will convert `;#` code to `;$` code. That is, given input `a` using standard methods, output he shortest `b` such that `a` in `;#` outputs the same thing as `b` in `;$`. The input will only contain the characters `';'` and `'#'`. The input will not have trailing semicolons. That is, it will match the regex `(;*#)+`. This also means input will not be blank. Note that `;;;;##` is possible (equivalent to `ord(4) ord(0)`).

# Examples

```
;# code -> ;$ code
;;;;;;;;;;#;;;;;;;;;;;;# -> ;;;;;;;;;;$;;$
;;;;;;;;;;;;;;#;;;# -> ;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# -> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;$$;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;$;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;$ (Hello, World!)

```

# Answer
> 3 votes
# Jelly, 18 bytes

```
ṣ”#L€ṙ-I%127”;ẋp”$

```

Try it online!

### How it works

```
ṣ”#L€ṙ-I%127”;ẋp”$  Main link. Argument: s (string)

ṣ”#L€               Split s at hashes. Take the length of each resulting chunk.
     ṙ-             Rotate the result -1 units to the left / 1 unit to the right.
                    Since s won't have trailing semicola, the length of the last
                    chunk will be 0. Rotating moves this 0 to the beginning.
       I            Increments; take all forward differences. Because of the 0 we
                    removed to the beginning, the first forward difference will be
                    the length of the first chunk.
        %127        Take the differences modulo 127. In Python, `n % d' is either 0
                    or has the same sign as d, so this reports how many semicola
                    are needed to get from one code point to the next one.
            ”;ẋ     Repeat ';' k times, for each modulus k.
               p”$  Take the Cartesian product with "$", appending '$' to each run
                    of semicola.

```

# Answer
> 2 votes
## JavaScript (ES6), 68 bytes

```
s=>s.replace(/;*#/g,s=>';'.repeat((127-a+(a=s.length))%127)+'$',a=1)

```

### Examples

```
let f =

s=>s.replace(/;*#/g,s=>';'.repeat((127-a+(a=s.length))%127)+'$',a=1)

console.log(f(";;;;;;;;;;#;;;;;;;;;;;;#"))
console.log(f(";;;;;;;;;;;;;;#;;;#"))
console.log(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"))
```

# Answer
> 1 votes
# PHP, 99 bytes

```
while(~$c=a^$argn[$p++])j^$c?r^$c?:$a=-$b*$b=print str_repeat(";",(127+$a%127)%127)."$":$b+=!!++$a;

```

# Answer
> 1 votes
# , 37 bytes

```
[:;';$'<@#~1,.~127|2-~/\0,=&'#'#;._2]

```

Try it online!

# Answer
> 0 votes
# Python, ~~101~~ ~~100~~ ~~97~~ 85 bytes

*1 bytes saved thanks to @WheatWizard*

```
def t(c,s=0):
 for x in map(len,c.split('#')[:-1]):print(end=';'*((x-s)%127)+'$');s=x

```

# Answer
> 0 votes
# Retina, 52 bytes

```
^
##
#
127$*;$
^;+\$;+\$|(;+)(?<=\$\1(;{127})?\$\1)

```

Try it online! Includes test suite. Explanation: 127 is added to each `#` to make the subtraction modulo 127 easier; the `#`s are changed to `$` at the same time. The subtraction itself is handled by the lookbehind `(?<=\$\1(;{127})?\$\1)` which ensures that we subtract either the number of `;`s between the previous two `#`s (which handles the case when there are more `;`s) or 127 fewer than that number (which handles the case when there are fewer `;`s and they need to wrap past 127). A lookbehind is used so that all the replacements can be calculated in one pass. In order for there always to be two previous `#`s, two extra `#`s are temporarily prefixed.

# Answer
> 0 votes
# Perl 5 `-p`, 65 bytes

```
s/(;*)#/$b=($q+$b)%127;';'x($q+=(($q=length$1)<$b)*127-$b).'$'/ge

```

Try it online!

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


title: Is the program 32 or 64 bits?

text:
# Question
Title: Is the program 32 or 64 bits?
Assignment is simple to explain: write the shortest code you need to determine whether an executable binary program supplied as parameter is 32 or 64 bits.

If there is a different kind of bitness, you can also do for it, but is not mandatory.

What I really don't want is telling me you support other bitnesses and after I get 32 or 64 as a result.

Valid outputs for 32:

```
32
32bit
32bits
32 bit
32 bits

```

The same pattern for 64.

No accepted answer.

# Answer
# Jelly on Linux, 6 bytes

```
5ịO×32

```

Try it online!

Usage note: the question says "write the shortest code you need to determine whether an executable binary program supplied as parameter", and that's exactly what you need to do here; supply the entire executable binary program as the parameter. Not its filename, the program itself. (I hope you have a fairly understanding shell!) The TIO link uses the shortest known ELF program Linux will run, by Brian Raiter as the example program.

Linux uses ELF as its executable format. It turns out that the fifth byte of an ELF program specifies the processor bitwidth it's designed for: 0x01 for a 32-bit program, or 0x02 for a 64-bit program. So all we have to do is extract the byte in question (`5ị`), convert it from a character to a number (`O`), and multiply by 32 (`×32`).

There's probably a language that can use this exact algorithm more succinctly, but I wanted to post this answer to demonstrate the algorithm.
> 5 votes

# Answer
# Bash + common Linux utils, 18

* 2 byte saved thanks to @Dennis.

```
file -|cut -c17-18

```

The input program piped in.

Try it online!
> 2 votes

# Answer
# MATL (Linux), 5 bytes

```
5)32*

```

Implicitly input entire program. Get fifth byte, multiply by 32.

Try it online!

---

As a bonus, here's an answer that works on most (but not all) Windows executables, for 20 bytes:

```
t'PE'Xf1)4+)100=Q32*

```

Try it online!

Find the `PE` signature (which would fail if there's an unusual DOS stub containing `PE`) and see if it is followed by `d` (100) two bytes later (which corresponds to x64, and thus would fail for other 64 bit architectures)
> 2 votes

# Answer
## GolfScript for ELF (5 bytes)

```
4=32*

```

## CJam for ELF (6 bytes)

```
q4=32*

```

or

```
q4=5m<

```

---

This is why I commented in the sandbox that "challenge" was not an appropriate description of this task.
> 2 votes

# Answer
# Windows Bash (with core util?), test PE32 vs PE32+; 37 bytes

```
file $1|grep -q 2+&&echo 64||echo 32

```

This is a bash script works on Windows Bash (`bash` in Ubuntu Linux Subsystem on Windows 10), which tell given `*.exe` file 32 bit or 64 bit.

Not yet tested on other platform, maybe it work.
> 1 votes

# Answer
# Jelly (Windows), 24 bytes

```
ƈO
Ç64Ð¡Uḣ4%⁹ḅ⁹_38Ç¹¡×32

```

Hexdump:

```
00000000: 9c4f 7f0e 3634 0f00 55ed 3425 89d4 895f  .O..64..U.4%..._
00000010: 3338 0e81 0011 3332                      38....32

```

I have no idea why `%⁹` is necessary, but it is.

Takes the whole executable from STDIN. Take from command line argument would definitely shorter but there is a (small) upper bound on the size.

Yes, Windows PE executable format is hard to parse. Also Jelly hates non-constant nilad.

---

```
ƈO

```

Link 1: Return the next byte value from stdin.

```
Ç64Ð¡Uḣ4%⁹ḅ⁹

```

Read the 4-byte `e_lfanew` at offset 60 and convert it to an integer.

```
_38Ç¹¡

```

Take the byte at (e\_lfanew - 38) positions later which is the higher byte of the signature in the PE optional header, described here at the "optional header magic number" part.

```
×32

```

Multiply by 32. Get 32 for 32-bit executables (PE32) and 64 for PE32+.
> 1 votes

# Answer
# Haskell, ~~36~~ 35 bytes

```
fmap((32*).fromEnum.(!!4)).readFile

```

For the ELF format

Try it online!
> 1 votes

# Answer
# Ruby `-n`, 23 bytes

```
p IO.read($_)[4].ord*32

```

Try it online!

Linux ELF version. TIO link tests the interpreter on itself.
> 0 votes

# Answer
# Bash, 36 bytes

```
cp $1 x
file x|egrep -o '32|64'|uniq

```

Try 64 bits online!

Try 32 bits online!
> 0 votes

---
Tags: code-golf, x86-family
---


title: +- knapsack problem

text:
# Question
Title: +- knapsack problem
Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

Wikipedia for more information

For example you can be given a max weight of 15 and objects with value/masses as `[5,2], [7,4] [1,1]` and you would output `[7,0,1]` which is 7 `[5 <value>, 2 <mass>]` objects and 1 `[1 <value>, 1 <mass>]` object for a score of 36.

# Rules

Input can be taken in any reasonable format

Output is also flexible format,

You may not use libraries that are non-standard. If you have to *install* or *download* any library to use it separate from the initial setup then it is ***not*** allowed

Objects may have negative mass and value (i.e -1,-1)

Optimal answers required

# Winning

Shortest code wins

# Negative mass and value?

This is a key part of this challenge. Lets say you have a object with items (mass, value) such as `[4,3],[-1,-1]` and a bag with capacity of 15. You could put 3 of the first ones and score 9 or put 4 of the first ones and one of the -1,-1 object for a score of 11.

# Answer
# Pyth, 18 bytes

```
h.MshMZfghQseMTy*F

```

Outputs as a list of \[value, weight\] pairs. Horrendously inefficient, but it *is* NP-complete.
Try it here

### Explanation

```
h.MshMZfghQseMTy*F
               y*FQ  Get all sets with up to <capacity> of each item.
       fghQseMT      Choose the sets whose total weight fits in the bag.
 .MshMZ              Choose those with the highest value.
h                    Take the first.

```
> 2 votes

---
Tags: code-golf, optimization
---