# Question
Title: Sum of multiples of powers of ten of an integer
Write a function to produce, for a non-negative integer, a string containing a sum of terms according to the following:

```
3 -> "3"

805 -> "800 + 5"

700390 -> "700000 + 300 + 90"

0 -> "0"

13 -> "10 + 3"

200 -> "200"

```

Any input other than a non-negative integer can be ignored. Zero terms must be skipped unless the input is 0. Terms must go from largest to smallest. The plus signs must have only a single space on either side.

This is code golf; fewest number of bytes wins.

# Answer
> 2 votes
# Jelly, 14 bytes

```
DḊƬḌINḟ0ȯ0j”+K

```

A full program which prints the result

**Try it online!**

### How?

```
DḊƬḌINḟ0ȯ0j”+K - Main Link: integer, n       e.g. 805
D              - to base ten                      [8,0,5]
  Ƭ            - collect until a fixed point:
 Ḋ             -   dequeue                        [[8,0,5],[0,5],[5],[]]
   Ḍ           - from base ten (vectorises)       [ 805,    5,    5,  0]
    I          - incremental differences          [    -800,   0,   -5 ]
     N         - negate                           [     800,   0,    5 ]
      ḟ0       - filter discard zeros             [     800,         5 ]
        ȯ0     - OR zero (replacing an empty list with 0)
          j”+  - join with '+' characters         [     800,  '+',   5 ]
             K - join with space characters       [800,' ','+',' ',5]
               - implicit, smashing print         "800 + 5"

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 31 bytesSBCS

Anonymous tacit prefix function, taking the number as a string.

```
(1↓∘∊1@1∘×⊆⌽∘⍳∘≢('+',10⊥↑)¨⊢)⍎¨

```

Try it online!

`⍎¨` execute each character (this gives the digits as numbers)

`(``)` apply the following anonymous tacit prefix function to that:

…`(``)¨⊢` apply the below function between each element and the corresponding element of…

the reversal
of
the **ɩ**ndices (1…N)
of
the tally of digits

take that many elements, padding with zeros (as there's only ever one)

`10⊥` evaluate that in base ten

`'+',` prepend a plus

… partition it beginning a new segment where indicated by:

`1@1` a one **at** the first element
of
`×` the sign (0 for 0; 1 for all other)

`1↓` drop the first
of
the **ϵ**nlisted (flattened) data

# Answer
> 1 votes
# Perl 5 `-p`, 53 bytes

```
$&&&push@a,$&.y//0/cr while s/.//;$"=" + ";$_="@a"||0

```

Try it online!

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


title: Tips for golfing in ///

text:
# Question
Title: Tips for golfing in ///
What general tips do you have for golfing in ///? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to /// (e.g. "remove unnecessary whitespace" is not an answer). Tips for itflabtijtslwi and Lines are on-topic and valid here as well.

Please post one tip per answer.

# Answer
> 9 votes
# Use `//` as a replacement

When you define a bunch of replacements, e.g.:

```
/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/

```

(65 bytes). You can use `//` as a replacement:

```
/~/\/\///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/

```

(61 bytes).

# Answer
> 6 votes
**When expanding on a basis and printing intermediate results, incorporate previous iterations in future ones**

That sounded a bit convoluted. What I mean might better be described using an actual answer. This challenge requires this specific output:

```
Steve Ballmer still does not know.
Steve Ballmer still does not know what he did.
Steve Ballmer still does not know what he did wrong.
Steve Ballmer still does not know what he did wrong with mobile.

```

One naive solution might be:

```
/1/Steve Ballmer still does not know//2/ what he did//3/ wrong//4/ with mobile./1.
12.
123.
1234

```

Notice how the pattern `1`, `12`,`123` ... is repeated? Well, not when you do this:

```
/1/Steve Ballmer still does not know//2/1 what he did//3/2 wrong//4/3 with mobile/1.
2.
3.
4.

```

*Once again, thanks go to Martin Ender for pointing this out!*

# Answer
> 4 votes
## Incomplete /// blocks are not printed

Note that this line of code

```
/Stack/Overflow//x/\//Stack/ignore/DoItyignore

```

prints only `Overflow` \- the part from `/ignore` onwards is not included in the output, because `///` only prints things in its third slash-part.

Try the incomplete block online!

It is however still considered by the replacer: if we were to inject a slash in there, things change:

```
/Stack/Overflow//x/\//Stack/ignore/doitxignore

```

Try that online!

Output here is `Overflowdoit`, because replacing `x` with `/` made it valid syntax.

# Answer
> 2 votes
# Use a character at the end of code to handle edge cases

When you have a piece of `///` code that handles all but one case, then you can use a character at the edge of the code to handle the edge case.

**Example:** Unary add two numbers together unless the second number is 7, in which case just output the first number.

Code that handles all but the "second number is 7" case:

```
/+//<INPUT 1>+<INPUT 2>

```

By adding a `*` to the end of the code, we can handle the edge case by replacing `+0000000*` with nothing (it is necessary to include the `+` to makes sure the number is not greater than 7). Make sure to include code at the end before the input to clean it up.

```
/+0000000*///+///*//<INPUT 1>+<INPUT 2>*

```

Try it online!

For a "real-world" example, I used this trick on some of the "Jimmy" problems:

---
Tags: code-golf, tips
---


title: Expand the number

text:
# Question
Title: Expand the number
You may remember in first or second grade using **expanded form** to learn about place value of numbers. It's easier to explain with an example, so consider the number `123`. In expanded form it is represented as `100 + 20 + 3`, which helps a young mind visualize place value. It is reminiscent of how you say it: one hundred (plus) twenty (plus) three.

We can extend this past the units place with decimals: `2.718 => 2 + 0.7 + 0.01 + 0.008`

Your challenge is to write a program or function that takes a positive floating point number or zero (assume it is as large or precise as your language can handle; it will not be in scientific notation) or string and prints/returns it in expanded form as explained above.

You need neither spaces between the `+`'s nor the zero before the decimal point, so the example above could be `2+.7+.01+.008`. Values that would be equal to zero must be omitted (`101.01 => 100 + 1 + 0.01`) unless the input is zero (see below).

