# Question
Title: Is there a single straight line in the matrix?
Inspired by Wzl

Determine if a given square binary matrix has exactly one row or column consisting of entirely `1`s, and the rest of the matrix is `0`s.

For example, these are all true:

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

```

And these are all false:

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

```

The reasons for the false ones:

* More than one row
* More than one row or column
* There are `1`s outside the "all `1`s column"
* There isn't a row or column of all `1`s (describes the last 4)

You should take a square binary matrix of side length \\$n \ge 2\\$, in any reasonable format, and output 2 distinct, consistent values to indicate whether it has a single straight line. This is , so the shortest code in bytes wins.

---

**Keep your golfing in your code, not your inputs/outputs**. I'm very liberal with the I/O formats, including but not limited to:

* A multiline string
* A list of lines
* A 2D list (or matrix) consisting of two distinct consistent values (e.g. `0`/`1`, space/`'*'`, `5`/`'('`)
* A flat array, and \\$n\\$, as separate arguments

* Two distinct consistent values (e.g. `1`/`0`) to indicate the output
* Erroring/not erroring
* Two families of values, one of which consists of values that are truthy in your language and the other falsey (for example, natural numbers and zero)

* etc.

As a broad, general rule, so long as the input can be clearly understood and the outputs clearly distinguished, it's fair game.

---

## Test cases

| Input | Output |
| --- | --- |
| ``` 000000000<br>000000000<br>000000000<br>000000000<br>000000000<br>000000000<br>000000000<br>000000000<br>111111111 ``` | true |
| ``` 00000<br>11111<br>00000<br>00000<br>00000 ``` | true |
| ``` 1000<br>1000<br>1000<br>1000 ``` | true |
| ``` 01<br>01 ``` | true |
| ``` 0000000<br>1111111<br>0000000<br>1111111<br>0000000<br>0000000<br>0000000 ``` | false |
| ``` 01000<br>11111<br>01000<br>01000<br>01000 ``` | false |
| ``` 0100<br>1101<br>0100<br>0100 ``` | false |
| ``` 1000<br>0100<br>0010<br>0001 ``` | false |
| ``` 000<br>101<br>000 ``` | false |
| ``` 000<br>000<br>000 ``` | false |
| ``` 001<br>100<br>010 ``` | false |
| ``` 01<br>00 ``` | false |

# Answer
# Python 2, 49 bytes

Takes as input a 2D binary matrix \\$ a \\$, and its size \\$ n \\$.

```
lambda a,n:sorted(map(sum,a+zip(*a)))[-2:]==[1,n]

```

Try it online!

There may be shorter approaches, but this is what I could find for now. Please let me know if the algorithm is incorrect.

## Explanation

Since there is exactly one line, there should be exactly one row/column which contains \\$ n \\$ ones. Furthermore, since every \\$ 1 \\$ in the matrix exists on that line, there can be no other row/column containing more than one \\$ 1 \\$. Since if there were another \\$ 1 \\$ existing somwhere not on that line, it would create a row/column with at least two \\$ 1 \\$s.

Given this, it suffices to check that the two rows/columns with the largest number of \\$ 1 \\$s have counts of `[1, n]`.
> 29 votes

# Answer
# Brachylog, 8 bytes

```
{z|}≡ᵛ+1

```

Try it online!

```
{z|}        Either the rows or the columns
    ≡ᵛ      are all the same list
      +1    which sums to 1.

```
> 15 votes

# Answer
# Ruby, 47 bytes

```
->m,n{m.uniq[1]?m-[[0]*n]==[[1]*n]:m[0].sum==1}

```

Try it online!

### Explain please:

Split the two cases:

* If m has at least 2 different rows, remove all zeros and check if we are left with a single row consisting of ones.
* If not (all the rows are the same), check that the sum of the first row is one.
> 11 votes

# Answer
# Factor \+ `math.unicode`, 59 bytes

```
[ [ concat Σ = ] keep dup flip [ all-equal? ] bi@ or and ]

```

Try it online!

Takes \\$n\\$ and a matrix of \\$1\\$s and \\$0\\$s, in that order.

* `[ concat Σ = ] keep` Is the sum of the matrix equal to \\$n\\$?
* `dup flip [ all-equal? ] bi@ or and` And are all the rows in either the original matrix or its transposition equal?
> 10 votes

# Answer
# JavaScript (ES6), 46 bytes

*Thanks to @PertinentDetail for a bug fix*

Expects a multiline string with a trailing line feed. Returns a Boolean value.

```
s=>/^(0*10*\n)\1*$|^(0+\n)*1+\n[^1]*$/.test(s)

```

Try it online!
> 10 votes

# Answer
# Jelly, 9 bytes

```
S;§ṢIṪ‘=L

```

Try it online!

Slightly modified port of dingledooper's algorithm.

### How it works

```
S;§ṢIṪ‘=L    Monadic link; input = matrix M
S;§          Column sums of M ++ Row sums of M
   Ṣ         Sort
    I        Increments; (next - previous) for each adjacent pair
     Ṫ       Last item
      ‘      +1
       =L    Equals the length of M?

```

# Jelly, 9 bytes

```
ZEȯE×SS=L

```

Try it online!

Slightly modified port of chunes's algorithm.

### How it works

```
ZEȯE×SS=L    Monadic link; input = matrix M
ZE           1 if transpose(M) has all rows equal
  ȯE           or M has all rows equal, 0 otherwise
    ×SS      times column sum, and sum again
             (= times the sum of the entire matrix)
       =L    equals the length of M?

```
> 8 votes

# Answer
# Wolfram Language (Mathematica), ~~21~~ ~~13~~ 35 bytes

```
Norm@#==#2&&Norm@Eigenvectors@#>#2&

```

Try It Online! (Thanks to @ZaMoC for configuring this.)

Takes `#` as the matrix, and `#2` as the square root of the side length, n. Returns True if the conditions are met, and False otherwise

**Explanation**

In Mathematica, the `Norm` function, when applied to a matrix, will perform a singular value decomposition and then identify and return, from among the resulting matrices, the element with the largest value. For most square binary matrices with n ≥ 2, the conditions will be met IFF the `Norm` of the matrix equals sqrt(n), i.e., if the following returns True:

```
Norm@#==#2&

```

However @Nitroden found an exception, which can be generalized as follows: If sqrt(n) is an integer, and the matrix contains a sqrt(n) x sqrt(n) submatrix that is all 1's, and has 0's everywhere else, its `Norm` will also equal sqrt(n).

Thus, to eliminate those, I added an additional test: that the `Norm` of the `Eignevectors` of the matrix is greater than sqrt(n).

My *Try It Online!* link contains all the OP's test matrices and, at the end, Norden's case plus three additional matrices of that form. These now all return False.

Alas, Mathematica's `Eigenvectors` function is 12 bytes.

Thanks to @Bubbler for the tip that my `If` wrapper was unnecessary.
> 8 votes

# Answer
# Vyxal, 12 bytes

```
:∑$v∑Js¯Nt›=

```

Try it Online!

Yay! Beating Lyxal by 1 byte with a different approach!!!

-1 byte from @Lyxal himself thanks
> 7 votes

# Answer
# 05AB1E, 8 bytes

Based on the first part of Bubblers Jelly answer, which uses dingledooper's algorithm.

Input is a 2d matrix and the side length, output is `1` for truthy inputs and any other integer for falsy ones. This is the definition of truthiness in 05AB1E.

```
Dø«O{¥θα

```

Try it online! or Try all cases!

```
D         # push two copies of the input matrix
 ø        # transpose one copy to get a list of columns
  «       # concatenate to the list of rows
   O      # sum each sublist
    {     # sort the row and column sums
     ¥    # take consecutive differences
      θ   # get the last one (largest value - second largest value)
       α  # absolute difference with the second input

```
> 7 votes

# Answer
# Jelly, 10 bytes

```
S;§>Ƈ1⁼LW$

```

Try it online!

Uses Unrelated string's test suite.

Fixed with some help from Unrelated string.

## Explanation

```
S;§>Ƈ1⁼LW$
S           sums of columns
 ;          concat with
  §         sums of rows
    Ƈ       keep the sums which are:
   > 1       greater than 1
      ⁼LW$  = [length] ?

```
> 6 votes

# Answer
# , 25 bytes

```
(1:0}0"0)e.],&(#\|."{])|:

```

Try it online!