Values should not have more than one leading zero before the decimal point or any trailing zeroes after it (no-no's: `0060, 0000.2, 30., 30.000, .0400`). The input will conform to this too.

Since first-graders have short attention spans, your code will have to be as short as possible.

## Test cases

```
0 => 0
6 => 6
0.99 => 0.9 + 0.09
24601 => 20000 + 4000 + 600 + 1
6.283 => 6 + 0.2 + 0.08 + 0.003
9000000.0000009 => 9000000 + 0.0000009

```

# Answer
> 6 votes
# CJam, ~~33~~ 26 bytes

```
r_ee\'0fe<f{\~t~}{},'+*0e|

```

This won't work with the Java interpreter; it print floats differently. Try it with the CJam interpreter.

The last test case prints `9000000+9e-7`, which has been ruled valid by @NinjaBearMonkey.

*Thanks to @jimmy23013 for golfing off 7 bytes!*

### How it works

```
r_                           Read a token from STDIN and push a copy.
  ee                         Enumerate its characters, i.e., push the array of all
                             [index character] pairs.
    \                        Swap the original input on top of the stack.
     '0fe<                   Perform vectorized minimum with the character '0'.
                             This replaces all digits with '0', but leaves '.'
                             untouched, since `.' < '0'.
          f{    }            For each [index character] pair, push the pair and the
                             string of zeroes and (possibly) a dot; then:
            \                    Swap the pair on top of the stack.
             ~                   Dump index and character on the stack.
              t                  Replace the string's element at that index with
                                 that character.
               ~                 Evaluate the resulting string.
                 {},         Filter the array to remove zeroes.
                    '+*      Join, using '+' as separator.
                       0e|   If the result is empty, replace it with 0.

```

# Answer
> 5 votes
# JavaScript (ES7), 102 bytes

```
n=>+n&&[...n.replace(/^\.0*|\./,"")].map(f=d=>10**p--*d,p=Math.floor(Math.log10(n))).filter(f).join`+`

```

## Explanation

Requires the number to be input as a string without leading zeroes (unless the number *is* `0` of course).

Note: Because of floating-point weirdness some numbers (like `.3`) come out wrong, but theoretically this works for any number.

```
n=>                             // n = input number as string
  +n&&                          // return 0 if n = 0
  [...n.replace(/^\.0*|\./,"")] // remove leading zeroes after the decimal place
  .map(f=d=>                    // for each digit d in n
      10**p--*d,                // raise the digit to the correct power of 10
    p=Math.floor(Math.log10(n)) // p = power of 10 for the first digit, floor needs to be
  )                             //     used instead of |0 due to negative powers of 10 :(
  .filter(f)                    // remove zeroes, the map function is reused
  .join`+`                      // return the output numbers joined with +

```

## Test

Test uses `Math.pow` instead of `**` for browser compatibility.

```
var solution = n=>+n&&[...n.replace(/^\.0*|\./,"")].map(f=d=>Math.pow(10,p--)*d,p=Math.floor(Math.log10(n))).filter(f).join`+`
```

```
<input type="number" oninput="result.textContent=solution(this.value)">
<pre id="result"></pre>
```

# Answer
> 5 votes
## Retina, ~~86~~ ~~77~~ 75 bytes

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

```
S_`.(?<=(\.\d+))|(?=(\d*)).
Tm`d`0`\..+\B|(?<=^\d).+
¶([.0]+¶)*
+
^0.|\+0$

```

The trailing linefeed is significant.

Try it online.

### Explanation

```
S_`.(?<=(\.\d+))|(?=(\d*)).

```

We start by turning the input into a linefeed separate list of components, although only the leading (or trailing) digit is correct. This is done by abusing a split stage. Instead of splitting the input we match all of it, so the remaining segments are all empty. We remove those empty segments with the `_` option. The catch is that split stages also return the values of all capturing groups. So we use a lookahead at each match to capture the correct part of the string: first we try to find a `.` left of the match. If that's the case, we capture everything from the `.` up to and including the digit we're currently matching. Otherwise, we must be in the integer part of the input, so we capture all the numbers after the match (including the match). We must also get rid of the decimal point itself, so the second capture is optional. If there are no `\d` to be capture, this will simply remove the match from the input.

```
Tm`d`0`\..+\B|(?<!=\d).+

```

Now we use a transliteration stage to turn all but the leading/trailing digits into zeroes. We either match a component that's less than 1 with `\..+\B` where the `\B` ensures that we stop the match one digit before the end, or we match an integer part with `(?<=^\d).+` where the lookbehind ensures that we start one digit into the number. The transliteration stage will then replace any digits (`d`) with zeroes inside the matches.

```
¶([.0]+¶)*
+

```

Now the actual output format should use `+` not linefeeds as separators. The  matches a linefeed to do that substitution. While we're at it, we also remove lines that contain only `0`s and `.`s.

```
^0.|\+0$

```

The previous stage does not remove a leading or trailing `0` (because those do not have a linefeed before and after them), so we remove those explicitly.

# Answer
> 4 votes
# Python 2, ~~216~~ ~~210~~ ~~196~~ 175 bytes

Here is some slightly golfed code that I will golf further when I get time. It uses string analysis.

```
i=input().split(".")
I=i[0]
e=enumerate
o=[(k+len(I[j+1::])*"0") for j,k in e(I) if k!="0"]
try:o+=["."+l*"0"+m for l,m in e(i[1]) if m!="0"]
except:0
print "+".join(o or"0")

```

**Explanation**

So, the input is seperated into a integer and decimal part. Then, there is a for loop list comprehension. On the integer part, the length of the string after a character in the decimal is multiplied by "0" to get that many zeros at the end if that character.

For the decimal part, the index of the current character is the number of zeros before it and so that part is simple.

The try and except is used to determine whether it has a decimal part or not (using an error).

The final result is joined with plus signs.

Try it here!

# Answer
> 3 votes
# Pyth, 30 bytes

```
L.xvbytb|j\+fT.eyXXzjkUT\0kbzz

```

Test suite

The basic solution here is to replace all of the digits in the input with `0`, then insert each digit at the proper location, eval, filter out the zeros, and join on pluses. Unfortunately, Pyth's eval function doesn't accept leading zeros currently. I will be working to fix this.

To get past this problem, I added a helper function, `y`, which recursively retries the eval until no error is thrown, removing the first digit every time. Note that this function will loop infinitely on invalid input.

Also, a special case was needed for the input `0`.

All in all, I think the code's pretty good, but the language facilities could be better. Who wants errors?

# Answer
> 3 votes
# Python 3, 138

This is loosely based on TanMath/Ogaday's approach of reading the number as a string and parsing it out that way. I have to use star assignment on `i` so that it correctly handles integers.

```
j,*i=input().split(".")
e=enumerate
z="0"
print("+".join([(x+len(j[y+1:])*z)for y,x in e(j)if x>z]+["."+o*z+p for o,p in e(i)if p>z]or z))

```

# Answer
> 3 votes
# Python, ~~141~~ ~~132~~ 128 bytes

This one is still relatively readable. Convert to string and handle the `>1` digits separately from the `<1` digits. We also have a special case for zero. I could remove two more spaces below, but I like keeping it pretty.

The downside is that it will breakdown for floats with more than 9 decimal places.

```
x=str(int(a*1e9))
l=len(x)-10
z="0"
print"+".join([(j+z*(l-i))if l>=i
 else"."+z*(i-l-1)+j
 for i,j in enumerate(x)if j!=z]or z)

```

Below is the original. First edit was to shorten the zero special case, second edit was to remove the 0 before the decimal, third was to remove some extra parenthesis and spaces.

```
x=str(int(a*1e9))
l=len(x)-10
z="0"
print "+".join([(j+z*(l-i)) if l>=i
 else ("0."+z*(i-l-1)+j)
 for i,j in enumerate(x) if j!=z]) if a else z

```

Explanation:

```
x=str(int(a*1e9)) # Convert into a string with nine decimals
l=len(x)-10
z="0"
print "+".join([
 (j+z*(l-i)) if l>=i       # Print numbers greater than 1
 else ("0."+z*(i-l-1)+j)   # Print less than one
 for i,j in enumerate(x) if j!=z
]) if a else z             # Special case zero

```

# Answer
> 2 votes
# Mathematica, 81 bytes

```
Inactive@Plus@@(10.^Range[#2-1,#2-Length@#,-1]#/.{0.->Nothing[]})&@@RealDigits@#&

```

Test case:

```
%[101.01]
(* 100. + 1. + 0.01 *)

```

# Answer
> 2 votes
# CJam, 44 bytes

```
r:TdLT'.-{'0f+IaaI~g*+}fI:dATW%'.##m]f/'+*e&

```

Try it here.

It fails the last test case, and outputs the following:

```
9000000+9e-7

```

But let's say it's too precise that CJam cannot handle it.

### Explanation

```
r:Td
LT'.-         e# Remove the period if any.
{             e# For each character I:
  '0f+        e# Append 0 to each previous string.
  IaaI~g*+    e# Append I as a string if I isn't '0.
}fI
:d            e# Convert each string to float.
ATW%'.##      e# 10 to the kth power where k is the position of the period from the end.
m]            e# Round up, so it becomes 1 if no periods are found.
f/            e# Divide each float by this number.
'+*e&         e# Format and the 0 special case.

```

# Answer
> 2 votes
# Python 3, ~~187~~ ~~180~~ ~~173~~ 154 bytes

Managed to golf a good 19 bytes off thanks to @Thomas Kwa's suggestions above about `result or['0']`, plus rearranging some algebra (**154 bytes**):

```
def f(n):
 *m,=n;o='0'
 try:p=m.index('.');m.pop(p)
 except:p=len(m)
 return'+'.join([['.'+o*(i-p)+d,d+o*(p-i-1)][p>i]for i,d in enumerate(m)if d!=o])or o

```

~~My best attempt so far~~ (**173 bytes**). Based upon new approach, see bottom of post:

```
def f(n):
 *m,=n;o='0'
 try:p=m.index('.');m.pop(p)
 except:p=len(m)
 return(o,'+'.join([['.'+o*(-1*(p-i))+d,d+o*(p-i-1)][p-i>0]for i,d in enumerate(m)if d!=o]))[eval(n)!=0]

```

golfed my original down to **180 bytes**:

```
def f(n):x=n.split('.');a,b=(x+[''],x)[len(x)-1];e=enumerate;return('0',"+".join([d+'0'*i for i,d in e(a[::-1])if d!='0'][::-1]+['.'+'0'*i+d for i,d in e(b)if d!='0']))[eval(n)!=0]

```

I learnt a new language feature today doing this! Conditionals via boolean indexing. I may have slightly overdone it.

I tried abstracting out the comprehensions, but I couldn't make it any shorter (**196 bytes**):

```
e=lambda s:[d+'0'*(len(s)-i-1) for i,d in enumerate(s) if eval(d)]
def f(n):x=n.split('.');a,b=(x+[''],x)[len(x)-1];return['0',"+".join(e(a)+['.'+d[::-1]for d in e(b[::-1])][::-1])][bool(eval(n))]

```

(Reversing sequences is expensive!)

Whilst mine is shorter for now, I think TanMath can golf his down to match mine: Using `e=enumerate`, replacing `pass` with `0`, and using `'0'` in place of `['0']` in the return statement should save 4+3+2=9 bytes! Taking it down to 187. I'm sure another few bytes can be shaved off somewhere...

**edit** New approach (**156 bytes**). However, it can only deal with precision up to 6dp similar to @jimmy23013's CJam entry, so it fails the final test. I couldn't coerce it to print more 0s, maybe someone else can. Instead I used it as the basis of my best attempt yet, see top (Also, this approach prints the 0 before the decimal place, but that seems valid as well.). Took the `try:... except:...` approach from TanMath:

```
def f(n):
 *m,=n
 try:p=m.index('.');m.pop(p)
 except:p=len(m)
 return('0','+'.join([str(eval(d)*10**(p-i-1))for i,d in enumerate(m)if d!='0']))[eval(n)!=0]

```

# Answer
> 2 votes
# Dyalog APL, 47 bytes

```
{×⍎⍵:1↓∊'+',¨0~⍨(⍎¨w)×10*(⍵⍳'.')-1+⍳≢w←⍵~'.'⋄0}

```

Takes number in character vector form, e.g. `'123'`.

Examples:

```
      f←{×⍎⍵:1↓∊'+',¨0~⍨(⍎¨w)×10*(⍵⍳'.')-1+⍳≢w←⍵~'.'⋄0}
      ↑⍕¨f¨,¨'0' '6' '0.99' '24601' '6.283' '900000.000009'
0
6
0.9 + 0.09
20000 + 4000 + 600 + 1
6 + 0.2 + 0.08 + 0.003
900000 + 0.000009

```

Notes:
○ The reason for the modified last example is that APL, like some of the other submissions, by default will switch to scientific notation for such extreme numbers.
○ The phrase `↑⍕¨f¨,¨` is only needed to process all examples at once.

# Answer
> 2 votes
### pure bash, 210

```
o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ];do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}

```

or

```
o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&
o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ]
do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}

```

Test:

```
exp() {
    o= a=${1%.*} b=${1#$a};while [ "$a" ];do c=${a:1};((${a%$c}>0))&&
    o+=${a%$c}${c//?/0}+;a=$c;done;[ "$b" ]&&{ b=${b#.} a=;while [ "$b" ]
    do c=${b:0:1};((c>0))&&o+=.$a$c+;b=${b:1};a+=0;done;};o=${o%+};echo ${o:-0}
}
while read num;do
    printf "%-12s => " $num
    exp $num
done <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415\n.99'
0            => 0
6            => 6
0.99         => .9+.09
24601        => 20000+4000+600+1
6.283        => 6+.2+.08+.003
9000000.0000009 => 9000000+.0000009
3.1415       => 3+.1+.04+.001+.0005
.99          => .9+.09

```

# Answer
> 2 votes
# Python, 131 bytes

```
f=lambda s,k=0,i=0,o="",z="0":s and f(s[1:],(s<z)+k,i+k,o+(s>="1")*([s[0]+~-(s+".").find(".")*z,"."+z*i+s[0]][k]+"+"))or o[:-1]or z

```

A really, really messy recursive function, probably not the best way to go about this. Input like `f("10.0203")`.

# Answer
> 2 votes
# C, ~~155~~ ~~153~~ 161 bytes

+2 to link in the math library (source itself is 159).

```
main(d,v,p,q)char**v,*p,*q;{for(p=strchr(q=v[1],46),d=p?p-q:strlen(q);*q;++q)*q^46?printf(*q^48|q==v[1]?"%.*f%c":"",d<0?-d:0,(*q-48)*pow(10,--d),q[1]?43:0):0;}

```

## Ungolfed

```
int main(int d, char **v, char *p, char *q)
{
    for(q = v[1], /* Cache the input string */
        p = strchr(q,'.'), /* find the decimal */
        d = p ? p-q : strlen(q); /* calculate number of digits before decimal */
        *q; /* loop while still input data */
        ++q) /* iterate to next character */
    {
        *q^46 /* if not at the decimal point... */
            ? printf(*q^48 || q == v[1] /* if not a zero, or if the string itself is zero... */
                ? "%.f%c" /* print the digit */
                : "", /* else print nothing */
                d<0 ? -d : 0, /* Calculate number of places after decimal to print */
                (*q-48)*pow(10,--d), /* Calculate the digit at the desired power of 10 */
                q[1]?43:0) /* If the next character is still valid input, print the '+' */
            : 0 /* else, do nothing */
    }
}

```

# Answer
> 1 votes
# Java, ~~284~~ ~~244~~ 243 Bytes

```
String x(String s){int b=s.length(),d=(d=s.indexOf(46))<0?b:d,i=-1,k=0;String o="";for(char c;++i<b;)o+=(c=s.charAt(i))>48?(k++>0?" + ":"")+(d-i>0?c:"0.")+new String(new char[Math.abs(d-i)-1]).replace('\0','0')+(d-i>0?"":c):"";return b<2?s:o;}

```

~~Unfortunately, I could not find a shorter way of creating repeating Strings than:~~

* ~~build a `char[]` of the required length~~
* ~~use `Arrays.fill` to set the characters~~
* ~~use `new String` so it can be concatenated~~

With inspiration by @Khaled A Khunaifer, I could shave off 40 Bytes.

Edit: `indexOf` takes an int, so I could replace `'.'` with `46`. Unfortunately, this does not seem to be possible with `replace`.

# Answer
> 1 votes
# Retina, 113 bytes

Currently much longer than Martin's solution but uses a different method so I decided to post it.

```
^
x
S_`(?<=(.*)).(?=(.*))
x

¶\..*¶.*

$
¶
T`d`0`(?<=\d).*¶.*¶
(.*)¶(.*)¶
$2$1¶
(\..*?)0*¶
$1¶
\.?¶0*
¶
¶+
+
\+$
[empty line]

```

Try it online here.

# Answer
> 1 votes
## Perl, 248 bytes

Ew, I am noobish at Perl golfing.

```
@a=split/\./,<>;
@b=split``,$a[1];
@c=split``,$a[0];
for($i=0;$i<length$a[0];$i++){
   $_.=($c[$i]!=0)?$c[$i]."0"x((length$a[0])-$i-2)."+":"";
}
for($i=1;$i<=length$a[1];$i++){
   $_.=($b[$i-1]!=0)?"0."."0"x($i-1).$b[$i-1]."+":"";
}
chop;
($_=="")?print"0 ":print;

```

Try it here.

# Answer
> 1 votes
### perl, 132 bytes

131 +1 for `-p` switch.

This is based on my previous `sed` answer:

```
1while s/^([1-9]\d*)([1-9])(0*)([+.].*|)$/${1}0$3+$2$3$4/||s/([1-9]0*)\.([0-9])/$1+.$2/||s/\.(0*)([1-9])(\d*[1-9])$/.$1$2+.${1}0$3/

```

Test suite:

```
perl -pe'1while s/^([1-9]\d*)([1-9])(0*)([+.].*|)$/${1}0$3+$2$3$4/||
    s/([1-9]0*)\.([0-9])/$1+.$2/||s/\.(0*)([1-9])(\d*[1-9])$/.$1$2+.${1}0$3/
' <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415'
0
6
0.9+.09
20000+4000+600+1
6+.2+.08+.003
9000000+.0000009
3+.1+.04+.001+.0005

```

# Answer
> 1 votes
## Powershell - ~~172~~ ~~166~~ 193 bytes

All on a single line:

```
$z=([string]$args[0])-split"\.";$y=$z[0].length-1+0.6;($z|%{$x=[char[]]$_;if($y-gt0){($x|%{$_+"0"*(-1+$y--)})}else{($x|%{"0."+"0"*[math]::abs($y--)+$_})}}|?{-not($_-match'^[0.]+$')})-join' + '

```

Ungolfed:

```
$z=([string]$args[0]) -split "\."
$y=$z[0].length-1+0.6
($z | %{
    $x=[char[]]$_
    if($y -gt 0) {
        ($x | %{$_+"0"*(-1+$y--)})
    } else {
        ($x | %{"0."+"0"*[math]::abs($y--)+$_})
    }
} | ?{ -not($_ -match '^[0.]+$')}) -join ' + '

```

Test cases, plus one additional:

```
PS> (0, 6, 0.99, 24601, 6.283, 9000000.0000009, [math]::pi) | %{.\expand.ps1 $_}

6
0.9 + 0.09
20000 + 4000 + 600 + 1
6 + 0.2 + 0.08 + 0.003
9000000 + 0.0000009
3 + 0.1 + 0.04 + 0.001 + 0.0005 + 0.00009 + 0.000002 + 0.0000006 + 0.00000005 + 0.000000003 + 0.0000000005 + 0.00 000000008 + 0.000000000009 + 0.0000000000007 + 0.00000000000009
PS>

```

# Answer
> 1 votes
# CoffeeScript, 144 bytes

Straight forward solution:

```
X=(n)->[m,k]="#{n}".split '.';(c+Array(m.length-i).join 0for i,c of m when+c).concat(".#{Array(++i).join 0}"+c for i,c of k when+c).join('+')||0

```

### Executable:

```
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">
X=(n)->[m,k]="#{n}".split '.';(c+Array(m.length-i).join 0for i,c of m when+c).concat(".#{Array(++i).join 0}"+c for i,c of k when+c).join('+')||0

# Tests follow
tests = [
  0
  6
  0.99
  24601
  6.283
  9000000.0000009
]

window.solution = X
result.textContent=("#{n} => #{X n}" for n in tests).join '\n'
</script>
<input type="number" oninput="result.textContent=solution(this.value)">
<pre id="result"></pre>
```

# Answer
> 1 votes
# Python, 125 bytes

After deleting my 1st answer (sry!) which could not handle small numbers due to machine epsilon issues, I found a different solution. It handles float as well as integers, trailing zeros (!) and is written as function.

Thanks to @ogaday for the useful hints and for the compact '0'-fix!

Golfed:

```
def f(x):x+='.';i=x.find('.');z=list(x);del z[i];return'+'.join([str(int(o)*10**(i-j-1))for j,o in enumerate(z)if'0'<o])or'0'

```

Ungolfed:

```
def f(x):
  x+='.'
  i=x.find('.')
  z=list(x)
  del z[i]
  return '+'.join([str(int(o)*10**(i-j-1)) for j,o in enumerate(z) if '0'<o]) or '0'

```

Usage:

```
>>> f("0")
'0'

>>> f("32.005")
'30+2+0.005'

>>> f("100020003000009000000.0007")
'100000000000000000000+20000000000000000+3000000000000+9000000+0.0007'

>>> f("1000000000009000000.0007000000000000000002")
'1000000000000000000+9000000+0.0007+2e-22'

>>> f("0001.99")
'1+0.9+0.09'

```

# Answer
> 1 votes
# Stax, 18 bytes

```
ºî≤FlφLfÜG→\ΦUq╜♥←

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
c           copy input
!C          terminate if input is falsy
y{          for each character in the string input...
  y.\d'0R   replace each digit in the input with "0"
  ia&       then replace the nth character back to its original value
  e         eval as float
m           map using block to produce array
{f          filter out zeroes
'+*         join with "+"

```

Run this one

Like the many of the other solutions posted, it produces `9000000+9e-7` for the last test case. According to established precedent this is allowed because the test case is too precise for the language.

# Answer
> 0 votes
# C, 253 bytes

```
m(char*i){int k,j=0,s=0,d=0;while(i[s])s++;while(i[d]!=46)d++;while(j<d){if(i[j]!=48){for(k=0;k<(d-j);k++)putchar(k?48:i[j]);putchar(43);}j++;}while(++j<s)if(i[j]!=48){putchar(46);for(k=0;k<(j-d);k++)putchar(k==(j-d-1)?i[j]:48);putchar(43);}putchar(8);}

```

Note: `putchar(8)` should perform a backspace.

```
 Input: 1230.0456
Output: 1000+200+30+.04+.005+.0006

```

**Detailed**, try here

```
while(i[s]) s++;
while(i[d]!=46) d++;

while (j<d)
{
    if (i[j]!='0')
    {
        for(k=0;k<(d-j);k++) putchar(k? '0': i[j]);
        putchar(43);
    }
    j++;
}

while (++j<s)
if (i[j]!='0')
{
    putchar(46);
    for(k=0; k<(j-d); k++) putchar(k==(j-d-1)? i[j]: '0');
    putchar(43);
}

putchar(8);

```

# Answer
> 0 votes
# Lua, 350 Bytes

I think there's two way to golf it down further :

* I could make use of `macro.define` to replace some of the commons expressions (can't test right now, and not sure it would make me gain some bytes)
* Use split on the dot instead of iterating on the whole string. Once again, I'm not sure it would reduce the size of this function, as manipulating string in lua is quite painful.

```
function f(s)v,r=s:find("%.")or#s+1,""if #s==1 then return s end for i=1,#s do a=""(v>i and s:sub(i,v-1)or s:sub(v,i)):gsub(".",function(c)a=a..(not a:find(c)and(c==s:sub(i,i)or c==".")and c or 0)end)s,r=v<i and s:sub(0,i-1).."0"..s:sub(i+1,#s)or s,r..((#a==a:find("%.")or tonumber(a)==0)and""or a:gsub("%.","0.")..(i~=#s and"+"or""))end return r end

```

### Explanations

```
function f(s)
  v=s:find("%.")or #s+1               -- v=index of the dot in a decimal number
  r=""                                -- v=#s+1 when s is an integer(v=0 would screw sub())
  if #s==1 then return s end          -- exit if s is a single digit
  for i=1,#s                          -- iterate over s
  do
    a=""

    (v>i and s:sub(i,v-1)or s:sub(v,i)-- only send the integer OR decimal part to gsub
      ):gsub(".",function(c)          -- iterate over each character of s:sub()

    -- a contains the next number to be concatenated to the string r(the one to be returned)
      a=a..(not a:find(c)             -- we concatenate a with c if a doen't contains
        and(c==s:sub(i,i)or c==".")   -- c, and c is either a dot, or the next number
             and c or 0)              -- to be add, we put a 0 otherwise
    end)
    -- we concatenate the new a with the string already formed
    r=r..((#a==a:find("%.")           -- if a=="." or a's value is 0
            or tonumber(a)==0)and""   -- we concatenate an empty string
      or a:gsub("%.","0.")            -- else, we replace the (possible) leading dot by "0."
      ..(i~=#s and"+"or""))           -- and concatenate a "+" if it isn't the last number to be added

    s=v<i and s:sub(0,i-1)            -- We then replace the digit we have worked with
      .."0"..s:sub(i+1,#s)or s        -- to prevent duplicates
  end
  return r
end

```

You can test lua online and use the following source code to run it with some test cases

```
function f(s)v,r=s:find("%.")or#s+1,""if #s==1 then return s end for i=1,#s do a=""(v>i and s:sub(i,v-1)or s:sub(v,i)):gsub(".",function(c)a=a..(not a:find(c)and(c==s:sub(i,i)or c==".")and c or 0)end)s,r=v<i and s:sub(0,i-1).."0"..s:sub(i+1,#s)or s,r..((#a==a:find("%.")or tonumber(a)==0)and""or a:gsub("%.","0.")..(i~=#s and"+"or""))end return r end

print(f("3123.12333"))
print(f("9545"))
print(f("9000000.0000009"))
print(f("6"))

```

# Answer
> 0 votes
### sed, ~~136~~ 128 bytes

Reduced by 8 chars by dropping spaces and useless `0`.

```
:;s/^([1-9][0-9]*)([1-9])(0*)([+.].*|)$/\10\3+\2\3\4/;s/([1-9]0*)\.([0-9])/\1+.\2/;s/\.(0*)([1-9])([0-9]*[1-9])$/.\1\2+.\10\3/;t

```

Test cases:

```
sed -r ':;
    s/^([1-9][0-9]*)([1-9])(0*)([+.].*|)$/\10\3+\2\3\4/;
    s/([1-9]0*)\.([0-9])/\1+.\2/;
    s/\.(0*)([1-9])([0-9]*[1-9])$/.\1\2+.\10\3/;
    t' <<<$'0\n6\n0.99\n24601\n6.283\n9000000.0000009\n3.1415'
0
6
0.9+.09
20000+4000+600+1
6+.2+.08+.003
9000000+.0000009
3+.1+.04+.001+.0005

```

# Answer
> 0 votes
# R - 133 bytes

Robust, ignores Machine Epsilon and works also with trailing zeros.

a) Golfed:

```
f=function(x)if(x=='0')x else{z=strsplit(x,'')[[1]];i=which(z=='.');n=as.numeric(z[-i])*10^(i-seq(z)[-1]);paste(n[n>0],collapse='+')}

```

Ungolfed:

```
f=function(x)
  if(x=='0')
    x
  else {
    z=strsplit(x,'')[[1]]
    i=which(z=='.')
    n=as.numeric(z[-i])*10^(i-seq(z)[-1])
    paste(n[n>0],collapse='+')
  }

```

Usage:

```
f("900.008")

```

# Answer
> 0 votes
## JavaScript (ES7), 114 bytes

```
s=>(p=s.search(/.\b/),i=-1,[for(c of s)if((i++,c>0))(z=s.substring(i,p).replace(/d/g,0),i<p?c+z:z+c)].join`+`||s

```

Works with arbitrary length numbers because it uses string manipulation throughout.

Without the array comprehension (122 bytes):

```
s=>[...s].map((c,i)=>c<'1'?'':(z=s.substring(i,p).replace(/\d/g,0),i<p?c+z:z+c),p=s.search(/.\b/)).filter(x=>x).join`+`||s

```

Ungolfed:

```
function expand(s) {
    zeros = s.replace(/\d/g, "0");
    point = s.indexOf(".");
    if (point < 0) point = s.length;
    result = [];
    for (i = 0; i < s.length; i++) {
        if (s[i] > "0") {
            if (i < point) result.push(s[i] + zeros.slice(i, point - 1));
            else result.push(zeros.slice(point - 1, i) + s[i]);
         }
     }
     return result.length ? result.join("+") : s;
}

```

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


# Question
Title: Generate combinations that add up to a target value
## Challenge

Suppose you have a list of numbers, and a target value. Find the set of all combinations of your numbers which add up to the target value, returning them as list indices.

## Input and Output

The input will take a list of numbers (not necessarily unique) and a target summation number. The output will be a set of non-empty lists, each list containing integer values corresponding to the position of the values in the original input list.

## Examples

```
Input: values = [1, 2, 1, 5], target = 8
Output: [ [0,1,3], [1,2,3] ]

Input: values = [4.8, 9.5, 2.7, 11.12, 10], target = 14.8
Output: [ [0,4] ]

Input: values = [7, 8, 9, -10, 20, 27], target = 17
Output: [ [1,2], [0,3,4], [3,5] ]

Input: values = [1, 2, 3], target = 7
Output: [ ]

```

## Scoring

This is , so the shortest code wins!

# Answer
# Husk, 10 bytes

```
ηλfo=¹ṁ⁰tṖ

```

1-indexed. Try it online!

## Explanation

```
ηλfo=¹ṁ⁰tṖ  Inputs are a number n (explicit, accessed with ¹) and a list x (implicit).
η           Act on the incides of x
 λ          using this function:
         Ṗ   Take all subsets,
        t    remove the first one (the empty subset),
  f          and keep those that satisfy this:
      ṁ⁰      The sum of the corresponding elements of x
   o=¹        equals n.

```

This uses the latest addition to Husk, `η` (act on indices). The idea is that `η` takes a higher order function `α` (here the inline lambda function) and a list `x`, and calls `α` on the indexing function of `x` (which is  in the above program) and the indices of `x`. For example, `ṁ⁰` takes a subset of indices, maps indexing to `x` over them and sums the results.
> 3 votes

# Answer
# JavaScript (ES6), 96 bytes

Takes input in currying syntax `(list)(target)`.

```
a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

```

### Test cases

This would fail on the 2nd test case if 4.8 and 10 were swapped because of an IEEE 754 precision error -- i.e. `14.8 - 4.8 - 10 == 0` but `14.8 - 10 - 4.8 != 0`. I think this is fine, although there may be a more relevant reference somewhere in meta.

```
let f =

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

console.log(JSON.stringify(f([1, 2, 1, 5])(8)))
console.log(JSON.stringify(f([4.8, 9.5, 2.7, 11.12, 10])(14.8)))
console.log(JSON.stringify(f([7, 8, 9, -10, 20, 27])(17)))
console.log(JSON.stringify(f([1, 2, 3])(7)))
```

### Commented

```
a => s =>                 // given an array a[] of length N and an integer s
  a.reduce((b, _, x) =>   // step #1: build the powerset of [0, 1, ..., N-1]
    [ ...b,               //   by repeatedly adding to the previous list b[]
      ...b                //   new arrays made of:
      .map(y =>           //     all previous entries stored in y[]
        [...y, x]         //     followed by the new index x
      )                   //   leading to:
    ],                    //   [[]] -> [[],[0]] -> [[],[0],[1],[0,1]] -> ...
    [[]]                  //   we start with a list containing an empty array
  )                       // end of reduce()
  .filter(b =>            // step #2: filter the powerset
    !b.reduce((p, i) =>   //   keeping only entries b
      p - a[i],           //     for which sum(a[i] for i in b)
      s                   //     is equal to s
    )                     //   end of reduce()
  )                       // end of filter()

```
> 9 votes

# Answer
# , ~~32~~ 31 bytes

```
(=1#.t#])<@I.@#t=.1-[:i.&.#.1"0

```

Try it online!

```
                  1-[:i.&.#.1"0         Make a list of all masks
                                        for the input list. We flip the bits
                                        to turn the unnecessary (0...0)
                                        into (1...1) that would be missing.
                                        Define it as t.

(=1#.t#])                               Apply the masks, sum and
                                        compare with the target

         <@I.@#                         Turn the matching masks into
                                        lists of indices

```
> 7 votes

# Answer
# Python 2, 110 bytes

```
lambda a,n:[b for b in[[i for i in range(len(a))if j&1<<i]for j in range(2**len(a))]if sum(a[c]for c in b)==n]

```

Try it online!
> 7 votes

# Answer
# , ~~85~~ 84 bytes

```
function(l,k){N=combn
o={}
for(i in I<-1:sum(l|1))o=c(o,N(I,i,,F)[N(l,i,sum)==k])
o}

```

Try it online!

1-indexed.

`combn` usually returns a `matrix`, but setting `simplify=F` returns a `list` instead, allowing us to `c`oncatenate all the results together. `combn(I,i,,F)` returns all combinations of indices, and we take `N(l,i,sum)==k` as an index into that list to determine those which equal `k`.
> 7 votes

# Answer
# Japt, 14 bytes

```
m, à f_x!gU ¥V

```

Test it online!

### How it works

```
m, à f_x!gU ¥V   Implicit: U = input array, V = target sum
m,               Turn U into a range [0, 1, ..., U.length - 1].
   à             Generate all combinations of this range.
     f_          Filter to only the combinations where
       x           the sum of
        !gU        the items at these indices in U
            ¥V     equals the target sum.
                 Implicit: output result of last expression

```
> 5 votes

# Answer
# Clean, ~~104~~ ~~102~~ 98 bytes

```
import StdEnv
@n=[[]:[[i:b]\\i<-[0..n-1],b<- @i]]
?l n=[e\\e<-tl(@(length l))|sum(map((!!)l)e)==n]

```

Try it online!
> 5 votes

# Answer
# Jelly, 11 bytes

```
ị³S=
JŒPçÐf

```

Try it online!

1-indexed. 4 bytes spent on returning indices rather than just the elements themselves.

-1 byte thanks to user202729
-1 byte thanks to Jonathan Allan
> 4 votes

# Answer
# Haskell, 76 bytes

```
x#t=[i|i<-tail$concat<$>mapM(\z->[[],[z]])[0..length x-1],t==sum[x!!k|k<-i]]

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 43 bytes

1-indexed.

```
Pick[s=Subsets;s@Range@Tr[1^#],Tr/@s@#,#2]&

```

Try it online!
> 3 votes

# Answer
# Python 3, 144 bytes

```
lambda a,t:[[e for e,_ in x]for r in range(len(a))for x in combinations(list(enumerate(a)),r+1)if sum(y for _,y in x)==t]
from itertools import*

```

Try it online!

0-indexed. 44 bytes spent on returning indices rather than just the elements themselves.
> 2 votes

# Answer
# Brachylog, ~~18~~ 15 bytes

```
hiᶠ⊇Shᵐ+~t?∧Stᵐ

```

Try it online!

*-3 bytes because it now works as a generator.* (It's probably possible to golf more, but working around the need to use indices is awkward.)

```
    S              The variable S
   ⊇               is a sublist of
  ᶠ                the list of all
 i                 pairs [element, index] from
h                  the first element of
                   the input;
     hᵐ            the first elements of each pair
       +           add up to
        ~t         the last element of
          ?        the input
           ∧       which isn't necessarily
            S      S,
             tᵐ    from which the last elements of each pair
                   are output.

```
> 2 votes

# Answer
# Perl 6, 45 bytes

```
->\a,\b{grep {a[$_].sum==b},^a .combinations}

```

Test it

## Expanded:

```
->
  \a, # input list
  \b, # input target
{

  grep

  {
      a[ $_ ].sum # use the list under test as indexes into ｢a｣
    ==
      b
  },

  ^a              # Range upto ｢a｣ (uses ｢a｣ as a number)
  .combinations   # get all of the combinations
}

```
> 1 votes

# Answer
# APL(NARS), 49 chars, 98 bytes

```
{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}

```

1-indexed; test:

```
  f←{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}
  ⎕fmt 8 f 1 2 1 5
┌2──────────────┐
│┌3────┐ ┌3────┐│
││2 3 4│ │1 2 4││
│└~────┘ └~────┘2
└∊──────────────┘
  ⎕fmt   14.8  f  4.8 9.5 2.7 11.12 10
┌1────┐
│┌2──┐│
││1 5││
│└~──┘2
└∊────┘
  ⎕fmt 17 f 7, 8, 9, ¯10, 20, 27
┌3──────────────────┐
│┌2──┐ ┌2──┐ ┌3────┐│
││4 6│ │2 3│ │1 4 5││
│└~──┘ └~──┘ └~────┘2
└∊──────────────────┘
  ⎕fmt 7 f 1 2 3
┌0┐
│0│
└~┘

```

comment:

```
{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}
                             ⍳¯1+2*k←≢w←⍵         copy ⍵ in w, len(⍵) in k, return 1..2^(k-1)
                 n←{⍵⊤⍨k⍴2}¨                     traslate in binary each element of  1..2^(k-1) and assign the result to n
          {∊⍵⊂w}¨                                for each binary element of n return the elemets of ⍵ in the place where there are the 1s
    b←⍺=+/¨                                       sum them and see if the sum is ⍺, that binary array saved in b
  ∨/                                     :⍸¨b/n   if or/b, get all the elements of n that are 1s for array b, and calculate each all indexs
                                               ⋄⍬ else return Zilde as void set

```
> 1 votes

# Answer
# Pyth, 11 bytes

```
fqvzs@LQTyU

```

Try it online here, or verify all the test cases at once here.

```
fqvzs@LQTyUQ   Implicit: Q=input 1 (list of numbers), z=input 2 (target value, as string)
               Trailing Q inferred
          UQ   Generate range [0-<length of Q>)
         y     Powerset of the above
f              Keep elements of the above, as T, when the following is truthy:
      L T        Map elements of T...
     @ Q         ... to the indicies in Q
    s            Take the sum
 q               Is the above equal to...
  vz             z as an integer
               Implicit print of the remaining results

```
> 0 votes

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


# Question
Title: Find all a, b, c, d, e, such that a + b + c + d + e = 1000 with no more than 3 loops
**The rule is:**

* `a, b, c, d, e` is an integer from `0` to `1000`, no relation between `a, b, c, d, e` so `a` can equal to `b` or `c`, ...
* can not use more than 3 loops (it can be 3 nested loops or 3 normal loops, or 2 nested loops + 1 normal loop, ...)
* you need to find all the answers for `(a, b, c, d, e)` that is:

```
a + b + c + d + e = 1000

```
* Your answer can be any format: line by line, array, object, ... but it must be clear so anyone can see it.
* Shortest bytes will be win for each language!

For example here is when I used 5 loops to solve this puzzle and it violates the rules:

https://repl.it/repls/BestKnobbyDonateware

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~23~~ 16 bytesSBCS

Full program. No loops. Prints a list of quintuplets with two spaces between them. Each quintuplet has the variables separated by single spaces. Requires 0-indexing (`⎕IO←0`) which is default on many systems.

```
⍸1E3=⊃∘.+/5⍴⊂⍳1001

```

Since the above code requires more memory than available on TIO, here's exactly the same, but with a + b + c + d + e between 0 and 10 and a sum of 10:

```
⍸1E1=⊃∘.+/5⍴⊂⍳11.0

```

Try it online!

`⍳1001` the **ɩ**ntegers 0…1000

enclose to treat as a unit

`5⍴` reshape that to length 5

`∘.+/` reduction by outer-sum (like outer product, but with plus)
this creates a 5D array with all dimensions being 1000 elements long

disclose (the reduction had to enclose the result to reduce the rank from 1 to 0)

`1E3` 5D Boolean mask where equal to 1000

list of **ɩ**ndices where true

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
₄Ý5ãʒO₄Q

```

No loops.. (Well, maybe 1 if you count the filter as a loop I guess.)

Outputs as a list of lists of integers.

Try it online with `10` instead of `1000`.

**Explanation:**

```
₄Ý        # Push a list in the range [0,1000]
  5ã      # Create quintuples by repeating the cartesian product 5 times
    ʒ     # Filter this list by:
     O    #  Where the sum
      ₄Q  #  Is equal to 1000
          # (output the result implicitly after the filter)

```

# Answer
> 1 votes
# VDM-SL, 57 bytes

```
{[a,b,c,d,e]|a,b,c,d,e in set{0,...,1000}&a+b+c+d+e=1000}

```

Set comprehension - 0 loops

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


# Question
Title: Tesco's Burger Relish Best Before End date number
Given a date between 2010-01-01 and 2099-12-31 as three integers (please state your order if not `[year,month,day]`), answer with Tesco's corresponding five-digit Burger Relish Best Before End date number.

The format is simply the last two digits of the year, followed immediately by three digits representing the day of that year, between 000 and 365.

Cookies if you can do this using only numeric operations and comparisons. You may put such code separately from your golfed code, if it isn't also the shortest code you have.

### Test cases

`[year,month,day]``BRBBED`:

`[2010,1,1]``10000`

`[2019,7,5]``19185`

`[2020,5,20]``20140`

`[2096,12,31]``96365`

`[2099,12,31]``99364`

# Answer
# PowerShell, ~~74~~ ~~70~~ 67 bytes

```
param($y,$m,$d)-join"$y 00$((date "$m/$d/$y"|% d*r)-1)"[2,3+-3..-1]

```

Try it online!

Exactly what it says on the tin (but formatted weirdly). Takes in `$y`ear, `$m`onth, `$d`ay, plucks out the last two digits of the `$y`ear, gets a .NET `datetime` object of the specified day, then gets the `dayofyear` (with `|% d*r`) thereof. Subtracts one to make it zero-indexed, then uses string formatting and slicing to make it three-padded (e.g., `000` instead of `0`), and then `-join`s it all together into a single string with implicit output.

Note this is culture dependent due to the `datetime` formatting. This works in `en-us`, which is what TIO also uses.

*-3 bytes thanks to mazzy*
> 6 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~88~~ ~~78~~ ~~73~~ ~~71~~ ~~59~~ 57 bytes

```
a=>a[0]%100*1000+new DateTime(a[0],a[1],a[2]).DayOfYear-1

```

Try it online!
> 4 votes

# Answer
# Ruby, 40 bytes

```
->d{Time.gm(*d).strftime('%y%j').to_i-1}

```

Try it online!

So close to being a built-in format, but `%j` is 1-indexed.

In a happier coincidence, though, Tesco Time (`.gm`) is one character shorter than local time (`.new`).
> 3 votes

# Answer
# PowerShell, ~~48~~ ~~45~~ 39 bytes

Port of Expired Data's answer for C#

```
$args[0]*1E3+("$args"|date|% d*r)-2E6-1

```

Try it online!

---

# PowerShell, ~~60~~ ~~58~~ 52 bytes

*-2 bytes thanks @AdmBorkBork*

```
-join"$args 00$(("$args"|date|% d*r)-1)"[2,3+-3..-1]

```

Try it online!

Explanation:

* The script takes three integers `[year,month,day]`
* `"$args"` makes a string like `YYYY MM DD`
* `"YYYY MM DD"|date` converts string to `[DateTime]`. I don't know why it works. Can you explain?
* `("YYYY MM DD"|date|% d*r)-1` calculates `dayOfYear`
* the script makes a result string like `YYYY MM DD 00###` where `###` is `dayOfYear`
* finally the script extracts chars from positions `[2,3+-3..-1]` of the result string and joins this chars to result
> 3 votes

# Answer
# Python 2, ~~63~~ ~~61~~ 57 bytes

```
lambda y,m,d:y%100*1000+(153*m-2)/5+[m+1,1>y%4][2<m]+d-33

```

Try it online!

Returns the result as an integer.

Neil found that his Charcoal approach turned out to be lucky after some rearrangement.

Pure arithmetic and comparison solution (61 bytes):

```
lambda y,m,d:y%100*1000+30*m+m/2+(8<m<12)+~(0<y%4)*(2<m)+d-31

```
> 2 votes

# Answer
# Python 3, ~~87~~ ~~85~~ 74 bytes

```
lambda y,m,d:sum([y*1000-2000029+28*m,3,y%4==0,3,2,3,2,3,3,2,3,2,3][:m])+d

```

Try it online!

This is using only numeric operations and comparisons.
> 2 votes

# Answer
# Jelly, 30 bytes

```
4ḍȯ2⁽¢wB+30¤_2¦ŻḣS+⁵’+³×ȷ¤_2ȷ6

```

A full program taking arguments `y m d`.
Jelly has no built-in date functionality.

**Try it online!**

### How?

```
4ḍȯ2⁽¢wB+30¤_2¦ŻḣS+⁵’+³×ȷ¤_2ȷ6 - Main Link
           ¤                   - nilad followed by link(s) as a nilad:
    ⁽¢w                        -   1370
       B                       -   to binary = [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0]
        +30                    -   add 30   = [31,30,31,30,31,30,31,31,30,31,30]
              ¦                - sparse application...
             2                 -   to indices: [2]
            _                  -   action: subtract...
4ḍ                             -     four divides y? -> 1 or 0
  ȯ2                           -     OR 2               1 or 2
               Ż               - prepend 0 = [0,31,29|28,31,30,31,30,31,31,30,31,30]
                ḣ              - head to index m
                 S             - sum
                  +⁵           - add d
                    ’          - subtract one
                         ¤     - nilad followed by link(s) as a nilad:
                      ³        -   y
                        ȷ      -   1000
                       ×       -   multiply
                     +         - add
                           2ȷ6 - 2000000
                          _    - subtract

```
> 2 votes

# Answer
# Charcoal, 33 bytes

```
ＩΣ⟦×φ﹪θ¹⁰⁰⊖ζ÷⊕×¹⁵³⊖η⁵⎇›η²⊖⊖¬﹪θ⁴⊖η

```

Try it online! Link is to verbose version of code. Try it online! Link includes test suite. I don't think Charcoal has any date functions, so here's a mathematical solution. Explanation:

```
   ×φ﹪θ¹⁰⁰                          Year * 1000
          ⊖ζ                        Day - 1
            ÷⊕×¹⁵³⊖η⁵               Days in previous months
                     ⎇›η²            For months after Februrary
                         ⊖⊖¬﹪θ⁴     Adjust for leap years else
                               ⊖η   Adjust for short Februrary
 Σ⟦                                 Take the sum
Ｉ                                   Cast to string for implicit print

```
> 1 votes

# Answer
# \[R\], 66 bytes

```
 function(a,b,c)as.numeric(strftime(paste(a,b,c,sep='-'),'%y%j'))-1

```

taking 3 integers and pasting them into a string strftime can recognize and extract the wanted parts. 0 indexing costs 14 bytes and another conversion to numeric
> 1 votes

# Answer
# Ruby, 79 81 79 78 bytes

```
->y,m,d{(y%100*k=1000)+[d-1,l=31,y%4<1?29:28,l,s=30,l,s,l,l,s,l,s][0,m].sum%k}

```

Cookies version. Saved a few bytes by including the -1 and day in the array that gets summed, since those spaces were spare anyway.

EDIT: I realised that using `"...%03d"%...` wasn't really in the spirit of 'numerical and comparison operators only' so I've updated this answer (and gone up by 2 bytes).

EDIT-2: ... and recovered them by using the alternative sub-array index format `[start,length]`, which in turn allowed me to combine the first two entries in the array.

EDIT-3: `y%4==0` can be shortened to `y%4<1`
> 1 votes

# Answer
# JavaScript, ~~70~~ 57 bytes

```
(y,m,d,U=Date.UTC)=>y%100*1e3+(U(y,m-1,d)-U(y,0,1))/864e5

```

Try it online!
> 0 votes

# Answer
# Japt, 23 bytes

Takes input as 3 individual strings, assuming that's allowed.

```
¤+@ÐUTX Å¶ÐN Å}as ùT3 É

```

Try it

Very unhappy with this (there must be a better way to get the day of the year!) but it's been a long day. A port of darrylyeo's JS solution would be 2 bytes shorter but, for some reason, despite Japt being JavaScript, floating point inaccuracies abound.

```
¤+@ÐUTX Å¶ÐN Å}as ùT3 É     :Implicit input of strings U=y, V=d & W=d (N=[U,V,W])
¤                           :Slice the first 2 characters off U
 +                          :Append
  @                         :  Function taking an integer X as its argument
   ÐUTX                     :    Construct a Date object with U as the year, 0 as the month & X as the day
        Å                   :    Convert to date string ("yyyy-mm-dd")
         ¶                  :    Test for equality with
          ÐN Å              :    Construct a Date object from N and convert to a date string
              }             :  End function
               a            :  Return the first integer that returns true when passed through that function
                s           :  Convert to string
                  ùT3       :  Left pad with 0 to length 3
                      É     :Subtract 1

```
> 0 votes

# Answer
# Red, 54 bytes

```
func[y m d][y % 100 * 1000 - 1 + pick to now[d m y]11]

```

Try it online!
> 0 votes

# Answer
# 8th, ~~77~~ 71 bytes

**Code**

```
needs date/utils : f third -rot d:ymd> doy n:1- swap 100 mod 1000 * + ;

```

Return the result on **TOS**

**Usage**

```
ok> 2010 1 1 f .
10000
ok> 2019 7 5 f .
19185
ok> 2020 5 20 f .
20140
ok> 2096 12 31 f .
96365
ok> 2099 12 31 f .
99364

```
> 0 votes

# Answer
# Perl 6, 45 bytes

```
{@_.[0]%100*1000-1+Date.new(|@_).day-of-year}

```

Try it online!
> 0 votes

# Answer
# 05AB1E, ~~29~~ ~~26~~ 23 bytes

```
¦¦₄*•ΘÏF•ºS₂+I<£O¹4ÖI<O

```

Try it online or verify all test cases.

Takes three loose inputs in the order \\$year\\$, \\$month\\$, \\$day\\$.

**Explanation:**

```
¦¦             # Remove the first two digits of the (implicit) input-year
               #  i.e. year=2024 → 24
  ₄*           # Multiply it by 1000
               #  → 24000
•ΘÏF•          # Push compressed integer 5254545
     º         # Mirror it vertically to 52545455454525
      S        # Convert it to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
       ₂+      # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         I<    # Push the second input-month decremented by 1
           £   # Leave the first month-1 amount of values from the list
            O  # Sum this list
               #  i.e. month=4 → [31,28,31] → 90
¹              # Push the first input-year again
 4Ö            # Check if it's divisible by 4
               #  2024 → 1 (truthy)
I<             # Push the third input-days, decremented by 1
               #  i.e. days=3 → 2
O              # Sum everything on the stack together
               #  24000,90,1,2 → 24093
               # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•ΘÏF•` is `5254545`.
> 0 votes

# Answer
# Elm 0.19, 112 bytes

```
t y m d=1000*(y-2000)+List.sum(List.take m[d-1,31,if modBy 4 y<1 then 29 else 28,31,30,31,30,31,31,30,31,30,31])

```

Verify all test cases here.
> 0 votes

---
Tags: code-golf, number, date, conversion
---


title: Jimmy needs your help!

text:
# Question
Title: Jimmy needs your help!
It seems as of recent, there have been a lot a Jimmys falling to their death, as can be seen here, and here where you were asked to determine if Jimmy would fall. It is time we put a stop to this madness and try to save Jimmy.

Jimmy has three body parts `/`, `o`, and `\` arranged like this

```
/o\

```

Platforms are represented with `-`. Jimmy will fall off their platform iff they have two or more body parts that are not directly above a platform.

Some examples:

```
   /o\
- -------

```

Jimmy will balance since all their body parts are above a `-`.

```
   /o\
    ------   ---

```

Jimmy will balanced since two body parts are above `-`s.

```
 /o\
-- ----  --

```

Jimmy will balance even though they are split between two platforms

```
  /o\
   -

```

Jimmy will not balanced since two body parts are not above a platform.

---

Since my platform supply is running low, I only have platforms with a length of 5, and it is important we use as few as possible.

Your task is to take an input of Jimmys and output a string of platforms which will save all of the Jimmys in the input. Your output must use as few platforms as possible, but each platform must be 5 `-`'s wide.

Note that the rule of the platform being 5 `-` wide, means that each platform must have a space between them. `----------` is not valid in the output since it will be considered a platform of length 10 and not two platforms of length 5.

### Test Case's

```
/o\  /o\/o\    // input
----- -----    // output

```

```
/o\           /o\
-----       -----

```

```
/o\           /o\      // same input as above
-----          -----   // this is also valid output

```

```
    /o\ /o\
     -----

```

Standard rules apply.

This is code-golf, may the shortest answer win!

# Answer
# Charcoal, ~~17~~ 15 bytes

```
Ｗ‹ⅈＬθ«×⁵№o\§θⅈ→

```

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

```
Ｗ‹ⅈＬθ«

```

Repeat while the cursor position is less than the length of the input.

```
×⁵№o\§θⅈ

```

If the character at that position in the input is an `o` or a `\` then print 5 `-`s.

Move to the next character, thus guaranteeing at least one space between platforms.

Previous 17-byte solution is IMHO more "Charcoal-y".

```
θ⸿Ｆθ«×⁵¬№ /⊟ＫＤ²↑→

```

Try it online! Link is to verbose version of code. Output includes input, thus demonstrating correctness of solution. Explanation:

```
θ⸿

```

Print the input and move to the start of the next line.

```
Ｆθ«

```

Loop over every character of the input to ensure that no Jimmy gets missed.

```
×⁵¬№ /⊟ＫＤ²↑

```

Look at the character above the cursor. If there is none, or if it is space or `/`, then do nothing, otherwise print 5 `-`s.

Move to the next character, thus guaranteeing at least one space between platforms.
> 2 votes

# Answer
# Python 2, ~~70~~ 67 bytes

```
lambda s:S('/',' ',S("\S.{5}","----- ",s+' '*5))
import re;S=re.sub

```

Try it online!

*-3 bytes thanks to Kevin Cruijssen & Neil*

Not the prettiest, not sure how to better handle those leftover slashes...

Unfortunately, we can't replace both ends of each platform with spaces using a single `re.sub` call, because in the case of 2 platforms being one space apart, the gap between them can't be matched more than once. A lookahead/lookbehind assertion won't help, because anything matched within those assertions doesn't get replaced.

Using a single `re.sub` reference:

# Python 3.8 (pre-release), 78 bytes

```
lambda s:[s:=re.sub(".[^/ -].{5}"," ----- ",s+"  ",1)for c in s][-1]
import re

```

Try it online!
> 7 votes

# Answer
# JavaScript (ES6),  ~~56 55~~  54 bytes

```
s=>[...s+1e4].map(c=>(s--?s:s=c>{}&&5)?'-':' ').join``

```

Try it online!

Or 47 bytes if returning an array of characters is acceptable.
> 4 votes

# Answer
# Python 3, ~~158~~ ~~164~~ 160 bytes

```
a=input();r=""
for i,c in enumerate(a):
 try:r[i]
 except:
  if c in"/o":
   r+=(a[i+5<len(a)and i+5or len(a)-1]=="o"and" "or"")+"----- "
  else:r+=" "
print(r)

```

Try it online!

This is my first code golf answer, and I'm happy it's on a Jimmy question!

Explanation:

* `a=input();r=""`: Take in input and initialize a new string `r`.
* `for i,c in enumerate(a):`: Enumerate over the input.
* `try:r[i] ... except:`: See if `r[i]` exists - if not, process the `except` block.
* `if c in"/o":`: Check if the current character is in Jimmy's first two body parts.
* `r+=(a[i+5<len(a)and i+5or len(a)-1]=="o"and" "or"")+"----- "`: If so, add a new segment. Add a space before our new segment if another Jimmy head is present in five characters.
* `else:r+=" "`: Otherwise, just add a space.
* `print(r)`: Print our final result.
> 2 votes

# Answer
# Japt, ~~23~~ 22 bytes

A port of Arnauld's JS solution that I'm just too exhausted to fully test. If it's invalid can a Diamond please delete?

```
+L² £=U´?U:X>M©5)?'-:S

```

Try it
> 2 votes

# Answer
# Retina, ~~23~~ 21 bytes

```
/

$
5*
\S.{5}
5*-
```

-2 bytes thanks to *@Neil*.

Contains a single trailing space on the second, fourth, and sixth lines.

Port of *@negativeSeven*'s Python 2 answer, so make sure to upvote him!

Try it online.

**Explanation:**

Replace all `"/"` with a `" "`:

```
/

```

Append 5 trailing spaces:

```
$
5*
```

Replace all substrings of size six that do not start with a space by `"----- "`:

```
\S.{5}
5*-
```
> 2 votes

# Answer
# Jelly, 35 bytes

```
;3x5¤;0;ṛṫ6ɗ
;⁶x5¤e€⁾o\œṡ1ç/$ÐLị⁾-

```

Try it online!

A monadic link that takes the input as a string and returns a Jelly string with the platforms.

Takes inspiration from @negativeseven’s answer.
> 1 votes

# Answer
# 05AB1E, ~~25~~ 24 bytes

```
ð5×«'/ð:DŒ6ùʒнðÊ}'-5×ð«:

```

Port of *@negativeSeven*'s Python 2 answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

```
ð5×«                      # Append 5 trailing spaces to the (implicit) input-string
    '/ð:                 '# Replace all "/" with a space
        D                 # Duplicate the string
         Œ                # Get all substrings of this
          6ù              # Only leave those of length 6
            ʒ   }         # Filter it further by:
             нðÊ          #  Only keep those which do NOT start with a space
                 '-5×ð«  '# Push a string of 5 "-" appended with a space: "----- "
                       :  # Replace in the initially duplicated string all substrings
                          # remaining in the list with this "---- "

```
> 1 votes

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


title: Implement a strongly Darboux function

text:
# Question
Title: Implement a strongly Darboux function
According to Wikipedia, a strongly Darboux function is

> one for which the image of every (non-empty) open interval is the whole real line

In other words, a function \\$f\\$ is strongly Darboux if given 3 arbitrary real numbers \\$a\\$, \\$b\\$, and \\$y\\$, it is always possible to find an \\$x\\$ between (distinct) \\$a\\$ and \\$b\\$ such that \\$f(x) = y\\$.

For the purposes of this challenge, we will consider strongly Darboux functions over the rationals instead.

Your challenge is to write a program or function that:

* gives a rational number as output for every rational number input,
* always gives the same output for a given input, and
* has the strongly Darboux property.

Input and output may be either of the following:

* an arbitrary-precision number type, if your language has one (or has a library for one, e.g. GMP).
* a string representation of the number, which you may assume will always contain a decimal point and at least one digit on either side. It may be in any base \\$b \geq 2\\$, but input and output must be in the same base. You may use any set of characters for the digits and decimal point (but again, they must be consistent between input and output).

The input will always have a terminating base \\$b\\$ expansion. As for the output, which may have a theoretically non-terminating base \\$b\\$ expansion depending on your choice of function, you may choose any of the following:

* output digits forever.
* take an additional integer as input and output at least that many digits.
* output at least as many digits as are in the input (which may contain trailing zeroes).

Note that by the nature of this challenge, the convention that numbers may be assumed to be representable by standard number types does **not** apply, except for the second input described in option 2 above.

To avoid loopholes with functions that are only defined on non-terminating rationals, your submission must be able to produce output arbitrarily close to a desired value **in practice**. Formally, given rational numbers \\$a\\$, \\$b\\$, \\$y\\$, and \\$\varepsilon\\$, there must be a rational number \\$x\\$ that terminates in your chosen base such that \\$a\<x\<b\\$ and \\$|f(x)-y|\<\varepsilon\\$.

---

To give you some ideas, here is a description of the Conway base 13 function:

* Convert \\$x\\$ to base 13 and remove the decimal point.
* If the result is of the form \\$\[x\]A\[y\]C\[z\]\_{13}\\$, where \\$\[y\]\\$ and \\$\[z\]\\$ consist of only digits from 0 to 9, then \\$f(x) = \[y\].\[z\]\\$.
* If the result is of the form \\$\[x\]B\[y\]C\[z\]\_{13}\\$, where \\$\[y\]\\$ and \\$\[z\]\\$ consist of only digits from 0 to 9, then \\$f(x) = -\[y\].\[z\]\\$.
* Otherwise, \\$f(x) = 0\\$.

This function is strongly Darboux. Say, for example, that we want to find some \\$x\\$ between \\$123.456\_{13}\\$ and \\$123.457\_{13}\\$ such that \\$f(x) = 7.89\\$. The base-13 value \\$123.456A7C89\_{13}\\$ would satisfy this requirement.

Your submission may be an implementation of this function, although I suspect that there are other strongly Darboux functions that are a lot shorter to implement. :)

# Answer
> 5 votes
# Retina 0.8.2, ~~43~~ 50 bytes

```
^.*\.(..)*1(.)((..)+)1.((..)*)$
$2$*-$3.$5
0(.)
$1

```

Try it online! I/O is as a binary string. Encode a binary number `y` close to another binary number `a` as follows:

1. If `a` does not contain a `.`, suffix one.
2. If `a` contains an odd number of digits after the `.`, suffix a `0`.
3. If `y` is negative then suffix `11` otherwise suffix `10`.
4. For each digit in `y`, suffix `0` followed by that digit.
5. If `y` contains a `.`, suffix `11` at that point, otherwise suffix it after all the digits in `y`.

Explanation:

```
^.*\.(..)*1(.)((..)+)1.((..)*)$
$2$*-$3.$5

```

Pair the digits starting at the binary point. If the number is a valid encoding, then decode the last `1x` digit pair to a `.` and the second last to an optional `-` sign. Digits before that are ignored.

```
0(.)
$1

```

This should just leave pairs that begin with `0`, so delete the `0`s.

# Answer
> 1 votes
# Jelly, 71 bytes

```
L7*©ṛḅ7WµṪ×⁵d®µ⁴‘¤Ð¡ḊṖ
DF7,8ṣṪ¥ƒṣ9ḅ7×ɗÇƭ€j”,
DFf7r9¤ṫ-Ḍ⁼Ɱ“OY‘TịØ+³çƲ0Ẹ?

```

Try it online!

A full program that takes a base-10 number as input and output and implements the Conway base 13 function but using bases 7 and 10 rather than 10 and 13. Both input and output use comma as a decimal separator. Output will have a leading - for negative numbers.

# Answer
> 1 votes
# Retina, ~~28~~ ~~25~~ ~~26~~ 28 bytes

```
.*11|22
.
D^`\.
^3
-
4(.)
$1

```

Try it online!

### Explanation

```
.*11|22     Delete up to the last 11 and prepend a dot. Also change 22 to a dot.
.
D^`\.       Keep only the last dot, if there is one.
^3          Change 3 at the beginning to a minus sign.
-
4(.)        4 is the escape character.
$1

```

It may output leading and trailing zeros, and numbers without a integer part.

It could be golfed 2 or 3 bytes more if I could use `4+`. But I'm not sure how to define the theoretical result if the input has an endless stream of `4`s.

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


# Question
Title: Print the previous answer in reverse - with a catch (pt. 2)
Your challenge is very simple: output the previous answer, in reverse.

However, as with this similarly-titled question, there's a catch: in this case, you **cannot** use characters from the answer *before* the last. For example:

Let's say the first answer looks like this:

> 1 - Python
>
> `print('hi!')`

And the second answer looks like this: (see 'Chaining' section for more info)

> 2 - Javascript
>
> `console.log(")'!ih'(tnirp")`

Now, it would be my job to write the third answer: a program to output the text `)"print('hi!')"(gol.elosnoc`, **without** using the characters `p`, `r`, `i`, `n`, `t`, `(`, `'`, `h`, `i`, `!` and `)`. I can choose whatever language I like to complete this task.

# Chaining

The first answer can output any text: but it *must* **output** *something*. The second answer should simply output the first answer in reverse, using any characters you like. The further rules about restricted characters, as described above, come into play from the third answer onwards.

# Scoring

Your score is \\$\frac{l\_{n}}{l\_{n-1}} - l\_{n-2}\\$, where \\$l\_x\\$ represents the length of the \\$x\\$th answer, and \\$n\\$ is the position your answer is at in the chain. (all lengths are in bytes; if your answer is no. 1 or no. 2 then miss out \\$l\_{n-1}\\$ and/or \\$l\_{n-2}\\$ where necessary.)

Best (lowest) score by August 1st wins.

# Formatting

Please format your post like this:

```
[Answer Number] - [language]

    [code]
    (preferably a TIO link)

SCORE: [Submission Score]

(notes, explanations, whatever you want)

```

*Everything in square brackets is a required argument to fill in; everything in normal brackets is an optional argument; everything not in brackets is there to make the snippet work.*

# Rules

* All characters, etc. are case sensitive.
* Preceeding/trailing whitespace is allowed, within reason (I'm looking at you, Whitespace).
* Every submission must be a unique language.
* You must wait at least 1 hour before submitting a new answer if you have just posted.
* You may **NOT** submit two answers in a row, you must wait for TWO more submissions before posting a new answer.
* Of course, standard loopholes are disallowed.
* Please make sure to triple check that your answer is valid. This is especially important, because someone may start writing their answer based on yours, so if it's wrong you can't really edit it any more... and the whole chain breaks down. Also, you can't edit answers for continuity purposes.
* Standard I/O methods are allowed.

# Answer list/used languages

```
$.ajax({type: "GET",url: "https://api.stackexchange.com/2.2/questions/187674/answers?site=codegolf&filter=withbody&sort=creation&order=asc",success: function(data) {for (var i = 0; i < data.items.length; i++) {var temp = document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];try {temp.innerHTML += " - <i>Score: " +data.items[i].body.split("SCORE")[1].split("\n")[0].match(/(?<!h)[+-]?(\d+(\.\d+)?)/g).slice(-1)[0].trim() +"</i>";} catch (TypeError) {temp.innerHTML += " (no score)";} finally {$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}}})
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <base href="https://codegolf.stackexchange.com">
   <ul id="list"></ul>
```

# Answer
> 1 votes
# 7-str

```
`DwJRK…E•EDo†LZ–w<SK…T>>Q<Sv‡D<J<I<G<>•‡GMMK•<ʇ̃?ό‰—íɁÍ‰ð̈́‰’ñÇùÿȫ<w<…><>_RQRRMKSQKKRKMRRNMLKQKRITK‡w•„‡GPK•<LSRL[J[b•ULXQLNaJ\\Z•NLQ˜“Lj<`D-D-o;

```

## Score: \\$\frac{187}{171}-212 = -210.906432748538\\$

Note that the code contains many unprintable characters.

The big string between the ```s is the reversed code of the Stax answer encoded by adding 26 (I brute-forced this number) to each codepoint. The str code then undoes this by subtracting 26 from the string before outputting it (You can subtract integers from strings, which does math on each codepoint, in this language)

Try it online!

# Answer
> 2 votes
# 1 - 05AB1E

```
"Hello, World!"

```

SCORE: \\$\frac{15}{1} - 0 = 15\\$

Try it online!

# Answer
> 1 votes
# 5. Runic Enchantments

```
")(esre"1´18k+"er.'"$7´884k$8´216k$7´690k$8´318k$8´220k$3´80k$1´87k$9´5k$7´814k$1´64k$1´61k$8´220k$1´18k$3´91k:$$7´776k$8´220k$8´310k$4´28k$3´04k$2´09k$1´69k$7´693k$1´61k$8´220k$"'tnirp"@

```

Try it online!

Encodes the Jelly portion as number literals. Its disgusting. Also, answer #7 will have a super low score. Which is also disgusting. Next.

## SCORE: 212÷77-25 = -22.246753247

# Answer
> 1 votes
# 6 - Stax

```
"P2y~724{@BB0G427>u2;{HA0A2uu892"{16-mj{]m1:/8171234883181179138878E$"$k"]\"ȑåß×xo̪Öo³ȧÓ}oβ%˩ɭ"{133-m{$"-"/"0"*m\9"7$$:k19"]|@2lU*+{+k180]*

```

Run and debug online

## Score: 171 ÷ 212 - 77 = -76.19

My first Stax answer. I’m sure it could be golfed better, but each byte is only worth \\$\frac{1}{212}\\$ points.

# Answer
> 0 votes
# 2 - Japt

```
`"HÁM, Wld!"`w

```

Try it \- Note the unprintable (codepoint 142) between the `W` and the `l`.

**SCORE: 15÷15-0=1**

---

Everything between the backticks is simply the source of the first solution compressed with Shoco. The backticks decompress it and the `w` reverses the result.

# Answer
> 0 votes
# 3 - Jelly

```
“¡ḍ©ÑİƬ⁶“ṠƇƇv“¡¤Ẇ_»ż“⁾Ḋ‘Ọ

```

Try it online!

## SCORE: 25 ÷ 15 - 15 = -13.33

No unprintable characters. Verification that no characters from 1 used.

# Answer
> 0 votes
# 4 - Groovy

```
print'“¡ḍ©ÑİƬ⁶“ṠƇƇv“¡¤Ẇ_»ż“⁾Ḋ‘Ọ'.reverse()

```

Try it online!

### SCORE = 77/25 - 15 = -11.92

---
Tags: code-challenge, restricted-source, answer-chaining
---


title: In-between fractions

text:
# Question
Title: In-between fractions
# In-between fractions

**The challenge:**

You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.

Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)

**Rules:**

1. The input "fraction" will always be a valid fraction, less than 1; example "1/4"
2. The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.
3. The input integers can be negative.
4. Outputted fractions should be reduced as much as possible (simplified)

The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.

The code should be a program or function as stated here

**Example 1:**

Input: `-2,3,"1/2"`

Output:

```
 -2
 -3/2
 -1
 -1/2
  0
  1/2
  1
  3/2
  2
  5/2
  3

```

**Example 2:**

Input: `1,2,"2/3"`

Output:

```
1
5/3
2

```

or

```
1
4/3
2

```

Note: Counting can start from either direction (thank you @Mego)

This is , so the shortest answer in bytes wins.

# Answer
> 5 votes
# Octave, ~~34~~ 30 bytes

```
@(a,b,c)rats(union([a:c:b],b))

```

Now takes the fraction as a numeric expression rather than separate numerator and denominator.

Sample on ideone

# Answer
> 11 votes
## Mathematica, 16 bytes

```
Range@##⋃{#2}&

```

An unnamed function that takes two integers and a rational number and returns a list of numbers, e.g.:

```
Range@##⋃{#2}&[-2, 3, 1/2]
(* {-2, -(3/2), -1, -(1/2), 0, 1/2, 1, 3/2, 2, 5/2, 3} *)

```

Mathematica's `Range` does exactly what the challenge asks, except that it omits the upper bound if the difference between lower and upper bound isn't exactly a multiple of the step size. Therefore we take the `Union` (using ) with the list containing only the upper bound which ensures that it appears exactly once. Note that `Union` will sort the result but we want it sorted anyway, since the step size is always positive. Also since we're working with rationals, they're automatically reduced as much as possible.

# Answer
> 10 votes
# T-SQL 2012+, ~~831~~ ~~535~~ ~~477~~ ~~270~~ ~~246~~ ~~240~~ 219 bytes

Please note this is a one liner - sql doesn't have build in function to reduce the fraction. May not be the best language for this type of question. It is human readable(kind of - compared to some of the other languages).

```
DECLARE @f INT=-5,@t INT=3,@n INT=3,@ INT=8;

WITH C as(SELECT
top((@t*@-@f*@)/@n+1)ROW_NUMBER()OVER(ORDER BY @)M
FROM sys.messages)SELECT(SELECT
IIF(V%@=0,LEFT(V/@,9),CONCAT(V/MAX(M),'/',ABS(@)/MAX(M)))FROM c
WHERE V%M=0AND @%M=0)FROM(SELECT
@f*@+@n*~-M V FROM c)k

```

**Try it online**

# Answer
> 6 votes
## Python 2, 81 bytes

```
from fractions import*
a,b,c=map(Fraction,input())
while a<b:print a;a+=c
print b

```

Try it online

# Answer
> 5 votes
# Ruby, ~~32~~ ~~54~~ 48 bytes

```
->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}

```

This solution is based on Mego's Python answer and assumes that `c` will always be a `Rational`, Ruby's fraction format. Try it online!

**Edit:** Fixed a bug where integers weren't presented like integers. -6 bytes thanks to Not That Charles and MegaTom.

The functions are called in this way:

```
> f=->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
> f[1,4,Rational(2,3)]
1
(5/3)
(7/3)
3
(11/3)
4

```

# Answer
> 5 votes
# Haskell, ~~31~~ 26 bytes

```
f a b c=min[b]$a:f(a+c)b c

```

Lazy evaluation FTW! Demo:

```
*Main> import Data.Ratio
*Main Data.Ratio> f (-2) 3 (1%2)
[(-2) % 1,(-3) % 2,(-1) % 1,(-1) % 2,0 % 1,1 % 2,1 % 1,3 % 2,2 % 1,5 % 2,3 % 1]
*Main Data.Ratio> f 1 2 (2%3)
[1 % 1,5 % 3,2 % 1]

```

(I was initially tempted by Haskell’s `[a,a+c..b]` notation, but it has some quirks that necessitate something like `f a b c|l<-[a,a+c..b-c/2]=l++[b|last l<b]` for 41 bytes or `f a b c=[x|x<-[a,a+c..],x<b]++[b]` for 33.)

# Answer
> 5 votes
# MATL, ~~16~~ 15 bytes

```
3$:3Gvu9X10ZGZD

```

This may fail for very large denominators. I hope output format is acceptable.

**Try it online!**

```
3$:    % take three inputs and generate range
3G     % push third input again
v      % vertically concatenate. Gives vertical array as output
u      % get unique elements (i.e. remove the last one if it is repeated)
9X1    % predefined literal 'rat'
0ZG    % set rational format
ZD     % display using that format

```

# Answer
> 3 votes
# Matlab with Symbolic Toolbox / Octave with SymPy, 27 bytes

*Thanks to @sanchises for pointing out an error, now corrected*

```
@(a,b,c)sym(union(a:c:b,b))

```

This is an anonymous function. To call it, assign it to a variable or use `ans`.

Example:

```
>> @(a,b,c)sym(union(a:c:b,b))
ans =
    @(a,b,c)sym(union(a:c:b,b))
>> ans(-2,3,1/2)
ans =
[ -2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2, 5/2, 3]

```

# Answer
> 3 votes
# Julia, 14 bytes

```
f(a,b,c)=a:c:b

```

This is similar to the Mathematica answer, except that Julia's ranges are already in the desired format, so it is even shorter. Also returns a collection of numbers. Example output:

```
11-element StepRange{Rational{Int64},Rational{Int64}}:
 -3//1,-5//2,-2//1,-3//2,-1//1,-1//2,0//1,1//2,1//1,3//2,2//1

```

Note that the integers are displayed with 1 in the denominator, and a double-slash is used for fractions. To get the output exactly as defined in the question requires some more code:

```
f(a,b,c)=map(x->println(x.num,x.den<2?"":"/$(x.den)"),a:c:b)

```

# Answer
> 2 votes
# Javascript, ~~108 90 86~~ 81 bytes

```
(a,b,n,d)=>{var s="";for(a=a*d;a<b*d;a+=n)s+=(a%d?a+"/"+d:a/d)+" ";s+=b;return s}

```

An anonymous function. After assignment to a named variable with white space:

```
var f=(a,b,n,d)=>
{ var s="";
  for(a=a*d; a<b*d; a+=n)
    s+= (a%d ? a + "/" + d : a/d) + " ";
  s+=b;
  return s
}

```

Test examples:

```
console.log(f(1,2,1,8)); //writes:
1 9/8 10/8 11/8 12/8 13/8 14/8 15/8 2

console.log(f(-3,3,4,7)); // writes:
-3 -17/7 -13/7 -9/7 -5/7 -1/7 3/7 1 11/7 15/7 19/7 3

```

An imperative approach using javascript, no recursion, library or functional programming.

# Answer
> 1 votes
# Smalltalk – 89 bytes

For once Smalltalk is almost competitive!

```
Number extend[p:e q:i[|h|self to:e by:i do:[:x|h:=x. x printNl].h=e ifFalse:[e printNl]]]

```

Call like this:

```
> 2 p:5 q:1/2
2
5/2
3
7/2
4
9/2
5

> 1 p:2 q:2/3
1
5/3
2

```

# Answer
> 1 votes
## R - 71 bytes

Assumes you have already installed the `MASS` package

```
f=function(x,y,z)MASS::fractions(union(seq(x,y,eval(parse(text=z))),y))

> f(1, 2, '1/3')
[1]   1 4/3 5/3   2
> f(2, 5, '1/2')
[1]   2 5/2   3 7/2   4 9/2   5

```

# Answer
> 1 votes
## Pyret, 56 bytes

```
{(b,e,n,d):link(e,map(_ / d,range(b * d, e * d))).sort()}

```

Takes in beginning (b), end (e), numerator (n), and denominator (d). Creates a range of integers, divides those through and appends the end to the list (by linking and then sorting).

---
Tags: code-golf, number, sequence, rational-numbers
---


title: Can the cursor reach the bottom?

text:
# Question
Title: Can the cursor reach the bottom?
In a matrix of characters, a **cursor** is a movable position between two adjacent characters, before the first character or after the last character in a line, like that "I"-shaped indicator which moves while you type.

In this challenge, a cursor position is considered **valid** if at least one of its two sides touches a space. The cursor travels through valid positions in a matrix, by moving up, down, left or right by one position each time. It could also move left or right though the line separator, to the end of the previous line, or the beginning of the next line respectively.

Given a character matrix as input, and a cursor initially at the top left corner, your task is to determine whether it can reach the bottom line.

This is a and problem; the rules of this question is the same as what these two tags specified.

### Rules

* You can assume that the input consists only of `.`, , and newlines. (Only these three characters and no more characters; otherwise its behavior is undefined.)
* You may require there must or must not be a trailing newline in the input, if you want to.
* **Your code should output either a truthy value (if the condition is true), or a falsy value (if the condition is false).**

### Examples

Example input(where  is the space character):

```
░.....░
░......
.░.░.░.
.░░░░░░
......░

```

The cursor can reach the bottom in this case. This process of moving the cursor will work: down, right(touches spaces on the left), down(touches spaces on the right), down, right(touches spaces on both sides) 6 times, and down(touching spaces on the left).

This will also work( still represent spaces):

```
░░
.░
.░

```

The cursor starts at the up-left corner. After moving right two times, it can move down twice, which touches the bottom of the lines.

This example will not work( represent spaces again):

```
░...
...░

```

The cursor cannot move down, as there is no sufficient whitespace to be touched. There are only newline characters on the right of the input, and there are no newline characters on the left(otherwise a line would have spanned two lines.)

The cursor can also move up and left, in order to solve a maze-like input as in this one:

```
░....
░░░░.
...░.
.░░░.
░....
░░░░░

```

In this case, the cursor has to move left in order to get through spaces and get to the bottom line.

Here is another important test case: the cursor **can** move left or right to another line.

```
░░░░
...░
░...

```

In this case, the cursor can reach the last line, as the cursor can move left or right in order to get to the next line. Moving the cursor down is blocked on the right position of row 2, column 4; however, the cursor can still get to the last line if it moves right (touching spaces).

This is a fairly interesting test input:

```
░░..░
░...░
....░

```

In this case, the cursor can reach the last line, by moving down and left to the end of the first line, then down twice to reach the end of the bottom line.

# Answer
# Jelly, ~~47~~ 43 bytes

```
p®§Qæ%L}>Ƈ0ịƇ
=⁶oŻ$€µZL;1;N$©ṛF1çƬFṀ’:®Ḣ‘=L

```

Try it online!

A full program that takes a list of strings as its argument and returns 1 if the bottom line is reachable and 0 if not.

## Explanation

### Helper link

Test moves up, down left and right and extend reachable position list. Left argument: most recently added reachable position list; right argument: boolean list of whether each possible position is valid

```
 p®            | Cartesian product with each of the values stored in the register (the width of the position list, 1 and the negation of each)
   §           | Sum each of these
    F          | Flatten
     Q         | Uniquify
      æ%L}     | Symmetric mod using the length of the valid position list: this will mean any positions that move off the top or bottom will be negative
          >Ƈ0  | Filter out those reachable positions which are negative
            ịƇ | Filter out those which are invalid

```

### Main link

Takes a single argument, a list of Jelly strings representing the grid

```
=⁶                             | Check of equal to space
   oŻ$€                        | Logical or each row with itself prepended with zero; this yields rows 1 longer, and will indicate whether each cursor position is valid
       µ                       | Start a new monadic chain
        ZL                     | Zip and get the length (will be the length of each row)
          ;1                   | Concatenate 1
            ;N$©               | Concatenate the negations and store in the register (i.e. width, 1, -width, -1)
                ṛF             | Replace with the flattened grid of position validity
                  1çƬ          | Call the helper link, starting with 1 as left argument and using the flattened position validities as right. Repeat until unchanged. Return all collected values.
                     F         | Flatten, getting all reachable positions (may include duplicates)
                      Ṁ        | Maximum position reached
                       ’       | Decrease by 1 (because of 1-indexing)
                        :®     | Integer divide by the register
                          Ḣ    | Head (will effectively be max position integer divided by width)
                           ‘   | Increase by 1
                            =L | Check if equal to length (i.e. height) of position grid

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 60 bytesSBCS

Full program. Prompts for character matrix from stdin. Prints 1 or 0 to stdout. Requires zero-indexing (`⎕IO←0`) which is default on many systems.

```
P←{' '0∊⍨s←(×⍨≢⍺)⊃,⍵:1∊⍵⋄s}
1∊⊢⌿{P⌺3 3⊢(⍴⍵)⍴1@0P⌺3,⍵}⍣≡3/3⌿⎕

```

Try it online! (space characters replaced by  for clarity)

The method here is basically to seed fill from the top left corner, but alternating between 1D and 2D seed fill to account for line wrapping and vertical/diagonal motion. Diagonal motion is simple horizontal motion followed by vertical motion, since the cursor sits in between adjacent characters.

The first line defines a helper function `P`(rocess) which will be called on each neighbourhood.

`P←{``}` "dfn";  is the neighborhood,  is the number of padded elements for each dimension:

`,⍵` ravel (flatten) the neighbourhood into a list

`(``)⊃` pick the following element from that:

the paddings per dimension (so a 1 or 2 element list, depending on  being 1D or 2D)

the tally of that (1 or 2)

`×⍨` the square of that (lit. multiplication selfie; 1 or 4)

`s←` assign to `s`(elf; i.e. the centre of the neighbourhood)

`' '0∊⍨` is that a member of `[" ",0]`?

`:` if so:

`1∊⍵` return whether the neighbourhood has a one

else:

`s` return `s`(elf unmodified, i.e. leave as-is for now)

The second line is the main part of the program:

prompt for evaluated input via the console (stdin)

`3⌿` triplicate each row (ensures we have at least 3 — makes no difference to connectivity)

`3/` triplicate each column (ensures we have at least 3 — makes no difference to connectivity)

`{``}⍣≡` apply this function repeatedly until two successive results are identical (i.e. until stable):

`,⍵` ravel (flatten) the matrix into a list

`P⌺3` apply `P` to each neighbourhood of 3 elements

`1@0` replace the current value **at** position `0` with a `1` (this seeds the top left corner)

`(``)⍴`**r**eshape that into the following shape:

`⍴⍵` the original shape of the matrix

`⊢⌿` get the bottom row (lit. vertical right-reduction)

`1∊` is there any `1` there?
> 3 votes

---
Tags: code-golf, string, decision-problem, grid, path-finding
---


title: See you in another life, brotha!

text:
# Question
Title: See you in another life, brotha!
Most of us LOST fans out there remember the computer that Desmond had to type the characters "4 8 15 16 23 42" in every 108 minutes or the world would end (or would it?).

The challenge here is to create a program that would do the same thing by requiring that every 108 seconds the input `4 8 15 16 23 42` is entered or it will display the message

```
Sorry, the world has ended with status code -1

```

It should warn the user at 100 seconds that they need to enter a number with the message

```
Enter, Quick!

```

The program must be able to read input at any time and if it is the correct input it will reset the timer. If incorrect input is given nothing happens.

The program should run indefinitely. So the timeline after the last valid input looks like

From 0 to 99 seconds: no output
At 100 seconds: `Enter, Quick!`
At 108 seconds: `Sorry, the world has ended with status code -1`.

This is code golf so the shortest answer (in bytes) that accomplishes this task wins! Good Luck!

# Answer
> 10 votes
# bash, 160 bytes

```
I()($s 100&&echo Enter, Quick!&$s 108&&echo Sorry, the world has ended with status code -1&)
i()(read r;[[ $r = '4 8 15 16 23 42' ]]&&pkill $s&&I;i)
s=sleep;I;i

```

I'm currently uncertain what the expected behavior is after "the world has ended".

Run like this:

```
bash lost.sh 2>&-

```

`2>&-` is required to ignore STDERR, which is allowed by default.

# Answer
> 2 votes
## Modern-browser JavaScript, ~~252~~ ~~247~~ 242 bytes

```
n=t=>Date.now()+(t?0:1e5)
d=n(i=f=0)
onkeyup=e=>{if("4 8 15 16 23 42".charCodeAt(i%15)==e.keyCode&&++i%15<1)d=n(f=0)}
setInterval('if(n(1)>d&&f<2)d=n(1)+8e3,console.log(f++?"Sorry, the world has ended with status code -1":"Enter, Quick!")',9)

```

Instructions: run this in the console of a blank tab, click on its document to gain focus and start repeatedly typing the string. As long as you're doing well, you'll get no feedback whatsoever. Refresh and change 1e5 to 1e4 to make things more interesting.

# Answer
> 1 votes
# Groovy, 244 or 228 bytes

I wrongly remembered Java having a nextLine method that took an argument of how long to wait, so I thought this would be easy. I couldn't find a method that did that, so I implemented this with two threads. It's a bit bulky. Oh well.

```
t=Thread.start{while(1)try{Thread.sleep(1e5);println "Enter, Quick!";Thread.sleep(8e3);println "Sorry, the world has ended with status code -1";System.exit(-1)}catch(e){}};while(1)if(System.console().readLine()=="4 8 15 16 23 42")t.interrupt()

```

This assumes the proper behavior for the world ending is for the process to exit with a status code of -1. If the intended behavior is to keep looping and expect an external force to end the world (and by extension, the program), the `;System.exit(-1)` portion can be omitted to save 16 bytes. Yay.

I originally wrote this to use the hashCode of the string, but that wound up *longer* than an exact comparison embedding the string because `hashCode` is long.

# Answer
> 1 votes
# APL (Dyalog Unicode), 144 bytesSBCS

As it turns out, both sides are running APL…

```
:For t:In 100 8
:For s:In⍳t
→{1E3::⍬⋄⍳⍞≡⍕4 8 15 16 23 42}⎕RTL←1
:End
⊃'Enter, Quick!' 'Sorry, the world has ended with status code -1'⌽⍨t=8
:End

```

Try it online!

`:For t:in 100 8` loop twice, once with `t`(timput) being `100` and then with `t` as `8`:

`:For s:In⍳t` for `s`(econds) `1` through and all the **ɩ**ndices until `t`

`⎕RTL←1` set the **R**esponse **T**ime **L**imit to 1 (second)

`{``}` apply the following anonymous lambda to that (although this argument is unused)

`1E3::` in the following, if any exception happens:

return `[]`

try:

`⍕4 8 15 16 23 42` stringify the required numbers

`⍞≡` prompt for input and compare to that (gives 0 or 1)

the first that many **ɩ**ndices (`[]` or \[1\]\`

go to that line (1 if `[1]`, continue on next line if `[]`)

`:End` end of inner loop; proceed with next second of the current timeout

`t=3` is this the second timeout (0 or 1)?

…`⌽⍨` rotate the following that many steps:

`'Enter, Quick!' 'Sorry, the world has ended with status code -1'` implicitly print appropriate text

disclose (to print without leading and trailing space)

`:End` end of outer loop: after warning, loop; after printing "Sorry…", proceed to terminate program

# Answer
> 0 votes
# C++ (gcc), 395 bytes

Compiling on Linux requires the `-pthread` switch. MinGW does without.

```
#import<iostream>
#import<thread>
using namespace std;auto N=chrono::steady_clock::now;auto L=N();int w;int main(){thread A([]{for(;;){auto t=chrono::duration_cast<chrono::seconds>(N()-L).count();t>99&&!w?puts("Enter, Quick!"),w=1:t>107?exit(puts("Sorry, the world has ended with status code -1")),0:0;}}),B([]{for(string s;;s=="4 8 15 16 23 42"?L=N(),w=0:0)getline(cin,s);});A.join();B.join();}

```

Try it online!

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