Not the shortest (my previous translation of dingledooper's was a couple bytes shorter), but I wanted to come up with a different approach:

* `(1:0}0"0)` Is the matrix with all ones in the first row and zeros elsewhere...
* `e.` an elment of...
* `],&(#\|."{])|:` All possible rotations of the input, and all possible rotations of its transpose, catted together?
> 6 votes

# Answer
# Jelly, 9 bytes

```
ŒṪZEƇȧiɗJ

```

Try it online!

The *fourth* totally different Jelly 9 byter. Returns either 1 or 2 for truthy and either an empty list or the number 0 for falsy. Also the program structure is more convoluted.

### How it works

```
ŒṪZEƇȧiɗJ    Monadic link. Input: the matrix M of size n
ŒṪZ          Take the transpose of multi-dimensional indices of 1
             the result is a 2-row matrix X;
             in order to satisfy the condition, one of the rows must be
             all-equal, and the other must be identical to 1..n
   ....ɗJ    A dyad with ^ as left arg and 1..n as right:
   EƇ          Collect every row that is all-equal from X
     ȧ         Chain onto Python's `and`...
      i        Get 1-based index of 1..n in X, 0 if not found

```
> 6 votes

# Answer
# Jelly, 9 bytes

```
,ZfJṁ=ⱮJƲ

```

Try it online!

Idea stolen from Razetime in TNB

```
,            Pair the input with
 Z           its transpose.
  f          Filter the pair to elements contained in
   Jṁ=ⱮJƲ    every matrix of the same dimensions with a single column of 1s.

   Jṁ        Mold [1 .. len(input)] to the shape of the input.
      ⱮJ     For each 1 .. len(input),
     =       is each element equal to it?

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), 25 bytes

```
#||#/.{a_..}:>Tr@a==1&

```

Try it online!

Returns `True` if the matrix has a single line, and non`True` otherwise.

```
#||#                   input OR its tranpose
     /.{a_..}:>         replace lists of repeated elements with
               Tr@a==1      (is the sum of that element equal to 1?)

```

Then, any `Or` expression with `True` as an argument gets reduced to `True`.
> 5 votes

# Answer
# Python 2, 43 bytes

*Heavily based on dingledooper's answer, which you should upvote.*

```
lambda a,n:set(map(sum,a+zip(*a)))=={0,1,n}

```

Try it online!

Or:

### Python 3, 44 bytes:

```
lambda a,n:{*map(sum,a+[*zip(*a)])}=={0,1,n}

```

Saves bytes with set unpacking, but loses bytes because `zip` doesn't return a list. Try it online!

### Explanation

In a truthy input, the sum of a row or column must be one of these three numbers:

* \\$0\\$, if it is parallel to the line of \\$1\\$s
* \\$1\\$, if it is perpendicular to the line of \\$1\\$s
* \\$n\\$, if it is the line of \\$1\\$s

Any number other than these three indicates the existence of multiple lines or a partial line.

Furthermore, all three of these numbers must be represented among the list of sums:

* If \\$n\\$ is missing, there is no row or column that contains all \\$1\\$s.
* If \\$1\\$ is missing, there are multiple rows and columns containing \\$1\\$s.
* If \\$0\\$ is missing, the input has two perpendicular lines of \\$1\\$s (as in the second falsey test case). Conveniently, we don't have to worry about the case of a \\$1 \times 1\\$ matrix, because we're given that \\$n \geq 2\\$.

Therefore:

```
set(                  )           # The set of
    map(sum,         )            # the sums of each
            a+                    # row and
              zip(*a)             # column
                       ==         # must be exactly
                         {0,1,n}  # that set

```
> 4 votes

# Answer
# Retina 0.8.2, 32 bytes

```
^(0*10*)(¶\1)*$|^(0+¶)*1+(¶0+)*$

```

Try it online! Turns out to be much like @Arnauld's answer, except I wanted to solve it for no trailing newline instead.
> 3 votes

# Answer
# Julia, 37 bytes

```
x$n=(l=sum([x x'],dims=1))[l.>1]==[n]

```

Try it online!

uses Razetime's approach
> 3 votes

# Answer
# Vyxal, 14 bytes

```
:ÞTJv∑s2Nȯ1?"⁼

```

Try it Online!

Another stealing of the python answer.

## Explained

```
:ÞTJv∑s2Nȯ1?"⁼
:ÞTJ           # merge the input list with itself transposed.
    v∑s        # sort the list that results from getting the sum of each item
       2Nȯ     # take the last two items of that list
          1?"⁼ # and check for equality with the list [1, second_input]

```
> 2 votes

# Answer
# T-SQL, 152 bytes

Input is a table variable

Returns 1 for true, 0 for false

To save bytes, this can only handle matrix up to length 10

```
SELECT top 1iif(x=replace(a,0,'')or
sum(x)over()=x*2-1and a not like'%0%'and
0=min(a)over(),1,0)FROM(SELECT
rank()over(order by a)x,*FROM @)c ORDER BY-x

```

**Try it online**
> 2 votes

# Answer
# tinylisp, 88 bytes

```
(load library
(d _(q((M)(e 1(*(sum(map all M))(sum(map any M
(q((M)(+(_ M)(_(transpose M

```

The solution is the anonymous function in the last line. Try it online!

Here's an ungolfed version that verifies all test cases: Try it online!

### Explanation

Define a helper function `_` that takes a matrix (list of lists) `M`:

```
      (sum(map all M))                    Number of rows that are all 1s
                      (sum(map any M))    Number of rows that have any 1s
    (*                                )   Multiply those two numbers
(e 1                                   )  Is the product equal to 1?

```

In other words, is there exactly one row that has all 1s, which is also the only row that has any 1s?

Then our main function needs only apply `_` to the matrix and its transpose, and return truthy if either result is truthy:

```
  (_ M)                   Test M
       (_(transpose M))   Test transpose(M)
(+                     )  Add the two results

```
> 2 votes

# Answer
# Charcoal, 27 bytes

```
ＷＳ⊞υι∨∧⁼⌊υ⌈υ⁼¹Σ⌈υ⁼ΦυΣι⟦⭆⌈υ¹

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings. Explanation:

```
ＷＳ⊞υι

```

Input the matrix.

```
  ⁼⌊υ⌈υ                 All rows are identical
 ∧                      Logical And
         Σ⌈υ            The sum of a row
       ⁼¹               Equals literal `1`
∨                       Logical Or
              υ         Input array
             Φ          Filtered where
                ι       Current row
               Σ        Is non-zero
            ⁼           Equals
                  ⭆⌈υ¹  Row of 1s
                 ⟦      As a 1-row 2D array

```
> 1 votes

# Answer
# APL (Dyalog Unicode), ~~63~~ 55 bytes

```
{(F⍉⍵)+(F←{(1↑⍴⍵)=(+/,⍵)×+/∧/⍵})⍵}

```

Try it online!

* changed approach
* F used on input + input transposed

```
×+/∧/⍵  ⍝ number of all 1s lines multiplied by
(+/,⍵)    ⍝ total 1s
(1↑⍴⍵)=  ⍝ equal to side length?

```
> 1 votes

# Answer
# PowerShell, ~~49~~ ~~45~~ 46 bytes

inspired by Arnauld's and Neil's answers.

+1 bytes with additional Test cases.

```
"$args "-match'^(0*10* )\1+$|^(0+ )*1+ [0 ]*$'

```

Try it online!

* convert the arguments to a string with space char as separator
* add the trail space char
* match with regexp
> 1 votes

# Answer
# GNU-APL, 34 bytes

```
{+/(⍺≡+/,⍵)∧(⍵∧.=⍺⍴1)∨((⍺⍴1)∧.=⍵)}

```

Input the size of the matrix, and the matrix itself.

```
⍵∧.=⍺⍴1    finds the row with all ones, a1=1∧a2=1∧a3=1 ...
(⍺⍴1)∧.=⍵  finds the column with all ones
           The disjunction of the above two ensures atleast one of them happends
⍺≡+/,⍵     ensures that only required numbers of ones are present

```
> 1 votes

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

*-2 bytes thanks to ceilingcat*

```
l;e;r;o;a;f(m,n)int*m;{r=l=o=0;for(e=a=~0;r++<n;o|=*m,a&=*m++)~*m<<32-n?e&=!*m:++l;for(o-=a;a;a/=2)l+=a&1;r=l<2&&e^!o;}

```

This has entire rows stored in integer arrays, making the maximum matrix size 32.

Try it online!
> 1 votes

# Answer
# jq, 38 bytes

Reads a 2D array, outputs a boolean.

```
(.+transpose|map(add)-[0,1])==[length]

```

Try it online!
> 1 votes

---
Tags: code-golf, decision-problem, subsequence, binary-matrix
---


title: Implement the flip-floperator

text:
# Question
Title: Implement the flip-floperator
Ruby has a strange operator, `..`, called flip-flop (not to be confused with the range operator, which looks the same). Used in a loop, flip-flop takes two conditions as operands and will return `false` until the first operand is truthy, then return `true` until the second operand is truthy, whereupon it returns `true` one more time and restarts the cycle with `false`.

```
0.upto 10 do |i|
  if (i==2)..(i==8)
    puts i
  end
end

# Prints 2, 3, 4, 5, 6, 7, and 8

```

Attempt This Online

Your task is to implement a higher-order function (or something equivalent in your language) that behaves like flip-flop. It must take two predicate functions as arguments and return a new function that takes an argument and returns falsey until the first predicate returns `true` given the argument, continues to return `true` until the second predicate returns `true`, whereupon the flip-flop returns `true` one more time (think of it like an inclusive range) and thereafter returns `false`, until the first predicate returns `true` again and so on.

Below is an example of such a function called `make_flip_flop`, which takes two predicate lambdas and returns a new lambda, `flip_flop`, to be used in the following loop.

```
flip_flop = make_flip_flop(->i{ i==2 }, ->{ i == 8 })

0.upto 10 do |i|
  if flip_flop.(i)
    puts i
  end
end

# Prints 2, 3, 4, 5, 6, 7, and 8

```

Here's another example with a different set of predicates:

```
flip_flop = make_flip_flop(->i{ i % 5 == 0 }, ->i{ i % 5 == 2 })

0.upto 10 do |i|
  if flip_flop.(i)
    puts i
  end
end

# Prints 0, 1, 2, 5, 6, 7, and 10

```

## Rules

* Please include a brief example or description of how your solution works.
* Since not all languages have first-class functions, the definition of "predicate" is loose. You could take the names of previously-defined functions to be called or a string to be eval'd, for example. Your solution may not, however, just take primitive values like `true` and `false`. It must be your language’s equivalent of a higher-order function.
* Your predicate functions should take at least one argument, of any type that's convenient, as long as it's reasonable. (A predicate that only takes the specific value `1` is not reasonable, for example.)
* Built-ins are allowed, but only if they fit the spec (it must be a function or similar, etc.). You can’t post **Ruby, 2 bytes, `..`**.
* Default I/O rules apply, standard rules apply, and standard loopholes are forbidden.
* This is code golf. Shortest answer in bytes wins.

# Answer
> 8 votes
# JavaScript (ES6), 26 bytes

Expects `[ first_predicate, second_predicate ]`, where both predicates are functions taking a single parameter.

Returns a flip-flop function which itself returns either 0 or 1.

```
(p,k=0)=>v=>k|(k^=p[k](v))

```

Try it online!

### Commented

```
(                  // flip-flop generator taking:
  p,               //   p[] = pair of predicate functions
  k = 0            //   k   = flip-flop status, initialized to 0
) =>               //
  v =>             // anonymous function taking a parameter v
    k | (          //   always return 1 if k is already set
                   //   (because we must still return 1 when the 2nd
                   //   predicate is triggered)
      k ^= p[k](v) //   toggle k if the result of p[k](v) is true
    )              //

```

# Answer
> 6 votes
# Python, 59 bytes

```
lambda a,b:lambda x,t={0}:t.add((o:=t.pop()|a(x))>b(x))or o

```

Attempt This Online!

Anonymous function returning an anonymous function that keeps state in a mutable initialiser.

# Answer
> 5 votes
# Raku, 18 bytes

```
->\f,\g{&{f ff g}}

```

Try it online!

Raku has a built-in operator `ff` that does exactly what's asked for. My answer is mostly just setting up the functional plumbing around it.

* `-> \f, \g { ... }` is an anonymous subroutine taking two arguments.
* `&{ ... }` is the anonymous subroutine the top-level subroutine returns. Not having an explicit signature, it takes its argument in the topic variable `$_`, which the flip-flop operator implicitly checks against.
* `f ff g` returns false until the topic variable smartmatches against `f`, that is, `$_ ~~ f`, then keeps returning true until `$_ ~~ g`. Since `f` and `g` are functions, those smartmatches are equivalent to `f($_)` and `g($_)`.

# Answer
> 4 votes
# Factor, 33 bytes

```
[ '[ _ _ bi on t get swap off ] ]

```

Try it online!

Expects the false-making predicate first and the true-making predicate second.

* `[ ... ]` A quotation (anonymous function)...
* `'[ ... ]` ...that creates a quotation (anonymous function).
* `_ _` Slot the predicates into the holes.
* `bi` Call both predicates on the inner quotation's input value (integer).
* `on` Here's where it gets tricky. In Factor, you can use any value as a variable (key) to store something. So what I am doing here is using the result of the true-making predicate to store the value `t`. It's a little strange to use a canonical boolean value to store a possibly different boolean value, but this is code golf. It's not supposed to make sense, it's just supposed to be short.
* `t get` Get the value that is stored in `t`. This is the result that will be returned from the quotation. This must be done after storing the result of the true-making predicate but before storing the result of the false-making predicate in order to get the 'inclusive' behavior we are looking for.
* `swap` Bring the result of the false-making predicate to the top of the stack.
* `off` Store `f` in the result of the false-making predicate.

# Answer
> 4 votes
# , 54 bytes

```
{x=F;function(f,g)function(y){x<<-(z=x|f(y))&!g(y);z}}

```

Try it online!

(or 52 bytes using a global variable to save the current state)

---

# , 37 bytes (non-competing)

```
{x=F;function(f,g){x<<-(z=x|f)&!g;z}}

```

Try it online!

Doesn't fit the written spec of the challenge (the function `%..%` returns truthy/falsy, rather than a function), but it seems to very well mimic the described behaviour of Ruby's `..`.

Usage example (to mimic the Ruby example in the challenge):

```
for(i in 1:20){
    if((i==2)%..%(i==8))print(i)
}

```

# Answer
> 4 votes
# C (clang), 43 bytes

Reusable form as proposed by AZTECCO

```
#define f(x,a,b)static m;m|(m^=m?x b:x a)&&

```

Try it online!

# C (clang), ~~41~~ 40 bytes

-1 byte thanks to ceilingcat!

```
t;f(a(),b(),i,*r){*r=t|(t^=(t?b:a)(i));}

```

Try it online!

# Answer
> 3 votes
# Python, 76 bytes

*`-1 byte` thanks to `py3_and_c_programmer`*

Takes as input an element `i`, two lambda functions `a` and `b` while using a global variable `t` to toggle between the `true` & `false` cycles.

```
def f(i,a,b):
 global t
 if~t&a(i):t=1
 if t&b(i):t=0;return 1
 return t
t=0

```

Attempt This Online!

# Answer
> 3 votes
# Japt, ~~29~~ 13 bytes

```
Ï{T|(T^=YgXgT

```

Try it

Defines a function which accepts an array of predicates as its input, and returns the flip-flop function. Theoretically should work on strings, numbers, or arrays as the input for the predicate, but I've only tested with numbers.

```
Ï{T|(T^=YgXgT
              # Initialize T = 0
Ï             # Define a function with argument X (an array of predicates):
 {            #  Return a function with argument Y:
  T           #   Current value of T
   |          #   Bitwise OR
    (T^=      #   T XOR-equals the following:
          XgT #    Get the function in X at index T
        Yg    #    Apply it to Y

```

A 16 byte alternative doesn't use a global variable, so could be used to define multiple flip flops.

# Answer
> 3 votes
# Rust, 40 bytes

```
|f|{let mut t=0;move|x|t|{t^=f[t](x);t}}

```

Try it online!

An expression compatible with `fn([fn(T)->usize; 2])->impl Fn(T)->usize` for any `T`. (Yes I know `impl Trait` can't be used as a return type for `fn` pointers)

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

```
%2ṁ§≠²o⁰←ḣ

```

Try it online!

```
%2ṁ§≠²o⁰←ḣ      # 2-argument function,
                # which yields a partially-applied function
                # requiring 1 further argument:
         ḣ      # 1..further argument
  ṁ             # map over this and return sum
   §≠           # absolute differences between
     ²          # function arg2 applied to each element, and
      o⁰        # function arg1 applied to
        ←       # each element plus 1;
%2              # modulo 2.

```

Example usage `f₁₂₃ḣ20`

```
f               # filter
    ḣ20         # 1..20
                # keeping only truthy results of
 ₁              # function returned by function on line 1
                # called with arguments:
  ₂₃            # functions on line 2 and line 3

```

# Answer
> 3 votes
# C++ (clang), 64 bytes

```
[t=0](auto p){return[=](auto x)mutable{return t|(t^=p[t](x));};}

```

Port of @Arnauld's JavaScript answer.

Instead of `t` being a default parameter, it's captured and initialized to 0. The function returns a mutable lambda which captures this `t` by value along with the predicates container.

This other lambda (the closure) does the heavy lifting, it's declared mutable because it's member `t` will alternate between the values 0 and 1.

We could save a byte by making the predicates take an `int x` but it would no longer be generic.

Try it online!

# Answer
> 3 votes
# C# (.NET Core) ~~120~~ ~~117~~ 107 bytes

Here is a C# version based of the Dart and Go examples.

```
Func<Func<int,bool>,Func<int,bool>,Func<int,bool>>f=(l,r)=>{var s=1<0;return v=>l(v)?s=!s:r(v)?!(s=!s):s;};

```
* Shaved off 3 bytes by replacing `false` with `1<0` and a non needed space. Hat tip to jdt
* Shaved off 10 bytes by not doing boolean wizardry

Ungolfed main version:

```
var flipflop = new Func<Func<int,bool>, Func<int, bool>, Func<int,bool>> ( (condition1,condition2) => {
    var flipflop = false;
    return new Func<int,bool>(value => {
        if (condition1(value))
        {
            flipflop = !flipflop;
        } else if (condition2(value)) {
            flipflop = !flipflop;
            return true;
        }
        return flipflop;
    });
});

```

How you use it:

```
var flop = f(v => v == 2, v => v == 8);
for(var x = 0; x< 11; x++)
{
      if (flop(x)) {
        Console.WriteLine(x);
      }
}

```

Try it online!

# C# (.NET Core), 91 bytes

Using a delegate as proposed by jdt

```
delegate bool d(int i);Func<d,d,d>f=(l,r)=>{var s=1<0;return v=>l(v)?s=!s:r(v)?!(s=!s):s;};

```

Try it online!

# Answer
> 2 votes
# Go, 131 bytes, `int`s only

```
func m(l,r func(int)bool)func(int)bool{f:=1<0
return func(t int)bool{if!f&&l(t){f=!f;return f}
if f&&r(t){f=!f;return!f}
return f}}

```

Attempt This Online!

# Go, 132 bytes, generic

```
func m[T any](l,r func(T)bool)func(T)bool{f:=1<0
return func(t T)bool{if!f&&l(t){f=!f;return f}
if f&&r(t){f=!f;return!f}
return f}}

```

Attempt This Online!

This solution is fully generic for any type `T`.

### Ungolfed

```
func makeFlipFlop[T any](l,r func(T)bool) func(T)bool {
	flipped := false
	return func(t T)bool {
		if !flipped && l(t) {flipped = true; return true}
		if flipped && r(t) {flipped = false; return true}
		return flipped
	}
}

```

Attempt This Online!

# Answer
> 2 votes
# Dart, 42 bytes

```
f(f,s,[b=1<0])=>(i)=>b?b|(b=!s(i)):b=f(i);

```

You use it as:

```
void main() {
  var flipflop = f((i)=>i % 3 == 0, (i) => i % 7 == 0);
  for (var i = 1; i < 15; i++) {
    if (flipflop(i)) print(i);
  }
}

```

Which prints 3,4,5,6,7,9,10,11,12,13,14.

It even allows you to pass in an extra Boolean to make it the active state.

In a less horribly mangled and more typed version, it would be:

```
bool Function(T) flipflop<T>(bool Function(T) from, bool Function(T) until) {
  bool b = false;
  return (T value) {
    if (b) {
      b = !until(value);
      return true;
    }
    b = from(value);
    return b;
  }
}

```

# Answer
> 2 votes
# Nim, 100 bytes

```
import sugar
var s,t=off
proc f(x,y:int->bool):proc=(z:int)=>(s=s or z.x;t=s;s=s and not z.y;s or t)

```

Attempt This Online!

Works with `int`-typed inputs, uses a couple of globals to store the current and previous states.

Unfortunately, Nim doesn't let us omit type annotations, unless we are supplying the lambda directly as an argument to a higher-order function (as in test cases in the footer), so this ends up rather verbose. Importing syntax sugar macros `->` and `=>` allows getting rid of some repetitive annotations and thus, pays off by a few bytes.

As a bonus, Nim also allows defining operators, so that we can mimick Ruby's behavior precisely:

Attempt This Online!

# Answer
> 1 votes
# Pyth, 11 bytes

```
L+Z=?Z!PbOb

```

Try it online!

Pyth doesn't have any way to take functions as arguments, nor any way to return a function. So here we do the next best thing, which is to define a function which will implement the required behavior on the two functions `O` and `P`. That is to say that when we call `y` it will flip-flop on whatever `O` and `P` are defined as. The try it online link above links to a full working example which is the same as the first example in the question, I'll explain below.

```
DOdRqd2;                           define O(d): (d==2)
        DPdRqd8;                   define P(d): (d==8)
                L+Z=?Z!PbOb        implement y as the flip-floperator
                           VQyN    loop N over range(0,input()) and print the output of y(N)

```

And the actual flip-floperator

```
L              define y(b)
 +Z            sum of previous output and
    ?Z         ternary on previous output
      !Pb          not P(b) if Z currently True
         Ob        O(b) if Z currently False
   =           assign result of ternary to Z

```

# Answer
> 1 votes
# C++ (clang), ~~123~~ 101 bytes

```
struct F{int r=0;template<class A,class B>int operator()(A a,B b,int t){return r|(r^=r?b(t):a(t));}};

```

Try it online!

* actually we can go to 92 Bytes if we just implemented a class function *h* for example but it's no more exactly a closure.

Assumes predicates take int type, generalize also predicates will cost a few Bytes.
Due to implicit type conconversion can work with strings.

Struct *F* is a closure with operator () defined to behave flipFlop.

Saved 22 Bytes by templatizing operator () instead of the entire class.

Approach stolen from @Arnauld answer where *r* keeps the state of flipFlop.

# Answer
> 1 votes
# PHP 67 bytes

```
function f($i,$a,$b){static$k=0;$r=$k;return$r|$k^=($k?$b:$a)($i);}

```

$k must be copied to a temp variable because the `^=` is executed before the `|`,
although both operators are LTR.

Just define your two functions and give them to `f` as parameters within the loop.
The functions may be anonymous or named, or even predefined.

e.g.

```
# example 1
$a=function($i){return$i==2;}    $b=function($i){return$i==8;}
for($i=0;$i<=10;$i++) f($i,$a,$b) && print "$i ";

```

or

```
# example 2
function a($i){return$i%5==0;}    function b($i){return$i%5==2;}
for($i=0;$i<=10;$i++) f($i,'a','b') && print "$i ";
# important: function names must be quoted to avoid "undefined constant" error (in PHP 8)

```

or

```
# other example
for($i=0;$i<=10;$i++) f($i,'intval',function($i){return$i<5;) && print "$i ";
# prints 1 2 3 4 5 6 7 8 9 10
# ('$i<5' is irrelevant because testing 'intval' immediately resumes the printing)

```

Try it online

---
Tags: code-golf, functional-programming
---


# Question
Title: Counting from 1 to an Integer… in Binary
# Intro:

I remember, when I was a kid, I would get a calculator and keep on pressing the `+` button, and see how high I could count. Now, I like to program, and I'm developing for iOS.

Counting is a fundamental skill for both humans and computers alike to do. Without it, the rest of math can't be done. It's done simply by starting at `1` and repetitively adding `1` to it.

# The challenge:

This is but a simple challenge. What I would like your program to do is print from `1` to whatever `Integer` it takes in. However, I'll throw a twist in it, since decimal counting is kinda boring:

**The counting cannot be in base 10, it has to show itself counting in binary.**

So, to count to 5, using 32-bit integers, it would look like this:

```
0000 0000 0000 0000 0000 0000 0000 0001 ..... 1
0000 0000 0000 0000 0000 0000 0000 0010 ..... 2
0000 0000 0000 0000 0000 0000 0000 0011 ..... 3
0000 0000 0000 0000 0000 0000 0000 0100 ..... 4
0000 0000 0000 0000 0000 0000 0000 0101 ..... 5

```

It's a computer. They know binary best. Your input can be either a 32-bit or 64-bit integer. It is truly up to you. **However, if you use 32-bit integers, your output *must* be 32-bit integers *in binary*, and if you use 64-bit integers, your output *must* be 64-bit integers *in binary*.**

# Sample input:

a 32-bit integer, `5`

# Sample output:

```
0000 0000 0000 0000 0000 0000 0000 0001
0000 0000 0000 0000 0000 0000 0000 0010
0000 0000 0000 0000 0000 0000 0000 0011
0000 0000 0000 0000 0000 0000 0000 0100
0000 0000 0000 0000 0000 0000 0000 0101

```

# Scoring:

Your score is equal to however many bytes your code is. As this is Code Golf, lowest score wins.

## Bonus points:

If you show, in the output, the number it's at as a base 10 number (for example, `0000 0000 0000 0000 0000 0000 0000 0001` in binary is equal to the base 10 `1`), multiply your score by `0.8`.

If you group 4 digits of output like I did, then multiply your score by `0.8` (again). **This isn't required.**

Do not round up, and do not round down. Your score is a floating-point number.

# Good luck!

# Answer
## APL, 10 characters

Another on in APL. Assumes`⎕IO←1` (the default). No bonus points. Reads the number from the input device. If your APL uses 64 bit integers instead of 32 bit integers, substitute 64 for 32 as needed.

Notice that APL transparently converts to floating point numbers when the range of an integer is exceeded. It's hard thus to exactly say what integer size APL works with.

```
⍉(32⍴2)⊤⍳⎕

```

### explanation

```
2          ⍝ the number 2
32⍴2       ⍝ a vector of 32 twos.
(32⍴2)⊤X   ⍝ X represented as base 2 to 32 digits precision
⍳X         ⍝ a vector of the integers from 1 to X
⎕          ⍝ a number queried from the terminal
(32⍴2)⊤⍳⎕  ⍝ the output we want, flipped by 90°
⍉(32⍴2)⊤⍳⎕ ⍝ the output we want in correct orientation (⍉ is transpose)

```
> 14 votes

# Answer
# JavaScript (*ES6*) 56.8 (71\*0.8)

32 bit version, as JavaScript can not handle 64 bit precision (at most 53 bits using floating point doubles)

Without grouping

```
f=n=>{for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).slice(1),i)}

```

With grouping - score 60.16 (94\*.64)

```
f=n=>{for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).slice(1).match(/..../g).join` `,i)}

```

**Test** in any browser (ES5)

```
function f(n)
{
  for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).substr(1).match(/..../g).join(' '),i)
}

// Test
console.log = function(x,y) { O.innerHTML += x+' '+y+'\n' }
```

```
Count to: <input id=I><button onclick="O.innerHTML='';f(+I.value)">-></button>
<pre id=O></pre>
```
> 7 votes

# Answer
# Pyth, 18 * 0.8 * 0.8 = 11.52 bytes

```
VSQjd+c.[64.BN\04N

```

Example output:

```
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 1
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 2
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0011 3
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0100 4
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 5
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 6
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0111 7
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1000 8
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1001 9
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1010 10

```
> 6 votes

# Answer
# Pyth, 19 * 0.8 * 0.8 = 12.16 bytes

```
VSQjd+cjk.[032.BN4N

```

Example output for input 5:

```
0000 0000 0000 0000 0000 0000 0000 0001 1
0000 0000 0000 0000 0000 0000 0000 0010 2
0000 0000 0000 0000 0000 0000 0000 0011 3
0000 0000 0000 0000 0000 0000 0000 0100 4
0000 0000 0000 0000 0000 0000 0000 0101 5

```

Demonstration.
> 4 votes

# Answer
## Python 2, 48 * 0.8 = 38.4

```
i=0;exec"i+=1;print format(i,'032b'),i;"*input()

```

Converts a number to binary, uses string formatting to convert it to binary with 32 digits, and then also prints the decimal number for the bonus. Uses an `exec` loop to increment from `1` to the input value.
> 4 votes

# Answer
# CJam, 13.44 (21 × 0.64)

```
ri{)_2b64Ue[4/S*S@N}/

```

Try it online.
> 4 votes

# Answer
# APL, 23.68 (37 × .8 × .8)

```
{⎕←(⍕⍵),⍨⊃,/,/' ',⍨⍕¨8 4⍴(32⍴2)⊤⍵}¨⍳⎕

```
> 4 votes

# Answer
# KDB(Q), 50 * 0.8 * 0.8 = 32

I feel a bit sad with my submission :( There should be a better way to do this!

```
{-1{" "sv raze@'string(0N 4#0b vs x),x}@'1+til x;}

```

# Explanation

```
                                         1+til x     / counting
   {                                  }@'            / lambda each
                      (0N 4#0b vs x),x               / convert to binary and join with input
    " "sv raze@'string                               / convert to string, concatenate each string and join with space
{-1                                             ;}   / print and surpress output in lambda

```

# Test

```
q){-1{" "sv raze@'string(0N 4#0b vs x),x}@'1+til x;}5
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 1
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 2
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0011 3
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0100 4
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 5

```
> 3 votes

# Answer
# Common Lisp, 96.0

Score: `(* 150 .8 .8)`

```
(lambda(y)(flet((p(n &aux(x(format()"~39,'0b ~:*~d"n)))(dolist(p'(4 9 14 19 24 29 34))(setf(aref x p)#\ ))(princ x)(terpri)))(dotimes(i y)(p(1+ i)))))

```

## Example

Calling the function with 10:

```
0000 0000 0000 0000 0000 0000 0000 0001 1
0000 0000 0000 0000 0000 0000 0000 0010 2
0000 0000 0000 0000 0000 0000 0000 0011 3
0000 0000 0000 0000 0000 0000 0000 0100 4
0000 0000 0000 0000 0000 0000 0000 0101 5
0000 0000 0000 0000 0000 0000 0000 0110 6
0000 0000 0000 0000 0000 0000 0000 0111 7
0000 0000 0000 0000 0000 0000 0000 1000 8
0000 0000 0000 0000 0000 0000 0000 1001 9
0000 0000 0000 0000 0000 0000 0000 1010 10

```

## Explanation

`(format()"~39,'0b ~:*~d" #b101010101010)` gives:

```
"000000000000000000000000000101010101010 2730"

```

The intermediate string (an array) is modified to put a space character at the following zero-based indices: 4 9 14 19 24 29 34. Then it is printed.

Note that the apparently straightforward `(format t"~39,'0,' ,4:b ~:*~d" #b101010101010)` format does not do what we want. It prints:

```
00000000000000000000000001010 1010 1010 2730

```

(the padding is not grouped by 4)
> 3 votes

# Answer
# C, 97 * 0.8 * 0.8 = 62.08

```
a,x;main(b){for(scanf("%u",&b);a++<b;printf("%d\n",a))for(x=32;x--;)printf("%*d",x%-4-2,a>>x&1);}

```

Example output for input "5":

```
0000 0000 0000 0000 0000 0000 0000 0001 1
0000 0000 0000 0000 0000 0000 0000 0010 2
0000 0000 0000 0000 0000 0000 0000 0011 3
0000 0000 0000 0000 0000 0000 0000 0100 4
0000 0000 0000 0000 0000 0000 0000 0101 5
0000 0000 0000 0000 0000 0000 0000 0110 6
0000 0000 0000 0000 0000 0000 0000 0111 7
0000 0000 0000 0000 0000 0000 0000 1000 8
0000 0000 0000 0000 0000 0000 0000 1001 9

```

~~I could add one more whitespace character to separate the decimal numbers from the binary numbers, but technically the problem doesn't require it, I think?~~ EDIT: Thanks, CL!
> 3 votes

# Answer
# Ruby, 28 (35 * 0.8)

```
?1.upto(*$*){|x|puts"%.32b #{x}"%x}

```
> 3 votes

# Answer
# Octave, 23 characters

```
dec2bin(1:input(""),32)

```

Example output for input 5:

```
ans =
00000000000000000000000000000001
00000000000000000000000000000010
00000000000000000000000000000011
00000000000000000000000000000100
00000000000000000000000000000101

```
> 2 votes

# Answer
# Julia, 42 bytes

This is a bit shorter without the bonuses.

```
n->for i=1:n println(lpad(bin(i),64,0))end

```

This creates an unnamed function that takes an integer and prints the binary representation of each number from 1 to *n*, each left padded with zeros to 64 characters.

---

### With bonuses, 78 bytes * 0.8 * 0.8 = 49.92

```
n->for i=1:n for j=1:4:64 print(lpad(bin(i),64,0)[j:j+3]*" ")end;println(i)end

```

This creates an unnamed function that takes an integer and prints the binary representation as before, this time split into groups of 4 with the number in base 10 at the end.
> 2 votes

# Answer
# MatLab, 19 bytes

```
@(x)dec2bin(1:x,32)

```

Not too much to this one, MatLab has a built in decimal to binary converter and automatically prints the result.
> 2 votes

# Answer
# Common Lisp, score: 64.0

*100 bytes * 0.8 * 0.8*

I'm pretty happy with my score, but I still feel like there should be a possibility to simplify my code a bit.

## Output

```
0000 0000 0000 0000 0000 0000 0000 0001  1
0000 0000 0000 0000 0000 0000 0000 0010  2
0000 0000 0000 0000 0000 0000 0000 0011  3
0000 0000 0000 0000 0000 0000 0000 0100  4
0000 0000 0000 0000 0000 0000 0000 0101  5
0000 0000 0000 0000 0000 0000 0000 0110  6
0000 0000 0000 0000 0000 0000 0000 0111  7
0000 0000 0000 0000 0000 0000 0000 1000  8
0000 0000 0000 0000 0000 0000 0000 1001  9
0000 0000 0000 0000 0000 0000 0000 1010  10

```

## Code

```
(defun r(n)(dotimes(i n)(format t"~{~a~a~a~a ~}~a~%"(coerce(format()"~32,'0B"(1+ i))'list)(1+ i))))

```

## Explanation

As described in coredump's answer, the format string

```
"~32,'0B"

```

does output base2 numbers but there seems to be no possibility to get the grouping right as well. Hence I *coerce* the string into a list and iterate over it by picking out groups of 4 with this format string:

"~{~a~a~a~a ~}~a~%"

After each group of 4 there's a blank, and after the last group, the base10 number is printed.

## Without grouping (60x0.8 =\> 48.0)

```
(defun r(n)(dotimes(i n)(format t"~32,'0B ~:*~a~%"(1+ i))))

```

This uses ~:\* to process the (single) format argument again.
> 2 votes

# Answer
## PHP, 51.84 (81 × .8 × .8)

32-bit version, as PHP is limited to only 32-bit on Windows regardless of whether the OS is 64-bit.

Takes one command line argument.

```
for($i=0;$i++<$argv[1];)echo chunk_split(str_pad(decbin($i),32,0,0),4," ")."$i\n";

```
> 1 votes

# Answer
## CoffeeScript, 60.8 (76 × .8)

32-bit version for reasons mentioned above, as CoffeeScript compiles down to JavaScript.

```
f=(x)->console.log(("0".repeat(32)+i.toString 2).slice(-32),i)for i in[1..x]

```

With grouping it becomes slightly longer: 64.64 (101 × .8 × .8)

```
f=(x)->console.log(("0".repeat(32)+i.toString 2).slice(-32).match(/.{4}/g).join(" "),i)for i in[1..x]

```
> 1 votes

# Answer
# Haskell, 56 bytes

```
f n=putStr$unlines$take n$tail$sequence$replicate 32"01"

```

Usage:

```
*Main> f 5
00000000000000000000000000000001
00000000000000000000000000000010
00000000000000000000000000000011
00000000000000000000000000000100
00000000000000000000000000000101

```

For 64bit, replace the `32` with `64`. Every other number works, too.
> 1 votes

# Answer
## J, 20 bytes

```
(32#2)#:>:i.".1!:1<1

```

Sample input and output:

```
3
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

```
> 1 votes

# Answer
# Swift: 98.56 (154 * 0.8 * 0.8)

```
for x in 1...Int(Process.arguments[1].toInt()!){var p=String(x,radix:2)
let q=count(p)
for i in 0..<32-q{p=(((q+i)%4==0) ?"0 ":"0")+p}
println("\(p) \(x)")}

```
> 1 votes

# Answer
## Ruby, 64 bit

### 70 * 0.8 * 0.8 = 44.8 bytes (split, decimal)

```
1.upto(gets.to_i){|i|puts ("%064d"%i.to_s 2).scan(/.{4}/)*?\s+" #{i}"}

```

### 51 * 0.8 = 40.8 bytes (decimal)

```
1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2)+" #{i}"}

```

### 67 * 0.8 = 53.6 bytes (split)

```
1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2).scan/.{4}/}

```

### 44 bytes (no bonuses)

```
1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2)}

```
> 1 votes

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

```
Lb32jsäð0:»

```

-2 bytes thanks to *@Mr.Xcoder*.

Outputs without space-delimiter nor sequence-number.

Try it online.

**Explanation:**

```
L              # List of range [1,input]
               #  i.e. 5 → [1,2,3,4,5]
 b             # Convert each to a binary string
               #  i.e. [1,2,3,4,5] → ['1','10','11','100','101']
  32j          # Join everything together with a minimum length per item of 32,
               # which basically prepends spaces to make it length 32
               #  i.e. ['1','10','11','100','101'] → '                               1                              10                              11                             100                             101'
     sä        # Split it into the input amount of parts
               #  i.e. 5 → ['                               1','                              10','                              11','                             100','                             101']
       ð0:     # Replace every space with a 0
               #  i.e. '                             101' → '00000000000000000000000000000101'
          »    # Join everything together by newlines (and output implicitly)

```
> 1 votes

# Answer
# Japt `-R`, 6 bytes

```
õÈ¤ùTH

```

Try it

```
õÈ¤ùTH     :Implicit input of integer
õ          :Range [1,input]
 È         :Map each X
  ¤        :  To binary string
   ù       :  Left pad
    T      :    with 0
     H     :    to length 32
           :Implicit output joined with newlines

```

## With bonuses, 8.96 bytes

```
õÈ¤ùTH ò4 pX ¸

```

Try it

```
õÈ¤ùTH             :As above
       ò4          :Partitions of length 4
          pX       :Push X
             ¸     :Join with spaces

```
> 1 votes

# Answer
# JavaScript, 50 bytes

```
f=n=>n&&print(n.toString(2).padStart(32,0,f(n-1)))

```

Try it online!

## With first bonus, 41.6 bytes

```
f=n=>n&&print(n.toString(2).padStart(32,0,f(n-1)),n)

```

Try it online!

## With both bonuses, 44.8 bytes

```
f=n=>n&&print(...n.toString(2).padStart(32,0,f(n-1)).match(/.{4}/g),n)

```

Try it online!
> 1 votes

# Answer
# Vyxal `j`, ~~7~~ ~~6~~ 5 bytes

```
vΠ₆↳›

```

Try it Online!

The benefits of having built-ins to pad things with spaces and to convert spaces to 0s. Uses 64 bit integers.

~~two can play at the flag game Japt.~~

## Explained

```
vΠ₆↳›
vΠ      # Convert each number in the range [1, input] to binary
  ₆↳    # left pad each binary string with spaces so that it's length 32
    ›   # replace spaces with 0s
        # join on newlines because of `-j` flag

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Let's abbreviate those numbers! Now reverse?
**Introduction:**

Like Twitter and Instagram and others, I wanted to display numbers like `1.2K` and `3.8 M` instead of `1,222` or `3,823,456`.

But that's not all! As we all know, there might be some *human beings* which undoubtely won't like these abbreviations and will try to reverse them. So, `1.2k` will become `1,200` and `3.8 M` will become `3,800,000`.

**The task:**

* your task is to write a program or a function that converts a list of numbers (**which are given as strings**) into their abbreviate pairs and vice-versa.

For example, if the input list (or any `STDIN`) was `['1.4k', '1,234,567', '7.99M']`, then you should output:

```
['1,400', '1.2M', '7,990,000']

```

*You can follow the next schema for abbreviations:*

* 103 -\> one kilo -\> K
* 106 -\> one million -\> M
* 109 -\> one billion -\> B

Your code may assume all lowercase, all uppercase, mixed case or undefined case for input and use any of these for output, but should be consistent.

**Rules and restrictions:**

* you may write a program or function, taking input via `STDIN` (or closest alternative), command-line argument or function argument and outputting the result via `STDOUT` (or closest alternative), function return value or function (out) parameter.
* input may be in any convenient list or string format. You may assume that the `a<sub>i</sub>` are less than `2<sup>31</sup>` each and that the list contains at least one element.
* each abbreviated number will contain **only one** `.` while a normal number will contain **as many** `,` **as necessary** (you may assume that this numbers won't be altered).
* you **MAY NOT** enter a number as `'123456'` but rather `123,456`
* standard rules apply.

**Test cases:**

```
Input: ['1.5M', '77.6k', '123,456,789']         Output: ['1,500,000', '77,600', '123.4M']
Input: ['3,000,000,000', '581k', '2b']          Output: ['3B', '581,000', '2,000,000,000']
Input: ['0.1k']                                 Output: ['100']
Input: ['888', '33']                            Output: ['0.888k', '0.033k']

```

**Clarifications:**

* for numbers \< 1000 after the decimal point in abbreviation output you should have as many digits as required to get the correct result. (e.g: `2` -\> will become `0.002k`) - *that means 3 decimals at most*; for numbers \> 1000 you can have *a maximum of 1 decimal*.
* the abbreviation may be in both lower or upper case
* **I removed the built-ins restriction as suggested in the comments**

The shortest code in bytes wins!

# Answer
> 2 votes
# PHP, ~~234~~ ~~224~~ ~~213~~ ~~201~~ 205 bytes

```
for(;$x=$argv[++$n];){$y=str_replace(",","",$x)/1e3;for($i=0;$y>999;$i++)$y=($y|0)/1e3;echo(A<$c=substr($x,strlen($x)-1))?number_format($x*[k=>1e3,m=>1e6,b=>1e9][$c]):($i?($y*10|0)/10:$y).kmb[$i]," ";}

```

6 bytes saved by insertusernamehere, 4 bytes inspired by that.

---

* takes input from command line arguments, prints results space-separated with a trailing separator
* expects lower case abbreviation
* run with `-r`

-2 bytes if underscore as separator is ok: Replace `" "` with `_`.
-1 byte if correct rounding is ok: Replace `($y*10|0)/10` with `round($y,1)`.
-17 bytes for PHP 7.1: Replace `substr($x,strlen($x)-1)` with `$x[-1]`.

---

80 (63) bytes for expanding one argument only:

```
<?=number_format(($x=$argv[1])*[K=>1e3,M=>1e6,B=>1e9][substr($x,strlen($x)-1)]);

```

save to file, then execute (or replace `<?=` with `echo` +space and run with `-r`.

# Answer
> 3 votes
# 05AB1E, 67 bytes

```
…KMBU3L3*°Vε',Ku¤©ai¨®XY‡*ïR3ô',ýRëY/ʒ1@N_~}ε4°z+N_·Ì.ò¨0Ü'.ÜXNè«}θ

```

What a mess.. :/

Try it online.

**Explanation:**

```
…KMB                     # Push string "KMB"
    U                    # Pop and store it in variable `X`
3L                       # Push list [1,2,3]
  3*                     # Multiply each by 3: [3,6,9]
    °                    # Take 10 to the power each: [1000,1000000,1000000000]
     V                   # Pop and store it in variable `Y`
ε                        # Map over the (implicit) input-list:
 ',K                    '#  Remove all ","
    u                    #  Convert it to uppercase
 ¤                       #  Get the last character (without popping)
  ©                      #  Store this in variable `®` (without popping)
   ai                    #  If it's a letter:
     ¨                   #   Remove it from the string
      ®                  #   Push the letter from variable `®`
       XY‡               #   Transliterate it to the correct value in `Y` based on `X`
          *              #   Multiply the two numbers together
           ï             #   Cast it to an integer
     R                   #   Reverse it
      3ô                 #   Split it into parts of size 3
        ',ý             '#   Join it with "," delimiter
           R             #   Reverse it back
    ë                    #  Else:
     Y/                  #   Divide it by each value in list `Y`
       ʒ                 #   Filter this triplet by:
        1@               #    Check if it's >= 1
            ~            #    OR
          N_             #    The 0-based filter-index is 0
                         #    (so we'll still have a result left if <1000)
       }ε                #   After the filter: map over the remaining values:
         4°z+            #    Add 0.0001 to the number:
         4°              #     Push 10 to the power 4
           z             #     Divide 1 by this
            +            #     Add this 1/10000 to the number
         N               #    Push the 0-based map-index
          _              #    Check if it's 0 (1 if 0; 0 otherwise)
           ·             #    Double it (2 if 0; 0 otherwise)
            Ì            #    Increase by 2 (4 if 0; 2 otherwise)
             .ò          #    Round to that many decimals
               ¨         #    Remove the last digit
                0Ü       #    First trim potential trailing "0"
                '.Ü     '#    And then also trim a potential trailing "."
                   XNè«  #    Append the `N`'th letter of string `X`
        }θ               #   After the inner map: pop and leave the last item
                         # (after which the mapped list is output implicitly as result)

```

# Answer
> 2 votes
# JavaScript, ~~545~~ ~~524~~ ~~522~~ ~~518~~ ~~514~~ ~~508~~ ~~504~~ ~~498~~ ~~494~~ 214 bytes

Thanks to @ETHproductions for saving 180 bytes!

```
d=F=>F.map(f=>1/f.slice(-1)?f=(f=f.replace(/,/g,""))[9]?(f/1e8|0)/10+"B":f[6]?(f/1e5|0)/10+"M":f/1e3+"k":R(R(f.slice(0,-1)+"e"+' kMB'.indexOf(f.substr(-1))*3-0+"").match(/.{1,3}/g)+""),R=x=>[...x].reverse().join``)

```

To call the function:

```
d(["1.5M","1,500,000"]) //["1,500,500","1.5M"]

```

Outputs as `alert`, where each `alert` contains a different element of the input

Readable version:

```
d = F => F.map(f => 1 / f.slice(-1) ? f = (f = f.replace(/,/g, ""))[9] ? (f / 1e8 | 0) / 10 + "B" : f[6] ? (f / 1e5 | 0) / 10 + "M" : f / 1e3 + "k" : R(R(f.slice(0, -1) + "e" + ' kMB'.indexOf(f.substr(-1)) * 3 - 0 + "").match(/.{1,3}/g) + ""), R = x => [...x].reverse().join ``)

```

**Summary of edits:** converted function to an arrow function

* removed semi-colons ';'
* removed `var`
* converted to an arrow function
* used map to iterate through the individual elements of the array
* used `|0` instead of floor
* used regex for testing
* used ternary operators instead of if-else statements
* included a separate function for `.reverse().join''`

# Answer
> 2 votes
# Python, ~~322 321~~ 318 bytes

```
import math
def f(l,r=[]):
 for s in l:
  if(c:=s[-1])in(p:=' kMB'):r+=[f'{int(float(s[:-1])*10**(p.index(c)*3)):,}']
  elif(i:=int(s.replace(',','')))>999:
   if(l:=math.log10(i))<4.5:r+=[f'{round(i/1e3,1)}k']
   elif l<7.5:r+=[f'{round(i/1e6,1)}M']
   else:r+=[f'{round(i/1e9,1)}B']
  else:r+=[f'{i/1e3}k']
 return r

```

-3 thanks to jezza\_99

Attempt This Online!

# Answer
> 1 votes
# Python, ~~207~~ 203 bytes

```
lambda L:[s[-1]in'kMB'and f'{int(float(s[:-1])*10**(" kMB".index(s[-1])*3)):,}'or((i:=int(s.replace(',','')))>999>(j:=(i>1e6)+(i>1e9))and f'{(i/10**(j*3+2)+.5)//1/10}{"kMB"[j]}'or f'{i/1e3}k')for s in L]

```

Attempt This Online!

Similar to @TheThonnu's answer , but in a single line lambda and with sufficient differences that I feel it deserves a seperate answer

-4 bytes thanks to @97.100.97.109

---
Tags: code-golf
---


title: Sum of (at most) 5 primes

text:
# Question
Title: Sum of (at most) 5 primes
Terence Tao recently proved a weak form of Goldbach's conjecture! Let's exploit it!

Given an odd integer `n > 1`, write `n` as a sum of up to 5 primes. Take the input however you like, and give output however you like. For example,

```
def g(o):
    for l in prime_range(o+1):
        if l == o:
            return l,
        for d in prime_range(l+1):
            for b in prime_range(d+1):
                if l+d+b == o:
                    return l,d,b
                for c in prime_range(b+1):
                    for h in prime_range(c+1):
                        if l+d+b+c+h == o:
                            return l,d,b,c,h

```

is Sage code that takes an integer as input, and returns a list of integers as output whose sum is `n`. By Tao's theorem, this will always terminate!

**Input**

An odd integer `n`. You decide how to take the input, but if it's weird, explain it.

**Output**

Rather open-ended. Return a list. Print a string. Gimme one, a few, or all. Leave crap lying around on the stack (GS, Piet, etc) or in a consecutive (reachable) memory block (BF, etc) in a predictable manner. For these later cases, explain the output. In all cases, what you return / print / whathaveyou should be a straightforward representation of a partition of `n` into primes with fewer than 6 parts.

**Scoring**

This is code golf, smallest byte count wins.

**Bonus!** if the word 'goldbach' appears as a subsequence (not necessarily consecutive; just in order. Case doesn't matter) of your program subtract 8 points. The code above is an example of this.

# Answer
## , 29

```
(#~y=+/@>),{5$<0,p:i._1 p:>:y

```

Assumes input is in `y`. Value of expression is list of boxes of list of 5 primes or 0 that sum to `y`.

```
   y =. 16
   (#~y=+/@>),{5$<0,p:i._1 p:>:y
+----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------...
|0 0 0 3 13|0 0 0 5 11|0 0 0 11 5|0 0 0 13 3|0 0 2 3 11|0 0 2 7 7|0 0 2 11 3|0 0 3 0 13|0 0 3 2 11|0 0 3 11 2|0 0 3 13 0|0 0 5 0 11|0 0 5 11 0|0 0 7 2 7|0 0 7 7 2|0 0 11 0 5|0 0 11 2 3|0 0 11 3 2|0 0 11 5 0|0 0 13 0 3|0 0 13 3 0|0 2 0 3 11|0 2 0 7 7|0 2 0 ...
+----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------...

```

Not enough letters to earn any bonus points.
> 4 votes

# Answer
### *Mathematica*, 38

```
IntegerPartitions[n,5,Prime~Array~n,1]

```
> 9 votes

# Answer
## C, 192-8 = 184 chars

Contains "Goldbach" consecutively (excluding punctuation), and "Tao" as well.
When the sum is less than 5 primes (i.e. always), prints zeros (16 = `0+0+0+3+13`)
Read the number from standard input: `echo 30 | ./prog`.

```
#define T(x)for(x=0;x<=s;b=&x,c(++x))
G,o,l,d,*b,a;c(h)
{(*b-1?h<3:++*b)||c(*b%--h?h:++*b);}
main(s){
    scanf("%d",&s);
    T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a));
}

```

Old version (179 chars), which can find only sums of exactly 5 primes (and therefore fails for x\<10):

```
#define T(x)for(x=2;x<s;b=&x,c(++x))
G,o,l,d,*b,a;c(h)
{h<3||c(*b%--h?h:++*b);}
main(s){
    scanf("%d",&s);
    T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a));
}

```

Explanation:
`c` sets `*b` to the next prime (including `*b` itself if it's prime).
`T` builds a for loop, which advances one of the variables `G,o,l,d,a` to the next prime.
Within all for loops, we check if the sum matches, and print&exit if it does.
> 8 votes

# Answer
# Brachylog, 9 bytes

```
~+.ṗᵐl≤5∧

```

Try it online!

```
~+.          Output (.) should sum to the input,
   ṗᵐ        consist of all primes,
     l≤5     and have length ≤ 5.
        ∧    (Don't unify that 5 with the implicit output variable.)

```
> 8 votes

# Answer
## Ruby ~~138~~ ~~124~~ 117 - 8 = 109

```
require'mathn'
def g(o,l=[])
p l if l.inject(:+)==o#db
(l.last||1..o).each{|d|d.prime?and g(o,l+[d])if l.count<5}
end

```

Call with `g(<number>)`. Sample output:

```
[2, 2, 2, 2, 19]
[2, 2, 3, 3, 17]
[2, 2, 3, 7, 13]
...

```

Test: http://ideone.com/rua7A
> 4 votes

# Answer
## PHP ~~143~~ 122 - 8 = 114

*EDIT: Saved a few bytes on output, removed the explicit function call.*

```
<?function g($o,$l,$d,$b){for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));)echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b
";}

```

Unrolled:

```
<?
function g($o,$l,$d,$b){
  for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));)
    echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b
";}

```

Call with `@g(<number>);` Sample output for `n=27`:

```
2,2,2,2,19
2,2,3,3,17
2,2,3,7,13
2,2,5,5,13
2,2,5,7,11
2,2,23
2,3,3,19
2,3,5,17
2,3,11,11
2,5,7,13
2,7,7,11
3,3,3,5,13
3,3,3,7,11
3,3,5,5,11
3,3,7,7,7
3,5,5,7,7
3,5,19
3,7,17
3,11,13
5,5,5,5,7
5,5,17
5,11,11
7,7,13

```
> 2 votes

# Answer
# Ruby 2 -rmathn, 66 bytes - 8 = 58

```
g=->o,*l{o==l.reduce(:+)?p(l):l[5]||b=Prime.each(o){|x|g[o,*l,x]}}

```

Heavily based on GolfWolf's answer, but since it's 6 years old I'm going to post my own instead of nitpicking. Advances in technology include the stabby lambda, using `reduce` instead of `inject` for the free `d`, a terse way of stopping at partitions of 5, and `Prime.each(o)`, which iterates over all primes less than or equal to `o` (and furnishes an `ach`). Maybe in another 6 years there'll be a better way of using the `b`.
> 2 votes

# Answer
### Scala 137-8=129

```
def g(o:Int)={val l=0+:(2 to o).filterNot(d=>(2 to d-1).exists(d%_==0))
for(b<-l;a<-l;c<-l;h<-l;e<-l;if(b+a+c+h+e==o))yield{(b,a,c,h,e)}}

```

After boothby's hint: eliminated one function call, allow to interpret 3 as the sum of 3 and nothing, remove input from output - saves another 20 chars.

Bonus emphasizing:

> def **g(o**:Int)={val **l**=0+:(2 to o).filterNot(**d**=\>(2 to d-1).exists(d%\_==0)) for(b\<-l;a\<-l;c\<-l;h\<-l;e\<-l;if(b+a+c+h+e==o))yield{(**b,a,c,h**,e)}}

Invocation and result:

```
println (l(17))
Vector((17,0,0,2,2,13), (17,0,0,2,13,2), (17,0,0,3,3,11), ...

```

The output repeats x for every list to sum up to x, and then shows the 5 summands. 0 for missing summand, i.e. 2+2+13.

Ungolfed:

```
// see if there is some x, such that o%x is 0.
def dividable (o:Int) = (2 to o-1).exists (x=> o % x == 0)

// +: is a kind of cons-operator for Vectors
def primelist (d: Int) = {
  val s = 0 +: (2 to d).filterNot (b => dividable (b))
  for (a <- s;
    b <- s;
    c <- s;
    h <- s;
    e <- s;
    if (a+b+c+h+e == d)) yield {(a,b,c,h,e)}
}

```
> 1 votes

# Answer
# MuPAD 113 - 8 = 105

```
g:=[0,ithprime(i)$i=1..n]:f:=_for_in:f(l,g,f(d,g,f(b,g,f(a,g,f(c,g,if l+d+b+a+c=n then print(l,d,b,a,c)end)))))

```

This version will also print all permutations of every solution:

```
0, 0, 0, 0, 7
0, 0, 0, 2, 5
0, 0, 0, 5, 2
0, 0, 0, 7, 0
0, 0, 2, 0, 5
...

```

And yes, it creates a way too long list `g`. Who cares? :-)

Ungolfed version:

```
g:=[0].select([$1..n],isprime):
for l in g do
  for d in g do
    for b in g do
      for a in g do
        for c in g do
          if l+d+b+a+c=n then print(l,d,b,a,c); end;
        end
      end
    end
  end
end

```
> 1 votes

# Answer
# Jelly, 19 bytes (but very slow -- advice wanted)

```
ÆR;0x5Œ!ḣ€5¹©S€i³ị®

```

Try it online!

```
ÆR;0x5Œ!ḣ€5¹©€i³ị®     main link, takes one argument N
ÆR                     get all the primes less than N
  ;0x5                 add zero, and then repeat the entire list 5 times
      Œ!               get all the permutations of this huge list (takes a long time!)
        ḣ€5            for each permutation, just take the first 5 numbers
                       (this gives us all possible length-5 combinations of the primes plus zero, with some repeats)
           ¹©          save that list to register
              S€       take the sum of every permutation in the list...
                i³     and find the index of our first argument N in that list of sums
                  ị®   then recall our list of permutations, and get the correct permutation at that index!

```

If you have any ideas to make it faster and shorter, please let me know!
> 1 votes

# Answer
# Vyxal, 9 bytes

```
Ṅ'L5≤næA∧

```

Try it Online!

Outputs all possible sums.

## Explained

```
Ṅ'L5≤næA∧   # Takes a single integer n and returns a list of lists
Ṅ           # Push all the integer partitions (ways to sum to) of n
 '          # and keep only those where:
  L5≤       #   the length of the partition is less than or equal to 5 (can also be 6<)
        ∧   #   and
     næA    #   all integers in the partition are prime

```
> 0 votes

# Answer
# Japt, 19 bytes

Hideous, and slow as hell! Will crap out on inputs higher than 5.

```
ÆõÃc fj à l§5 æ@¶Xx

```

Try it

```
ÆõÃc fj à l§5 æ@¶Xx     :Implicit input of integer U
Æ                       :Map the range [0,U)
 õ                      :  Range [1,U]
  Ã                     :End map
   c                    :Flatten
     f                  :Filter
      j                 :  Prime
        à               :Combinations
          l             :Filter by length
           §5           :  <=5
              æ         :Get the first to return true
               @        :When passed through the following function as X
                ¶       :  U is equal to
                 Xx     :  Sum of X

```
> 0 votes

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


title: Lily pad jumping

text:
# Question
Title: Lily pad jumping
In this challenge, you need to simulate a frog jumping back and forth on lily pads. The pond is infinitely big, has a line of an infinite number of lily pads, and the frog can jump across as many lily pads as he likes.

This frog likes to jump back and forth: **after jumping forward, he always jumps backwards**, and vice versa.

You are passed a list of integers, which represents his jumps. You need to output the result of his jumps.

For example, say you are passed `[2,3,6,8,2]`:

Our frog starts by jumping 2 lily pads forward:

```
_2

```

Then 3 lily pads back:

```
3__2

```

Then 6 lily pads forward:

```
3__2__6

```

8 back:

```
8_3__2__6

```

Then finally, 2 lily pads forward (notice how the 2 overwrites the 3):

```
8_2__2__6

```

To be more explicit: Your input is an an array of numbers `S`, you need to output `S[K]` at the position `S[K] - S[K-1] + S[K-2] - S[K-3]...`.

* If multiple numbers are to be printed at a certain location, print only the one with the highest index.
* You are to use `_` if a particular location is empty
* If a number has multiple digits, it does not take up multiple locations. (In other words, a location can consist of multiple characters)
* You can assume that your list is non-empty, and that all integers are greater than 0.

# Test cases:

```
5                   ____5
2,2                 2_2
4,3,2,1             3124
5,3,2,1             _3125
2,3,6,8,2           8_2__2__6
10,3,12,4,1,12,16   ___12__3__10____41__1216
100,4,7,2,2         _______________________________________________________________________________________________4___1002_2

```

This is a , so answer it in as few characters as possible!

# Answer
> 10 votes
# MATL, ~~35~~ 34 bytes

*Thanks to @Emigna for saving 1 byte!*

```
32Oittn:oEq*Yst1hX<-Q(Vh' 0'95ZtXz

```

Try it online! Or verify all test cases.

### How it works

*Golf your code, not your explanations!*

The following uses input `[2,3,6,8,2]` as an example. To see intermediate results in the actual code, you may want to insert a `%` (comment symbol) to stop the program at that point and see the stack contents. For example, this shows the stack after statement `Ys` (cumulative sum).

```
32       % Push 32 (ASCII for space)
O        % Push 0
i        % Input array
         % STACK: 32, 0, [2,3,6,8,2]
t        % Duplicate
         % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2]
tn:      % Push [1 2 ... n] where n is length of input array
         % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,2,3,4,5]
o        % Modulo 2
         % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,0,1,0,1]
Eq       % Multiply by 2, subtract 1
         % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,-1,1,-1,1]
*        % Multiply elementwise
         % STACK: 32, 0, [2,3,6,8,2], [2,-3,6,-8,2]
Ys       % Cumulative sum
         % STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1]
         % The top-most array is the positions where the entries of the second-top
         % array will be written. But postions cannot be less than 1; if that's
         % the case we need to correct so that the minimum is 1. If this happens,
         % it means that the frog has gone further left than where he started
t        % Duplicate
1hX<     % Append 1 and compute minimum. So if the original minimum is less than 1
         % this gives that minimum, and if it is more than 1 it gives 1
         % STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1], -3
-        % Subtract
         % STACK: 32, 0, [2,3,6,8,2], [5 2 8 0 2]
Q        % Add 1
         % STACK: 32, 0, [2,3,6,8,2], [6 3 9 1 3]
(        % Assign values (top array) to specified positions (second-top) into array
         % which contains a single 0 (third-top). Newer values overwrite earlier
         % values at the same position
         % STACK: 32, [8 0 2 0 0 2 0 0 6]
V        % Convert to string. This produces spaces between the numbers
         % STACK: 32, '8 0 2 0 0 2 0 0 6'
h        % Concatenate with initial 32 (space). This converts to char
         % STACK: ' 8 0 2 0 0 2 0 0 6'
         % Thanks to this initial space, all zeros that need to be replaced by '_'
         % are preceded by spaces. (In this example that initial space would not
         % be needed, but in other cases it will.) Other zeros, which are part of
         % a number like '10', must not be replaced
' 0'     % Push this string: source for string replacement
         % STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 '
95       % Push 95 (ASCII for '_'): target for string replacement
         % STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 ', 95
Zt       % String replacement
         % STACK: ' 8_2__2__6'
Xz       % Remove spaces. Implicit display
         % STACK: '8_2__2__6'

```

# Answer
> 5 votes
# , ~~100~~ ~~97~~ 96 bytes

```
function(x){p=cumsum(x*c(1,-1))[seq(x^0)]
p=p+max(1-p,0)
v=rep('_',max(p));v[p]=x
cat(v,sep='')}

```

Try it online!

Line 1 finds all positions where to jump. First, all jumps in `x` are multiplied by 1 or −1 and then transformed to final positions using cumulative summation. The vector `c(-1,1)` is recycled if necessary, however, when `x` is of length 1, `x` is recycled instead. Therefore only `seq(x^0)` (equivalent to `seq_along(x)`) sums are considered. (A warning is generated when the length of `x` is not a multiple of 2 but it does not affect the result)

Line 2 increases the jumping positions so that all are at least 1.

Lines 3 and 4 create the output and print it.

*−1 byte from Giuseppe*

# Answer
> 4 votes
# PHP, ~~100~~ ~~101~~ ~~99~~ 104 bytes

```
for($p=-1;$d=$argv[++$k];+$i<$p?:$i=$p,$x>$p?:$x=$p)$r[$p+=$k&1?$d:-$d]=$d;for(;$i<=$x;)echo$r[$i++]?:_;

```

takes input from command line arguments; run with `-nr`.

**breakdown**

```
for($p=-1;          // init position
    $d=$argv[++$k]; // loop $d through command line arguments
    +$i<$p?:$i=$p,          // 3. $i=minimum index
    $x>$p?:$x=$p            // 4. $x=maximum index
)
    $r[
        $p+=$k&1?$d:-$d     // 1. jump: up for odd indexes, down else
    ]=$d;                   // 2. set result at that position to $d
for(;$i<=$x;)           // loop $i to $x inclusive
    echo$r[$i++]?:_;        // print result at that index, underscore if empty

```

# Answer
> 4 votes
## JavaScript (ES6), ~~99~~ 107 bytes

*Edit: Because the OP clarified that the only limit should be the available memory, this was updated to allocate exactly the required space instead of relying on a hardcoded maximum range.*

```
f=(a,x='',p=M=0)=>a.map(n=>x[(p-=(i=-i)*n)<m?m=p:p>M?M=p:p]=n,i=m=1)&&x?x.join``:f(a,Array(M-m).fill`_`,-m)

```

### How it works

This function works in two passes:

* During the first pass:

+ The 'frog pointer' `p` is initialized to `0`.
    + The `x` variable is set to an empty string, so that all attempts to modify it are simply ignored.
    + We compute `m` and `M` which are respectively the minimum and maximum values reached by `p`.
    + At the end of this pass: we do a recursive call to `f()`.
* During the second pass:

+ `p` is initialized to `-m`.
    + `x` is set to an array of size `M-m`, filled with `_` characters.
    + We insert the numbers at the correct positions in `x`.
    + At the end of this pass: we return a joined version of `x`, which is the final result.

### Test cases

```
f=(a,x='',p=M=0)=>a.map(n=>x[(p-=(i=-i)*n)<m?m=p:p>M?M=p:p]=n,i=m=1)&&x?x.join``:f(a,Array(M-m).fill`_`,-m)

console.log(f([5]));                  // ____5
console.log(f([4,3,2,1]));            // 3124
console.log(f([5,3,2,1]));            // _3125
console.log(f([2,3,6,8,2]));          // 8_2__2__6
console.log(f([10,3,12,4,1,12,16]));  // ___12__3__10____41__1216
console.log(f([100,4,7,2,2]));        // _..._4___1002_2
```

# Answer
> 4 votes
# Jelly,  ~~28~~  24 bytes

-2 (and further allowing another -2) thanks to FrownyFrog (use the \[post-challenge\] functionality of the prefix application quick, `Ƥ`)

```
ṚƤḅ-µCṀ»0+µṬ€×"³Ṛo/o”_;⁷

```

**Try it online!** Full program, for a test suite using the same functionality, click here.

### How?

```
ṚƤḅ-µCṀ»0+µṬ€×"³Ṛo/o”_;⁷ - Main link: list a       e.g. [ 5, 3, 2, 1]
 Ƥ                       - prefix application of:
Ṛ                        -  reverse                e.g. [[5],[3,5],[2,3,5],[1,2,3,5]]
   -                     - literal minus one
  ḅ                      - from base (vectorises)  e.g. [ 5, 2, 4, 3]=
    µ                    - start a new monadic chain - call that list c
                         - [code to shift so minimum is 1 or current minimum]
     C                   - complement (vectorises) e.g. [-4,-1,-3,-2]
      Ṁ                  - maximum                 e.g.     -1
       »0                - maximum of that & zero  e.g.      0
         +               - add to c (vectorises)   e.g. [ 5, 2, 4, 3]
          µ              - start a new monadic chain - call that list d
           Ṭ€            - untruth €ach            e.g. [[0,0,0,0,1],[0,1],[0,0,0,1],[0,0,1]]
               ³         - the program input (a)
             ×"          - zip with multiplication e.g. [[0,0,0,0,5],[0,3],[0,0,0,2],[0,0,1]]
                Ṛ        - reverse                      [[0,0,1],[0,0,0,2],[0,3],[0,0,0,0,5]]
                 o/      - reduce with or          e.g. [0,3,1,2,5]
                    ”_   - '_'
                   o     - or (replace 0 with '_') e.g. ['_',3,1,2,5]
                      ;⁷ - concatenate a newline   e.g. ['_',3,1,2,5, '\n']
                         - implicit print

```

Notes:

The final concatenation of a newline, `;⁷` is for cases when no `_` appear in the output, in which case the implicit print would display a representation of the list, e.g. `[3, 1, 2, 4]`, rather than something like the example, `_3125`. For no trailing newline one could replace `;⁷` with `;““` to append a list of character lists, `[[''],['']]` (no close  required as it's the last character of a program).

The untruth function, Ṭ, gives a list with `1`s at the indexes in it's input, for a single natural number, **n** that is **n-1** `0`s followed by a `1` allowing the input numbers to be placed at their correct distance from the left by multiplication. The reversal, , is required to have *later* frog-visits overwrite rather than *earlier* ones when the reduction with or, `o/`, is performed.

# Answer
> 3 votes
# Perl 6, ~~68~~ 67 bytes

```
{(my @a)[[[\+] |(1,-1)xx*Z*$_].&{$_ X-min 1,|$_}]=$_;[~] @a X//"_"}

```

Try it online!

### How it works

First it determines the cumulative jump locations:

```
[[\+] |(1,-1)xx*Z*$_]
                  $_  # Input array.          e.g.  2, 3, 6, 8, 2
      |(1,-1)xx*      # Infinite sequence:          1,-1, 1,-1, 1...
                Z*    # Zip-multiplied.       e.g.  2,-3, 6,-8, 2
 [\+]                 # Cumulative addition.  e.g.  2,-1, 5,-3,-1

```

Then it turns them into 0-based array indices by subtracting the minimum number (but at most 1) from all the numbers:

```
.&{$_ X-min 1,|$_}    #                       e.g.  5, 2, 8, 0, 2

```

Then it creates an array with the input numbers assigned to those indices:

```
(my @a)[   ]=$_;      #                       e.g.  8, Nil, 2, Nil, Nil, 2 Nil, Nil, 6

```

Finally it concatenates the array to a string, with the underscore in place of undefined elements:

```
[~] @a X//"_"         #                       e.g.  8_2__2__6

```

# Answer
> 3 votes
# Javascript (ES6), 109 bytes

```
f=x=>x.map((y,i)=>o[j=(j-=i%2?y:-y)<0?o.unshift(...Array(-j))&0:j]=y,o=[],j=-1)&&[...o].map(y=>y||'_').join``
```

```
<!-- snippet demo: -->
<input list=l oninput=console.log(f(this.value.split(/,/)))>
<datalist id=l><option value=5><option value="4,3,2,1"><option value="5,3,2,1"><option value="2,3,6,8,2"><option value="10,3,12,4,1,12,16"><option value="100,4,7,2,2"></datalist>
```

### Commented:

```
f=x=>x.map((y,i)=>o[j=(j-=i%2?y:-y)<0?o.unshift(...Array(-j))&0:j]=y,o=[],j=-1)&&[...o].map(y=>y||'_').join``
                /* initialize output array [] and index j at -1: */  o=[],j=-1
     x.map((y,i)=> /* iterate over all items in input x (y=item, i=index) */  )
                      (j-=i%2?y:-y) /* update j +/-y based on if index i is odd */
                                   <0? /* if resulting j index is less than zero */
                                      o.unshift(...Array(-j)) /* prepend -j extra slots to the output array */
                                                             &0 /* and give result 0 */
                                                               :j /* else give result j */
                    j= /* assign result to j */
                  o[ /* assign y to output array at index j */   ]=y
   /* short-circuit && then spread output array to fill any missing entries */ &&[...o]
                                                      /* fill falsey slots with '_' */ .map(y=>y||'_')
                                                                         /* join with empty spaces */ .join``

```

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~45~~ 30 bytesSBCS

```
{∊⍕¨⍵@i⍴∘'_'⌈/1+i←(⊢-1⌊⌊/)-\⍵}

```

Try it online!

`-\⍵` scan the argument with alternating `-` and `+`

`(⊢ - 1 ⌊ ⌊/)` from that () subtract 1 or the minimum (`⌊/`), whichever is smaller ()

`i←` assign to `i`

`⌈/ 1+` increment and take the maximum

`⍴∘'_'` produce that many underscores

`⍵@i` put the numbers from the argument () at positions `i`

`∊⍕¨` format each and flatten

# Answer
> 1 votes
# Ruby, 85 bytes

```
->a{i=1;j=c=0;a.map{|x|[c-=x*i=-i,x]}.to_h.sort.map{|x,y|[?_*[x+~j,0*j=x].max,y]}*''}

```

Try it online!

Records the positions after each jump, converts the resulting array to hash to remove duplicates (preserving the last value at each duplicated position), and then glues the values with the required amount of underscores.

# Answer
> 1 votes
# Python 2, ~~113~~ 110 bytes

```
J=input()
i=sum(J)
l=['_']*2*i
v=i,
d=1
for j in J:i+=d*j;d=-d;l[i]=`j`;v+=i,
print''.join(l[min(v):max(v)+1])

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 36 bytes

```
Z·'_иsvy®yNÈi+ë-}©ǝ®0‹i¤®Äиy0©ǝì]¤ÜJ

```

Try it online or verify all test cases.

**Explanation:**

```
Z               # Get the maximum of the (implicit) input-list (without popping)
 ·              # Double it
  '_и          '# Pop and push a list with 2*max amount of "_"
s               # Swap so the input-list is at the top
 v              # Loop over each of its integers `y`:
  y             #  Push the current integer `y`
  ®             #  Push integer `®` (-1 the first iteration)
   y            #  Push integer `y` again
    N           #  Push the 0-based loop-index
     Èi         #  If the index is even:
       +        #   Add the `y` to `®`
      ë         #  Else (the index is odd):
       -        #   Subtract the `y` from `®` instead
      }         #  Close the if-else clause
       ©        #  Store it as new `®` (without popping)
  ǝ             #  Insert the `y` at this index `®` in the "_"-list
                #  (no-op with pops if index `®` is out of bounds, e.g. negative)
  ®0‹i          #  If `®` is negative (<0):
      ¤         #   Push the last item "_" (without popping the list)
       ®Ä       #   Push the absolute value of `®`
         и      #   Pop both and push a list with that amount of "_"
          y     #   Push integer `y` again
           0    #   Push 0
            ©   #   Replace `®` with this 0 (without popping)
             ǝ  #   Insert the `y` at index 0 in the second "_"-list
              ì #   Prepend the two lists together
 ]              # Close both the if-statement and loop
  ¤             # Push the last item "_" again (without popping the list)
   Ü            # Trim all trailing "_" from the list
    J           # Join the list together
                # (after which the result is output implicitly)

```

`NÈi+ë-}` could alternatively be `„+-Nè.V` for the same byte-count: Try it online or verify all test cases.

```
    „+-         #  Push string "+-"
       Nè       #  (Modulair) index the loop-index into it
         .V     #  Evaluate and execute this character as 05AB1E code

```

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


title: How long until this date?

text:
# Question
Title: How long until this date?
The idea is this: Write a function to print the length of time from now/today's date (at the time the function is called) until a date supplied as an argument.

**Assumptions:**

* Input date will always be tomorrow or later, in the future.
* Input date will never be more than 10 years in the future.

**Rules:**

* Output must be in this format: "\[z year(s)\], \[x month(s)\], y day(s) until -Input Date-"
* Output time frame (day/month/year) must be pluralized correctly. i.e. `1 month`, not `1 months`
* Input can be in whichever date format *you* prefer (3/15/12 - March 15, 2012 - 2012.03.15).

**Example:** Assuming program is run on March 15, 2012:

* Input date of `3/20/12` = `5 days until 3/20/12`
* *NOT* Input date of `4/16/12` = `1 month, 1 days until 3/20/12`
* Input date of `2012.04.20` = `1 month, 5 days until 2012.04.20`
* *NOT* Input date of `2012.04.20` = `36 days until 2012.04.20`
* Input date of `10/31/17` = `5 years, 7 months, 16 days until 10/31/17`
* Input date of `3/15/13` = `1 year until 3/15/13`

This is code golf, so shortest length code wins.

I suppose for the sake of having a deadline, I will be selecting an answer on:

## March 23, 2012!

(This is my first CG question, so I'll be happy to correct any question errors on my part!)

# Answer
## R, 99 characters

I know it is sort of cheating, but R is all about its packages and lubridate is so convenient for this kind of tasks!

```
f=function(x){library(lubridate);cat(show(as.period(interval(mdy("3/15/2012"),mdy(x)))),"until",x)}

```

# Usage:

```
f("10/31/2017")
[1] 5 years, 7 months and 16 days
5 years, 7 months and 16 days  until 10/31/2017

```
> 3 votes

# Answer
# Python \+ `dateutil`, 331 bytes

```
from dateutil import*
from datetime import*
def f(s):
 if'/'in s:m,y,d=map(int,s.split('/'))
 else:y,m,d=map(int,s.split('.'))
 x=relativedelta.relativedelta(datetime(y,m,d),datetime.now())
 D,M,Y=x.days,x.months,x.years
 return f"{Y} year{'s'*(Y>1)}, "*(Y>0)+f"{M} month{'s'*(M>1)}, "*(M>0)+f"{D} day{'s'*(D>1)} "*(D>0)+"until "+s

```
> 2 votes

# Answer
## VBA: 766 631 Chars

Thanks to mellamokb for helping shorten up the string creation and `IIf`.

```
Function k(i)
e=" month"
g="s"
n=Now()
r=Month(n)
s=Month(i)
t=DateSerial(Year(i),s,1)
u=DateSerial(Year(i),s-1,1)
v=Day(n)
w=Day(i)
x=DateSerial(Year(n),r,1)
d=t-u-v+w
For y=0 To 10
If Year(DateAdd("yyyy",-1*y,i))=Year(n) Then Exit For
Next
y=IIf(s=1,y-1,y)
z=s-r
z=IIf(z<0,z+12,z)
For m=0 To z
If Month(DateAdd("m",-1*m,i))=r Then Exit For
Next
d=IIf(v<=w,w-v,d)
m=IIf(v>w,m-1,m)
If y Then a=y & " year" & Left(g,y-1)
a=IIf((m Or d) And y,a & ",",a)
If m Then b=IIf(d,m & e & Left(g,m-1) & ",",m & e & Left(g,m-1))
If d Then c=IIf(d>1,d & " days",d & " day")
k=Trim(Trim(a & " " & b) & " " & c) & " until " & i & "."
End Function

```

I know `VBA` definitely does not lend itself to code golfing as well as some other languages, but it's what I'm good (not expert) at. :-)

This has been a fun exercise for me!
> 1 votes

# Answer
## PHP, 315 characters

```
function p($z)
{
list($d,$m,$y)=explode("/",$z);
$d=$d-date("d");
$n=$m-1;
$m=$m-date("m")-($d<0);
$d=$d+($d<0)*($n>7^$n&1)+27+($n-2?3:($y%4?1:($y%100?2:($y%400?1:2))));
$y=$y-date("Y")-($m<0);
$s="s ";
echo ($y?$y." year".$s[$y<2]:"")." ".($m?$m." month".$s[$m<2]:"")." ".($d?$d." day".$s[$d<2]:"")." until ".$z;
}

```

Usage:

```
p("11/03/2006");

```

Takes dates in a `dd/mm/yyyy` format. I've used Griffin's month length calculation(again), though I had to stick extra brackets in it to make the precedence work properly. I've also left some line-breaks in to make it a little easier to read.
> 1 votes

# Answer
# Ruby (213)

takes dates in any format `Date.parse` accepts. Tried just with `yyyy-mm-dd`

```
def u s
t=Date.today
f=Date.parse s
[[0,'year'],[0,'month'],[0,'day']].map{|c,n| while t<f
c+=1
t=t.send"next_#{n}"
end
c,t=c-1,t.send("prev_#{n}")if t>f
[c,n+(c>1??s:'')]*' 'if c>0}.compact*', '+' until '+s
end

```

to also get weeks, add:

```
['prev_','next_'].each{|n|Date.send(:define_method,n+'week'){send n+'day',7}}

```

and `[0,'week'],` (between month and day). days will then always be `< 7`
> 1 votes

# Answer
# PHP, 151 chars

```
function p($z){$n=date_create(date('Y-m-d'));$d=date_create($z);$i=date_diff($n,$d);print($i->format('%R%y years, %m months, and %a days until '.$z));}

```
> 1 votes

# Answer
## JavaScript (ES6), 125 bytes

Since the answer by Paolo used an external library, I shall do the same. Node.js is all about NPM packages and moment \+ HumanizeDuration is so convenient for this task!

### Node environments

```
m=require('moment'),f=d=>console.log(require('humanize-duration')(m(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d)

```

### Browser environment

Since the libraries declare global variables, it's actually a bit shorter (102 bytes). It's not clear whether I need to include the script tags required to load in the third-party JavaScript, so I will count the Node one officially.

```
f=d=>console.log(humanizeDuration((m=moment)(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d)

```

---

## CoffeeScript, also 125 bytes

```
f=(d)->console.log require('humanize-duration')((m=require 'moment')(d).diff(m()),{units:['y','mo','d'],round:1})+' until '+d

```
> 1 votes

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