title: Additional facts!

text:
# Question
Title: Additional facts!
In mathematics, the factorial, shortened "fact" of a non-negative integer **n**, denoted by **n!**, is the product of all positive integers less than or equal to **n**. For example, **5!** is **1 * 2 * 3 * 4 * 5 = 120**

The factorial of **0** is **1**, according to the convention for an empty product.

---

These are the regular facts we are used to. Let's add some alternatives:

1. The factorial (defined above)
2. The double factorial: **n!! = 1 + 2 + ... + n**
3. The triple factorial: **n!!! = 1 - (2 - (3 - ( ... - n)))...)**
4. The quadruple factorial: **n!!!! = 1 / (2 / (3 ... / n)))...)**. Note: This is floating point division, not integer division.

---

### Challenge

Take a non-negative integer input **n**, directly followed by between **1** and **4** exclamation marks. The input will look (exactly) like this: **0!**, **5!!**, **132!!!** or **4!!!!**. In this challenge, you may not assume a flexible input format, sorry.

### Output

The output should be the result, on any convenient format. The result of the quadruple factorial must have at least 2 digits after the decimal point, except for **0!!!! = 0**.

### Test cases:

```
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
---
0!! = 0
1!! = 1
2!! = 3
3!! = 6
4!! = 10
5!! = 15
6!! = 21
7!! = 28
8!! = 36
9!! = 45
10!! = 55
---
0!!! = 0
1!!! = 1
2!!! = -1
3!!! = 2
4!!! = -2
5!!! = 3
6!!! = -3
7!!! = 4
8!!! = -4
9!!! = 5
10!!! = -5
---
0!!!! = 0
1!!!! = 1
2!!!! = 0.5
3!!!! = 1.5
4!!!! = 0.375
5!!!! = 1.875
6!!!! = 0.3125
7!!!! = 2.1875
8!!!! = 0.27344
9!!!! = 2.4609
10!!!! = 0.24609

```

The shortest solution in each language wins.

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

```
s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))

```

### Test cases

```
let f =

s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))

for(o = '!'; o <= '!!!!'; o += '!') {
  for(n = 0; n <= 10; n++) {
    console.log(n + o + ' = ' + f(n + o));
  }
}
```

### Formatted and commented

```
s =>                                // given the input string s,
  eval(                             // evaluate as JS code:
    ( [a, b] = s.split(/\b/),       //   a = integer (as string) / b = '!' string
      g = k =>                      //   g = recursive function taking k as input
        +a ?                        //     if a is not zero:
          k - a ?                   //       if k is not equal to a:
            k + '_*+-/'[b.length] + //         append k and the operation symbol
            `(${g(k + 1)})`         //         append the result of a recursive call
          :                         //       else:
            k                       //         just append k and stop recursion
        :                           //     else:
          +!b[1]                    //       return 1 for multiplication / 0 otherwise
    )(1)                            //   initial call to g() with k = 1
  )                                 // end of eval()

```

# Answer
> 7 votes
## Husk, 15 bytes

```
§!ëΠΣF-F/#'!oṫi

```

Try it online!

## Explanation

Indexing into a list of functions: the joys of using a functional language.

```
§!ëΠΣF-F/#'!oṫi  Implicit input, say x = "6!!!"
              i  Convert to integer (parses the leading sequence of digits): 6
            oṫ   Descending range to 1: y = [6,5,4,3,2,1]
  ë              Four-element list containing the functions
   Π             product,
    Σ            sum,
     F-          left fold with subtraction (gives 0 for empty list), and
       F/        left fold with division (gives 0 for empty list).
 !               1-based index into this list with
         #'!     count of !-characters in input: gives F-
§                Apply to y and print implicitly: -3

```

I use a descending range and left folds, since `-` and `/` take their arguments in reverse order in Husk.

# Answer
> 6 votes
# C# (.NET Core), 134 130 128 bytes

```
s=>{double e=s.Split('!').Length,n=int.Parse(s.Trim('!')),i=n,r=n;for(;--i>0;)r=e>4?i/r:e>3?i-r:e>2?i+r:i*r;return n<1&e<3?1:r;}

```

Try it online!

The best part of code golfing are the things you learn while trying to solve the challenges. In this one I have learnt that in C# you can trim other characters besides whitespaces from strings.

* 4 bytes saved thanks to LiefdeWen!
* 2 bytes saved because I do not need to substract 1 to `s.Split('!').Length`, just fix the limits in `e>4?i/r:e>3?i-r:e>2?i+r:i*r` and `n<1&e<3?1:r`.

# Answer
> 4 votes
# Perl 5, 62 bytes

**61 bytes code + 1 for `-p`.**

```
$_=/^0!$/+eval join(qw{| *( +( -( /(}[s/!//g],1..$_).")"x--$_

```

Thanks to @G B for pointing out a miss on my part!

Try it online! (this uses `-l` for readability)

# Answer
> 4 votes
# Python3, 124 130 ~~121~~ 119 bytes

At this point, I believe that recursion is the key to further byte saving.

```
s=input()
l=s.count('!')
v=int(s[:-l])+1
print(eval((" *+-/"[l]+"(").join(map(str,range(1,v)))+")"*(v-2)or"0")+(l<2>v))

```

Try the testcases on Try it online!

-9 bytes thanks to @Mr.Xcoder!

-2 bytes thanks to @Felipe Nardi Batista!

# Answer
> 4 votes
# , ~~113~~ 111 bytes

```
function(s){z=strtoi((n=strsplit(s,'!')[[1]])[1])
n=length(n)
`if`(z,Reduce(c('*','+','-','/')[n],1:z,,T),n<2)}

```

Try some test cases!

ungolfed:

```
function(s){
  n <- strsplit(s,"!")[[1]]          # split on "!"
  z <- strtoi(n[1])                  # turn to integer
  n <- length(n)                     # count number of "!"
  FUN <- c(`*`,`+`,`-`,`/`)[[n]]     # select a function
  right <- TRUE                      # Reduce (fold) from the right
  if( z > 0)                         # if z > 0
    Reduce(FUN, 1:z,,right)          # return the value
  else
    (n < 2)                          # 1 if n = 1, 0 if n > 1
}

```

# Answer
> 3 votes
# Pyth, ~~34~~ 30 bytes

```
+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!

```

Try it online!

### Explanation

```
+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!"Q    Implicit: append "Q
                                    Implicit: read input to Q
                      .vQ           Evaluate Q as Pyth code. This evaluates the integer,
                                    any !'s are parsed as unary NOT for the next expression
                                    and discarded.
                     K              Save the result to K.
                    U               Get a list [0, 1, ..., K-1].
                   t                Drop the first item to get [1, 2, ..., K-1].
                  _                 Reverse to get [K-1, K-2, ..., 1].
 u                       K          Starting from G = K, for H in [K-1, K-2, ..., 1] do:
             /Q\!                     Count the !'s in Q.
      @"/*+-"                         Get the correct operator.
    +H                                Prepend the current H.
   +             G                    Append the previous value G.
  v                                   Evaluate as Python code.
                          q"0!"Q    See if Q == "0!".
+                                   If so, add 1.

```

# Answer
> 2 votes
# Ruby, ~~83 80~~ 79 bytes

```
->s{z=s.count ?!;s<?1?1+1<=>z:eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)}

```

Try it online!

### Explanation:

```
->s{
    # Get number of !
    z=s.count ?!

    # Special case: if the number is 0, then output 0 or 1 depending on z
    s<?1?1+1<=>z:

    # Otherwise build the full expression as a string and then evaluate it
    eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)
}

```

# Answer
> 2 votes
# 05AB1E, 27 bytes

```
þL"/*+-"¹'!¢©è".»"ì.VD_нi®Θ

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~105 102 98~~ 96 bytes

```
0!3=0
x!y=foldr([(*),(+),(-),(/)]!!y)([1,0,0,1]!!y)[1..x]
f s|[(n,b)]<-lex s=read n!(length b-1)

```

Saved 9 bytes thanks to Zgarb and nimi.

Try it online.

# Answer
> 2 votes
# Java 8, ~~141~~ ~~136~~ 134 bytes

```
s->{float q=s.split("!",-1).length,n=new Float(s.split("!")[0]),i=n,r=n;for(;--i>0;r=q<3?i*r:q<4?i+r:q<5?i-r:i/r);return n<1&q<3?1:r;}

```

-5 bytes (141 → 136) thanks to *@CarlosAlejo*'s C# answer.

**Explanation:**

Try it here.

```
s->{                                // Method with String parameter and float return-type
  float q=s.split("!",-1).length,   //  Amount of exclamation marks + 1
        n=new Float(s.split("!")[0]),
                                    //  The number before the exclamation marks
        i=n,                        //  Index (starting at `n`)
        r=n;                        //  Return sum (starting at `n`)
  for(;--i>0;                       //  Loop from `i-1` down to 1
    r=                              //   Change the result (`r`) to:
      q<3?                          //    If `q` is 2:
       i*r                          //     Multiply
      :q<4?                         //    Else if `q` is 3:
       i+r                          //     Addition
      :q<5?                         //    Else if `q` is 4:
       i-r                          //     Subtraction
      :                             //    Else (if `q` is 5):
       i/r                          //     Division
  );                                //  End of loop
  return n<1&q<3?                   //  Edge case if the input is `0!`:
          1                         //   Then return 1
         :                          //  Else:
          r;                        //   Return the result
}                                   // End of method

```

# Answer
> 2 votes
# Jelly,  ~~24 23 26~~  25 bytes

+ ~~3~~  2 bytes patching up to fix after misinterpretation :(

```
×
+
_
÷
ṣ”!µḢVRṚȯL©Ị$®ŀ@/

```

A full program (a monadic link with helper links referenced by program location)

**Try it online!** or see a test suite.

### How?

```
× - Link 1, multiply: number, number

+ - Link 2, add: number, number

_ - Link 1, subtract: number, number

÷ - Link 1, divide: number, number

ṣ”!µḢVRṚȯL©Ị$®ŀ@/ - Main link: list of characters, a
ṣ”!               - split s at '!' characters
   µ              - monadic separation, call that b
    Ḣ             - head - pop and yield the digit list from b, modifying b
     V            - evaluate as Jelly code (get the number, say N)
      R           - range = [1,2,3,...,N]
       Ṛ          - reverse = [N,...,3,2,1]
            $     - last two links as a monad:
         L        -   length of modified b (number of '!' characters)
          ©       -   (copy to register)
           Ị      -   insignificant? (1 when just one '!', 0 when two or more)
        ȯ         - logical or (1 for "0!", 0 for "0!!...", the reversed-range otherwise)
                / - cumulative reduce by:
               @  -  with swapped arguments:
              ŀ   -    dyadic call of link at index:
             ®    -      recall value from register (number of '!' characters)

```

# Answer
> 2 votes
# Self-modifying x86\_64 machine code, 123 bytes

```
0f b6 0f 31 c0 eb 11 0f be c9 8d 04 80 8d 44 41 d0 0f b6 4f 01 48 ff c7 83 f9 21 75 ea b9 21 21 21 a1 33 0f 0f bc c9 81 c1 ff 07 00 00 c1 e9 03 0f b6 c9 89 ca 09 c2 74 35 55 48 89 e5 c7 45 fc 59 58 5c 5e 8a 4c 0d fc 88 0d 15 00 00 00 f3 0f 2a c8 83 f8 02 5d 7c 1f ff c8 0f 57 c0 f3 0f 2a c0 f3 0f 5e c1 83 f8 01 0f 28 c8 7f eb c3 f3 0f 10 05 03 01 00 00 c3 0f 28 c1 c3

```

Why would interpreted languages be able to dynamically run code with fancy `eval`s, but not plain machine code?

Try it with:

```
#include <stdio.h>
#include <sys/mman.h>
#include <errno.h>

char ff[] = "\x0f\xb6\x0f\x31\xc0\xeb\x11\x0f\xbe\xc9\x8d\x04\x80\x8d\x44\x41\xd0\x0f\xb6\x4f\x01\x48\xff\xc7\x83\xf9\x21\x75\xea\xb9\x21\x21\x21\xa1\x33\x0f\x0f\xbc\xc9\x81\xc1\xff\x07\x00\x00\xc1\xe9\x03\x0f\xb6\xc9\x89\xca\x09\xc2\x74\x35\x55\x48\x89\xe5\xc7\x45\xfc\x59\x58\x5c\x5e\x8a\x4c\x0d\xfc\x88\x0d\x15\x00\x00\x00\xf3\x0f\x2a\xc8\x83\xf8\x02\x5d\x7c\x1f\xff\xc8\x0f\x57\xc0\xf3\x0f\x2a\xc0\xf3\x0f\x5e\xc1\x83\xf8\x01\x0f\x28\xc8\x7f\xeb\xc3\xf3\x0f\x10\x05\x03\x01\x00\x00\xc3\x0f\x28\xc1\xc3";
int main()
{
    char* page = (char*)((unsigned long)((char*)ff) & (~0xfffLL));
    if (mprotect(page, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) {
        perror("mprotect");
        return -1;
    }
    float (*f)(char*) = (float (*)(char*))ff;
    char* testcases[] = { "0!","1!","2!","3!","4!","5!","6!","7!","8!","9!","10!",
                          "0!!","1!!","2!!","3!!","4!!","5!!","6!!","7!!","8!!","9!!","10!!",
                          "0!!!","1!!!","2!!!","3!!!","4!!!","5!!!","6!!!","7!!!","8!!!","9!!!","10!!!",
                          "0!!!!","1!!!!","2!!!!","3!!!!","4!!!!","5!!!!","6!!!!","7!!!!","8!!!!","9!!!!","10!!!!",
                        };
    for (int i = 0; i < 44; i++) {
        printf("%s -> %f\n", testcases[i], f(testcases[i]));
    }
}

```

Assembly:

```
_f:
100000d4f:  0f b6 0f    movzx   ecx, byte ptr [rdi]
100000d52:  31 c0   xor eax, eax
100000d54:  eb 11   jmp 17 <_f+18>
100000d56:  0f be c9    movsx   ecx, cl
100000d59:  8d 04 80    lea eax, [rax + 4*rax]
100000d5c:  8d 44 41 d0     lea eax, [rcx + 2*rax - 48]
100000d60:  0f b6 4f 01     movzx   ecx, byte ptr [rdi + 1]
100000d64:  48 ff c7    inc rdi
100000d67:  83 f9 21    cmp ecx, 33
100000d6a:  75 ea   jne -22 <_f+7>
100000d6c:  b9 21 21 21 a1  mov ecx, 2703302945
100000d71:  33 0f   xor ecx, dword ptr [rdi]
100000d73:  0f bc c9    bsf ecx, ecx
100000d76:  81 c1 ff 07 00 00   add ecx, 2047
100000d7c:  c1 e9 03    shr ecx, 3
100000d7f:  0f b6 c9    movzx   ecx, cl
100000d82:  89 ca   mov edx, ecx
100000d84:  09 c2   or  edx, eax
100000d86:  74 35   je  53 <_f+6E>
100000d88:  55  push    rbp
100000d89:  48 89 e5    mov rbp, rsp
100000d8c:  c7 45 fc 59 58 5c 5e    mov dword ptr [rbp - 4], 1583110233
100000d93:  8a 4c 0d fc     mov cl, byte ptr [rbp + rcx - 4]
100000d97:  88 0d 15 00 00 00   mov byte ptr [rip + 21], cl
100000d9d:  f3 0f 2a c8     cvtsi2ss    xmm1, eax
100000da1:  83 f8 02    cmp eax, 2
100000da4:  5d  pop rbp
100000da5:  7c 1f   jl  31 <_f+77>
100000da7:  ff c8   dec eax
100000da9:  0f 57 c0    xorps   xmm0, xmm0
100000dac:  f3 0f 2a c0     cvtsi2ss    xmm0, eax
100000db0:  f3 0f 5e c1     divss   xmm0, xmm1
100000db4:  83 f8 01    cmp eax, 1
100000db7:  0f 28 c8    movaps  xmm1, xmm0
100000dba:  7f eb   jg  -21 <_f+58>
100000dbc:  c3  ret
100000dbd:  f3 0f 10 05 03 01 00 00     movss   xmm0, dword ptr [rip + 259]
100000dc5:  c3  ret
100000dc6:  0f 28 c1    movaps  xmm0, xmm1
100000dc9:  c3  ret

```

Explanations will be added later. The basic idea is to modify the `divss xmm0, xmm1` instruction at `0x100000db0` and replace it with a `mulss`, `addss`, `subss` or `divss` according to supplied operand. A small trick is also used to parse the input string.

Assembly generated with:

```
float f (char* s)
{
    int x;
    for (x=0; *s != '!'; s++) {
        x=10*x + (*s-'0');
    }
    unsigned char op = (__builtin_ctz(*(unsigned int *)s ^ 0xa1212121)-1) >> 3;
    if (x == 0 && op == 0) {
        return 1;
    }
    unsigned int lookup = 0x5e5c5859;
    unsigned char new_code = ((unsigned char*)&lookup)[op];
    asm("movb %0, 0x15(%%rip)" : : "r" (new_code));
    float sum;
    for (sum = x--; x>0; x--) {
        sum = x / sum;
    }
    return sum;
}

```

# Answer
> 1 votes
# Jelly, 28 bytes

```
×
+
_
÷
³ċ”!
ḟ”!VRṚ¢ŀ@/¢Ị¤¹?

```

Try it online!

Got the idea of separating the links into lines from Jonathan Allan's answer for -2 bytes.

# Answer
> 1 votes
# Gaia, ~~26~~ 25 bytes

```
ẋ)@d┅v;l“×+⁻÷”=“ₔ⊢”+e¤ḥ!∨

```

Try it online!

### Explanation

```
ẋ                          Split the input into runs of the same character.
 )                         Get the last one (the !'s).
  @                        Push an input (since there's none left, use the last one).
   d                       Parse as number (ignores the !'s).
    ┅v                     Get the reverse range: [n .. 1]
      ;                    Copy the ! string
       l“×+⁻÷”=            Get its length and index into this string of operators.
               “ₔ⊢”+       Append 'ₔ⊢' to the operator.
                    e      Eval the resulting string, which is "reduce by <operator> with
                            swapped arguments." Reducing an empty list gives 0.
                     ¤     Bring the !'s back to the top.
                      ḥ!   Remove the first character and check if it's empty.
                        ∨  Logical OR; turns 0 from 0! to 1, doesn't change anything else.

```

# Answer
> 1 votes
# APL (Dyalog), 30 bytes

Inspired by lstefano's solution.

```
{0::0⋄(⍎'×+-⌹'⊃⍨≢⍵~⎕D)/⍳⍎⍵∩⎕D}

```

Try it online!

`{``}` anonymous function where the argument is represented by :

`0::` if any error happens:

`0` return zero

now try:

`⍵∩⎕D` the intersection of the argument and the set of **D**igits (removes exclamation points)

execute that (turns it into a number)

**ɩ**ndices of that

`(``)/` insert (APL is right associative, as needed) the following function between terms:

`⍵~⎕D` argument without **D**igits (leaves exclamation points)

tally that (i.e. how many exclamation points)

`'×+-⌹'⊃⍨` use that to pick from the list of symbols\*

execute (turns the symbol into a function)

---

(matrix division) is used instead of `÷` (normal division) to cause an error on an empty list

# Answer
> 0 votes
# Perl 5, 96 bytes

```
s/(\d+)//;@a=1..$1;$"=qw|* + -( /(|[$l=-1+length];$_=$1?"@a".($l>1?')'x($1-1):''):$l?0:1;$_=eval

```

Try it online!

# Answer
> 0 votes
## Dyalog APL, at least 29 chars

```
{(⍎i⊃'×+-÷')/⍳⍎⍵↓⍨-i←+/'!'=⍵}

```

The expression is ALMOST correct. It passes all the test cases EXCEPT `0!!!!` for which it gives `1` instead of the required `0` and that's because in APL the reduction of an empty vector is supposed to return the neutral element for the function used to reduce. For the quotient that's 1. At the moment I don't have time to try and fix it but I'll leave it here for a rainy day.

# Answer
> 0 votes
# 05AB1E, ~~25~~ 24 bytes

```
þDLðýs¹'!¢<"*+-/"ès<×J.V

```

Try it online!

# Answer
> 0 votes
# Mathematica, 152 bytes

```
(T=ToExpression;If[#=="0!!!!",0,s=T@StringCount[#,"!"];t=T@StringDrop[#,-s];{#!,i~Sum~{i,#},Sum[-i(-1)^i,{i,#}],N@Product[1/i^(-1)^i,{i,#}]}[[s]]&[t]])&

```

# Answer
> 0 votes
# Javascript, ~~111~~ 163 bytes

```
s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))

```

Readable Version

```
s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=
[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-
(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))

```

---
Tags: code-golf, math, number, factorial
---


title: When do the lights blink?

text:
# Question
Title: When do the lights blink?
Imagine you have two lights. These lights blink on and off at a specific rate:

```
Light 0: Delay 0ms and then blink every 1000ms
Light 1: Delay 500ms and then blink every 1000ms

```

Let's simulate these lights for the first 2000ms:

```
0ms:    Light 0 on
500ms:  Light 1 on
1000ms: Light 0 off
1500ms: Light 1 off
2000ms: Light 0 on

```

# The challenge

Given a list of ordered pairs representing the timing for lights, write a program or function to output the sequence for when they blink.

### Input

The input should be in the following format:

```
TimeToSimulate
Light0Delay,Light0Period
Light1Delay,Light1Period
...

```

In this format, the example above would be:

```
2000
0,1000
500,1000

```

### Output

The output should be a series of ordered triples:

```
Time,LightNum,LightStatus

```

LightStatus is a truthy value if the light turns on and a falsy value if the light turns off.

The output from the above example would be:

```
0,0,True
500,1,True
1000,0,False
1500,1,False
2000,0,True

```

If two lights blink at the same time, the light with the lower number should display first in the output.

### Other stuff

* The input and output formats aren't strict
* Code shouldn't produce any errors
* The solution shouldn't rely on race conditions
* No standard loopholes
* This is , so shortest solution wins!

### Test cases

```
Input:

2000
0,1000
500,1000

Output:

0,0,True
500,1,True
1000,0,False
1500,1,False
2000,0,True

----

Input:

2
0,1
0,1

Output:

0,0,True
0,1,True
1,0,False
1,1,False
2,0,True
2,1,True

----

Input:

500
100,50
200,100
300,150

Output:

100,0,True
150,0,False
200,0,True
200,1,True
250,0,False
300,0,True
300,1,False
300,2,True
350,0,False
400,0,True
400,1,True
450,0,False
450,2,False
500,0,True
500,1,False

----

Input:

1000
23,345
65,98
912,12
43,365

Output:

23,0,True
43,3,True
65,1,True
163,1,False
261,1,True
359,1,False
368,0,False
408,3,False
457,1,True
555,1,False
653,1,True
713,0,True
751,1,False
773,3,True
849,1,True
912,2,True
924,2,False
936,2,True
947,1,False
948,2,False
960,2,True
972,2,False
984,2,True
996,2,False

```

# Leaderboard Snippet:

```
var QUESTION_ID=137465,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# JavaScript, ~~98~~ 97 bytes

```
a=>b=>[...Array(a+1)].map((_,i)=>b.map((d,j)=>d[0]--||c.push([i,j,d[d[0]=d[1]-1,2]^=1])),c=[])&&c

```

Try it online

*Saved a byte thanks to Shaggy* \- use currying input syntax.
> 3 votes

# Answer
# Python 2, 93 bytes

```
lambda t,l:sorted(sum([zip(range(x[0],-~t,x[1]),[i]*-~t,[1,0]*t)for i,x in enumerate(l)],[]))

```

Try it online!
> 3 votes

# Answer
# Jelly,  ~~26~~  25 bytes

```
Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ

```

A dyadic link taking a list of `delay, period` number-lists and a time-frame number and returning a list of `time, light, action` integers.

The lights are 1-indexed and `0` represents the 'off' action, while `1` represents the 'on' action.

**Try it online!**

### How?

```
Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ - Link: [[delay, period],...], time-frame
    ð€                    - for €ach [delay, period]:
Ḣ                         -   head (get the delay and modify the item to [period])
 r                        -   inclusive range to time-frame = [delay,delay+1,...,time-frame]
   ⁸                      -   chain's left argument = [period]
  m                       -   modulo slice = [delay, delay+period, delay+2*period, ...]
      µ                   - monadic chain separation, call that v
           J              - range(length(v)) = [1,2,...,nLights]
          "               - zip with:
       ;€€                -   concatenate for €ach for €ach (add light indexes to times)
               $€€        - last two links as a monad for €ach for €ach:
              J           -   range (length(switch-times-for-a-light))
             "            -   zip with:
            ;             -     concatenation (i.e. append a 1-based index)
                  ẎẎ      - tighten & tighten again (flatten by 2 to a list of triples)
                      |€  - sparse application of (for €ach):
                     0    - ...to indexes: 0 (=last entry)
                    Ḃ     - ...action: modulo by 2 (even appended indexes ->0s; odds -> 1s)
                        Ṣ - sort the resulting list of triples

```
> 2 votes

# Answer
# Python 2, ~~206~~ 214 bytes

* Added eight bytes to comply with the rules (taking input via stdin).

```
Q=input();D,T=Q[0],[map(int,q.split(","))for q in Q[1:]];O,l=[],len(T)
for j in range(l):
	t,b=T[j][0],9>8
	while t<=int(D):O+="%0*d,%0*d,%s"%(len(D),t,len(str(l)),j,b),;b=not b;t+=T[j][1]
print"\n".join(sorted(O))

```

Try it online!

This code generates an unordered lists containing each light's switching times, pads those times and the light identifier, sorts said list and outputs it.
> 2 votes

# Answer
# Perl 5, 106 + 1 (-n) = 107 bytes

```
($a[$i],$b[$i++])=eval for<>;for$i(0..$_){for(0..$#a){$a[$_]+=$b[$_],say"$i,$_,".($s[$_]^=1)if$i==$a[$_]}}

```

Try it online!
> 1 votes

# Answer
# Röda, ~~105~~ ~~87~~ 85 bytes

```
{|t|enum|[([_+_]*(t-_1[0]+1))()|enum|(_+_)]|{[[_+_4,_3,_4//_2%2=0]]if[_4%_2=0]}|sort}

```

Try it online!

Explanation:

```
{|t| /* Declare a lambda with one parameter */
/* The input stream contains arrays */
enum| /* For each array in the input, push an ascending number after it */
/* [1] (for stream content in this point, see below) */
[ /* For each array-number pair in the stream: */
    (
        [_+_] /* Create a copy of the array with the number as the last element */
        *(t-_1[0]+1) /* Create copies of the array for every ms simulated */
    )()| /* Push all copies to the stream */
    enum| /* After each copy, push an ascending number to the stream */
    (_+_) /* Append the number to each array before */
]|
/* [2] (for stream content in this point, see below) */
{
    /* Push an on or off event to the stream: */
    [[
        _+_4,      /* delay + time = actual time */
        _3,        /* light-id */
        _4//_2%2=0 /* does the light go on or off? */
    ]]
    if[_4%_2=0] /* if the light goes on or off (time%period=0) */
}|
/* [3] (for stream content in this point, see below) */
sort /* Sort the events */
}

```

The stream contains at point `[1]` values in the following order:

```
[delay, period], light-id
 _1[0]  _1[1]    _2

```

The stream contains at point `[2]` values in the following order:

```
delay, period, light-id, time
_1     _2      _3        _4

```

The stream contains at point `[3]` arrays with the following structure:

```
[time, light-id, on_or_off]

```
> 1 votes

# Answer
# Haskell, 121 bytes

```
import Data.List
t!l=sort$(zip[0..]l)>>=takeWhile(\(a,_,_)->a<=t).(\(i,(d,w))->iterate(\(t,i,s)->(t+w,i,not s))(d,i,2>1))

```

Try it online.

This is the program I started from:

```
import Data.List

type LightId = Int
type Time = Int
type State = Bool
type LightEvent = (Time, LightId, State)

lightSimulation :: Time -> Time -> [(Time, State)]
lightSimulation delay interval = iterate step (delay, True)
  where step (time, state) = (time+interval, not state)

addId :: LightId -> (Time, State) -> LightEvent
addId id (t, s) = (t, id, s)

simulate :: Time -> [(Time, Time)] -> [LightEvent]
simulate timeLimit lights = sort $ concatMap lightSim (zip [0..] lights)
  where withinTimeLimit = ((<=timeLimit) . fst)
        lightSims (id, (delay, interval)) = map (addId id) $ takeWhile withinTimeLimit (lightSimulation delay interval)

```

And before final golfing I has shortened it to:

```
import Data.List

light (id,(delay,interval)) = iterate step (delay, id, True)
  where step (time, id, state) = (time+interval, id, not state)

simulate timeLimit lights = sort $ concatMap lightSims (zip [0..] lights)
  where lightSims l = takeWhile(\(a,b,c)->a<=timeLimit)$light l

```
> 1 votes

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


title: The Double Slit Experiment

text:
# Question
Title: The Double Slit Experiment
A lazy physicist has the job to perform the double slit experiment. However, they are lazy and can't be bothered to set up all the equipment themselves and so are going to simulate the effects. They can't program though so are going to need some help. As they are lazy your program should be as short as possible.

---

Given an odd positive integer `n` (`n >= 1` and `n % 2 == 1`), perform the simulation.

**How it works**

You will start off with an empty canvas and each frame a single particle of light will go through the slits and land on the canvas. The particle will land at a maxima with a chance of:

`n = 1`:

```
+-----+
|     |
| 1/2 |
|     |
+-----+

```

`n = 3`:

```
+-----+ +-----+ +-----+
|     | |     | |     |
| 1/4 | | 1/2 | | 1/4 |
|     | |     | |     |
+-----+ +-----+ +-----+

```

`n = 5`:

```
+-----+ +-----+ +-----+ +-----+ +-----+
|     | |     | |     | |     | |     |
| 1/8 | | 1/4 | | 1/2 | | 1/4 | | 1/8 |
|     | |     | |     | |     | |     |
+-----+ +-----+ +-----+ +-----+ +-----+

```

etc.

For example for `n=5` we check the middle box, there's a 50% chance of falling in it. If it falls end of frame, if not move to the next two, there's a 25% chance of falling in those. If it falls end of frame, if not move to the next two, there's a 12.5% chance of falling in those. If it doesn't fall it doesn't matter, it's still the end of the frame.

**There has been some confusion over how to calculate the chances, most of this is due to people thinking of them as probabilities that should add up to 1. Remove that idea from your mind and it should clear it up a bit for you.**

* At most one particle will lad per frame, this means a particle may not land at all on that frame.
* A particle can be represented by any printable character.
* The particle will land anywhere in the box with a random chance.
* The width of the boxes should be `2n-1` the size of the canvas. So for `n=5` they should be `1/9`th of the canvas's width.
* The height of the boxes should be the height of the canvas.
* The particle should not land outside of the boxes at all.
* If a particle has already landed at a spot that is chosen that doesn't matter it can land there again.
* The above ascii boxes are for clarity, they should not be drawn.
* You may choose your own canvas size as long as it is reasonable. For example, it mustn't just be a few pixels high. It also should be able to fit all of the boxes on it.
* If your code sleeps between frames you do not need to add that into your byte count.

There should be gaps between each of the maxima, a minima. This should be the same width as a box but no particles will land there. See the following diagram:

```
+---+---+---+---+---+
|   |   |   |   |   |
|max|min|max|min|max|
|   |   |   |   |   |
+---+---+---+---+---+

```

The program should run until it is stopped manually.

**Rules**

* A pseudo random number generator (pRNG) is fine.
* Standard loopholes are forbidden.
* Input may be taken by any reasonable format.
* You should output to STDOUT.
* This is so the shortest answer wins.

**Example**

The following GIF is an example run for `n = 5`. I only knocked it up quickly so the chances may be off slightly.

# Answer
# Python 2, ~~207~~ 200 bytes

There is a method to this madness, I promise. Follows the probability interpretation I commented in the OP.

*Edit: -7 bytes through some clever lazy evaluation (and removing some signs)*

```
import time  # not counted for byte total
import random as R,curses as C
r=R.randint
c=C.initscr()
h,w=c.getmaxyx()
n=input()
w/=2*n-1
while 1:
 all(r(0,1)or c.addch(r(0,h-1),(i*(2-4*r(0,1))+n)*w-r(1,w),42)for i in range(n/2+1))
 c.refresh()
 time.sleep(0.1)  # not counted for byte total

```
> 4 votes

# Answer
# BASH, *396 - 11* = 385 bytes

```
E='echo -en';$E "\e[2J\e[99A";while :;do sleep 0.01;for i in `seq $((($1+1)/2)) -1 1`;do p=$(((($1+1)/2 - $i)));[ $p -lt 0 ]&&p=$((-$p));p=$((2**(p+1)));if [ $RANDOM -lt $((32768/$p)) ];then [ $(($RANDOM%2)) -eq 1 ]&&i=$((($1+1)-i));sector=$(((i*2-1)-1));C=`tput cols`;R=`tput lines`;SS=$((C/($1*2-1)));SX=$((SS*sector));X=$((SX+(RANDOM%SS)));Y=$((RANDOM%R));$E "\e[$Y;${X}H*";break;fi;done;done

```

Unfortunately I cannot demonstrate this on TryItOnline because of the endless loop & ANSI escape sequences that move cursor, but you can still copy-paste it into your terminal!

Unminified version:

```
E='echo -en'
$E "\e[2J\e[99A"

while :
do
    sleep 0.01
    for i in `seq $((($1+1)/2)) -1 1`
    do
        p=$(((($1+1)/2 - $i)))
        [ $p -lt 0 ] && p=$((-$p));
        p=$((2**(p+1)))
        if [ $RANDOM -lt $((32768/$p)) ]
        then
            [ $(($RANDOM%2)) -eq 1 ] && i=$((($1+1)-i));
            sector=$(((i*2-1)-1))
            C=`tput cols`
            R=`tput lines`
            SS=$((C/($1*2-1)))
            SX=$((SS*sector))
            X=$((SX+(RANDOM%SS)))
            Y=$((RANDOM%R))
            $E "\e[$Y;${X}H*"
            break
        fi
    done
done

```
> 4 votes

# Answer
# Mathematica, 231 bytes

```
(R=RandomInteger;p=20(#+1)+10;s=Array[0&,{20,6p-3}];i=(#+1)/2;Monitor[While[1<2,y=RandomChoice[Join[q=Riffle[Array[2^#&,i,0],Table[0,i-1]],Reverse@Most@q]->Array[Range[4#+1]&,i,0][[i]]];s[[R@19+1,10y-R@9]]=1;s],Grid[s//. 0->" "]])&

```

**input**

> \[5\]

**output**
> 3 votes

# Answer
# C# (.NET 4.5), ~~319~~ 254 bytes

*Saved 65 bytes thanks to TheLethalCoder!*

```
namespace System{using static Console;n=>{for(var r=new Random();;)for(int w=WindowWidth/(2*n-1),i=(n-1)/2,c=0,m=2,l;i>-1;i--,c+=2)if((l=r.Next(0,(m*=2+1)*2))<2){SetCursorPosition((i+(l<1?c:0))*2*w+r.Next(0,w),r.Next(0,WindowHeight));Write('*');break;}}}

```

Phew, that was a lot of work, but it works somehow.

Since this uses `Console` specific functions and Thread sleeping, it won't work on TIO, sadly.
> 2 votes

# Answer
# Clojure + Quil, 394 bytes

```
(use '[quil.core])(defn -main[n](let[w 999 h 100 c(/ w(-(* n 2)1))s(range 0 w c)a(vec(take-nth 2 s))v(fn[x](<(rand)x))q(fn[a b](+ a(rand-int(- b a))))g(for[i(range(int(/ n 2))-1 -1)][i(- n 1 i)])z(for[[j i](map vector(range 1(inc(count g)))g)][(/ 1(Math/pow 2 j))i])](defsketch m :size[w h]:draw #(loop[[[p i]& r]z](when p(if(v p)(let[o(a(rand-nth i))](point(q o(+ o c))(q 0 h)))(recur r)))))))

```

Well, I certainly didn't win, but this was a good brain workout! I may have picked a overly roundabout way of doing this, but it works! Basically, how it works is:

1. The x-values of each column are calculated based on `n`. Then, the "active colums" that will contain the dots are filtered out. The columns are then zipped with the possibilities that they'll be chosen.
2. The animation starts, and each frame, a loop is entered. Starting from the middle, each pair of columns is tried. Once one pair of columns is chosen, one column from the pair is randomly chosen.
3. A dot is drawn at a random position within the chosen column, the inner loop exits, and a new frame begins.

Uses the Quil graphics library, which is essentially a Processing wrapper for Clojure.

Note, the golfed code doesn't produce the same animation as shown in the GIF. In the golfed code, the background is grey, and the window and dots are smaller. It has the same effect, it's just not as pretty.

See the ungolfed code for an in-depth explanation:

```
(ns bits.golf.interference.interference
  (:require [quil.core :as q]))

; Canvas size
(def width 1800)
(def height 800)

(defn -main [n]
  (let [col-width (/ width (- (* n 2) 1))
        ; The left-most x of each column
        col-starts (range 0 width col-width)

        ; The columns that need to be drawn. Need "vec" so I can index it later.
        active-cols (vec (take-nth 2 col-starts))

        ; Function taking a decimal percentage, and returning whether or not it's satisfied.
        ; (chance? 0.5) would be used to simulate a coin toss.
        chance? (fn [perc] (< (rand) perc))

        ; Function that returns a random int between a and b
        r-int (fn [a b] (+ a (rand-int (- b a))))

        ; Generates index pairs for each complimentary column.
        indices (for [i (range (int (/ n 2)) -1 -1)]
                  [i (- n 1 i)])

        ; Zips each index pair from above with the chance that it will be" chosen"
        zipped-perc (for [[j i] (map vector (range 1 (inc (count indices))) indices)]
                      [(/ 1 (Math/pow 2 j)) i])]

    ; Animation boilerplate
    (q/defsketch Interference
      :size [width height]
      :draw
      ; The animation loop. It contains a loop over each complimentary column. It tries each column pair starting
      ;  from the middle, and works outward. Once it picks a pair of columns, it randomly chooses one of them.
      #(loop [[[p i] & r] zipped-perc]
         (when p
           ; Pick this column?
           (if (chance? p)
             ; Pick one of the column pairs
             (let [col (active-cols (rand-nth i))]
               ; Set the coloring and dot size
               (q/fill 0 0 0)
               (q/stroke-weight 5)
               ; And finally draw the dot
               (q/point (r-int col (+ col col-width))
                        (r-int 0 height)))

             ; If the column wasn't chosen, loop again to try the next one
             (recur r)))))))

```
> 1 votes

# Answer
# C#, 238 bytes

```
namespace System{using static Console;n=>{for(var r=new Random();;)for(int i=0,p=1,w=WindowWidth/(2*n-1),x;i<n+1;i+=2)if(r.Next(p*=2)<1){SetCursorPosition(r.Next(x=(n-1+(r.Next(2)<1?i:-i))*w,x+w),r.Next(WindowHeight));Write("*");break;}}}

```

Try it online! (It won't work but y'know).

Full/Formatted version:

```
namespace System
{
    using static Console;

    class P
    {
        static void Main()
        {
            Action<int> f = n =>
            {
                for (var r = new Random(); ;)
                {
                    for (int i = 0, p = 1, w = WindowWidth / (2 * n - 1), x; i < n + 1; i += 2)
                        if (r.Next(p *= 2) < 1)
                        {
                            SetCursorPosition(r.Next(x = (n - 1 + (r.Next(2) < 1 ? i : -i)) * w, x + w), r.Next(WindowHeight));
                            Write("*");
                            break;
                        }

                    Threading.Thread.Sleep(25);
                }
            };

            f(5);
        }
    }
}

```
> 0 votes

---
Tags: code-golf, ascii-art, random, animation, physics
---


# Question
Title: Find the longest run of consecutive digits
Simple challenge: given a series of positive integer numbers, find the number that contains among its digits the longest run of consecutive digits. The trick? It's allowed for the digits in the runs to wrap around the possible values (`0123456789`) and to run backwards. So both `2345`, `89012` and `5432109` are valid runs of consecutive digits (but not `3456765` nor `321090123` as the run must be always in the same direction, although `3456765` can be considered as two runs: `34567` and `765`). In the case of ties, return the first one.

**Test cases:**

```
Input:  [3274569283, 387652323, 23987654323648, 2345687913624]
Output: 23987654323648
        (The run is 98765432; run length: 8)

Input:  [123012363672023, 098761766325432, 15890123456765]
Output: 15890123456765
        (The run is 8901234567; run length: 10)

Input:  [43, 19, 456]
Output: 456

Input:  [5, 9, 0]
Output: 5

Input:  [71232107, 7012347]
Output: 7012347

Input:  [1234, 32109876]
Output: 32109876

Input:  [9090, 123]
Output: 123

```

**Notes:**

* There will be at least one number in the input.
* Input numbers can contain leading zeroes.
* Input and output can be in any reasonable format. So input numbers can be taken as strings, lists of digits/characters...
* Output can contain trailing and/or leading whitespaces and newlines as long as the number is printed.
* This is , so may the shortest program/function for each language win!

# Answer
# Jelly, 18 bytes

```
I9,-;N¤yŒgỊS€ṀµÐṀḢ

```

Try it online!

Takes and returns as list of digits so as to preserve leading zeroes.
> 4 votes

# Answer
# Jelly,  ~~18 16~~  15 bytes

```
I%⁵Œg%8ċ€1ṀµÐṀḢ

```

A monadic link taking a list of lists of digits, and returning the leftmost one containing a maximal run as described.

**Try it online!** or see a test suite (with processing to make I/O look like it is in the question).

### How?

```
I%⁵Œg%8ċ€1ṀµÐṀḢ - Link: list of lists of integers (digits) from [0-9]
           µÐṀ  - keep elements for which the link to the left is maximal:
I               -   incremental differences (i.e. [a2-a1, a3-a2, ...])
  ⁵             -   literal 10
 %              -   modulo by (i.e. [(a2-a1)%10, (a3-a2)%10, ...])
                -     this equates deltas of -9 and -1 with 1 and 9 respectively
   Œg           -   group runs of equal elements
     %8         -   modulo by 8; vectorised (9s become 1s, others unaffected)
       ċ€1      -   count number of 1s in €ach group
          Ṁ     -   maximum
              Ḣ - head (get the first one of those that were maximal)

```
> 3 votes

# Answer
## JavaScript (ES6), ~~104~~ ~~102~~ 98 bytes

Takes input as a list of lists of digits. Returns the best one.

```
a=>a.map(s=>s.map(n=>(i=(d=(x-(x=n)+11)%10)&&d-2?0:d-p?(p=d,1):i+1)>j&&(r=s,j=i),p=x=-10),j=-1)&&r

```

### Test cases

```
let f =

a=>a.map(s=>s.map(n=>(i=(d=(x-(x=n)+11)%10)&&d-2?0:d-p?(p=d,1):i+1)>j&&(r=s,j=i),p=x=-10),j=-1)&&r

console.log(JSON.stringify(f([[3,2,7,4,5,6,9,2,8,3], [3,8,7,6,5,2,3,2,3], [2,3,9,8,7,6,5,4,3,2,3,6,4,8], [2,3,4,5,6,8,7,9,1,3,6,2,4]])))
console.log(JSON.stringify(f([[1,2,3,0,1,2,3,6,3,6,7,2,0,2,3], [0,9,8,7,6,1,7,6,6,3,2,5,4,3,2], [1,5,8,9,0,1,2,3,4,5,6,7,6,5]])))
console.log(JSON.stringify(f([[4,3], [1,9], [4,5,6]])))
console.log(JSON.stringify(f([[5], [9], [0]])))
```
> 3 votes

# Answer
# Python 2, 118 bytes

Takes a list of lists of digits `a`; returns one of its lists.

```
lambda a:max(a,key=lambda l:len(max(re.findall('1+|9*',`[(x-y)%10for x,y in zip(l,l[1:])]`[1::3]),key=len)))
import re

```

Try it online!
> 2 votes

# Answer
## Husk, 20 bytes

```
←Ö¤>(→Of€1†%8gẊo%10-

```

Takes and returns a list of lists of digits. Try it online!

## Explanation

```
←Ö¤>(→Of€1†%8gẊo%10-  Implicit input.
←                     Return first element of
 Ö                    the input sorted in a stable manner
   >                  in descending order
  ¤ (                 with respect to the following function:
                       Argument is list of digits, say [5,2,1,0,9,1,0].
                   -   Differences
               o%10    mod 10
              Ẋ        of all adjacent pairs: [7,9,9,9,2,1]
             g         Group adjacent equal elements: [[7],[9,9,9],[2],[1]]
          †%8          Vectorized mod 8: [[7],[1,1,1],[2],[1]]
       f€1             Keep those runs where 1 occurs: [[1,1,1],[1]]
      O                Sort in ascending order: [[1],[1,1,1]]
     →                 Take last element (gives [] on empty list): [1,1,1]
                       This is a list of 1s with length one less than
                       the longest run of consecutive digits.

```
> 2 votes

# Answer
# MATLAB, 130 bytes

Take input to array, array of column differences \[X(2)-X(1),...,X(n)-X(n-1)\], check the most frequent value in the array (1 ascending order -1 otherwise), get the index for either the most frequent value or -9 multiplied by the most frequent value (-9 occurs in ascending order, 9 otherwise), find the consecutive indices (i.e. whose difference is equal to 1) and sum it please, because it's late. Output the largest.

```
a=input('')
t=[]
for i=1:numel(a)
b=diff(num2str(a(i))-'0')
c=mode(b)
t=[t sum(diff(find(b==c|b==-9*c))==1)]
end
[t,I]=max(t),a(I)

```

Try it online!
> 1 votes

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


title: A Room Of Mirrors

text:
# Question
Title: A Room Of Mirrors
(This challenge is very similar, but this current challenge has additional complications.)

---

Imagine a 2-dimensional room, where the walls are plated with flat mirrors.

Suddenly, a beam of light strikes into the room, where a piece of wall is missing! The lightbeam dances around the room, getting reflected by the wall mirrors, and eventually leaving the room again.

## The Logic

You are given 5 variables: *W, H, X, Y* and *Z*.
*Now, what do they mean?*

W, H is the size of the room (including the walls), with W being width and H being height.
X, Y is the coordinate that the wall has the hole at. You can assume that this is always located on a wall tile. Coordinates are 0-based, with the X-axis pointing right and the Y-axis pointing down.
Z is a single character, representing the direction that the light falls into the room, either `\` or `/`.

The room has to be built up of the following characters:

* `|` for horizontal walls
* `-` for vertical walls
* `+` for corners

Example: (W=7,H=4)

```
+-----+
|     |
|     |
+-----+

```

---

Now that we have a room, lets destroy one of the wall tiles, so a beam of light falls into the room. Beams of light are diagonal lines, represented by `\` and `/` characters.

Let's replace the wall tile at X=2, Y=0 with a `\` beam of light.

```
+-\---+
|     |
|     |
+-----+

```

The incoming light travels diagonally across the room until it hits a mirror wall. If a wall is hit, the direction inverts along the axis of the wall, and the beam travels on.

```
+-\---+
|\ \/\|
| \/\/|
+-----+

```

In this example, the light beam gets to a point where a corner of the wall is hit, which inflicts that the beam gets reversed completely and travels all the way back, eventually leaving the room.

## Your Task

Write a program that prints the room and the whole path of the light beam, until it leaves the room again or repeats into an infinite loop.

## Input

Input may be received in any reasonable format, but it has to include the 4 integers W, H, X, Y and the character Z, for example `[10, 8, 0, 3, \]`.

You may assume that:

* W, H \>= 3
* X, Y are always located at a wall
* Z will only be able to contain the values `\` and `/`.

## Output

You can decide if you return a string or directly output to `stdout`.
It has to include the room's wall and the light beam (defined by the ASCII characters above).

## Rules

* Standard loopholes are forbidden.
* This is , so the shortest code in bytes, in any language, wins.
* All coding languages that were created prior to the publication of this challenge are allowed.

## Examples

Input: `[5, 4, 2, 0, /]`

```
+-/-+
|/ /|
|\/ |
+---+

```

Input: `[20, 3, 0, 1, \]`

```
+------------------+
\/\/\/\/\/\/\/\/\/\|
+------------------+

```

Input: `[10, 8, 0, 3, \]` <sub>(Example of an infinite loop that won't leave the room again.)</sub>

```
+--------+
|/\/\/\/\|
|\/\/\/\/|
\/\/\/\/\|
|\/\/\/\/|
|/\/\/\/\|
|\/\/\/\/|
+--------+

```

---

Good luck!

# Answer
# Charcoal, 55 bytes

```
ＢＮＮＪＮＮＰψ↷⎇⁼δ/⎇∧⁻⁻θ¹ζＩε⁷Ｉ3⎇∧ＩζＩε⁵Ｉ1Ｗ¬℅ＫＫ«¹Ｆ³¿∧κ℅ＫＫ«↷κ¶↷κ

```

Try it online! Link is to verbose version of code. Edit: I don't know why but that code isn't working right now. Here's a tweaked version instead. Explanation of the original code:

```
ＢＮＮ

```

Draw the outer box.

```
ＪＮＮＰψ

```

Move the cursor to the entry point and make a hole in the box at this point, so this becomes the background.

```
↷⎇⁼δ/⎇∧⁻⁻θ¹ζＩε⁷Ｉ3⎇∧ＩζＩε⁵Ｉ1Ｐ

```

Rotate to the appropriate direction to print the initial line segment.

```
Ｗ¬℅ＫＫ«¹

```

While the cursor is over a hole, draw the next line segment.

```
Ｆ³¿∧κ℅ＫＫ«↷κ¶↷κ

```

Look for a hole in which to draw the next line segment. This works by repeating the same code three times. The first time, nothing happens. The second time, if the cursor is not over a hole, it rotates right 45°, then takes one step to the right, then rotates right 45°. This has the effect of reflecting it in one axis. The third time, if the cursor is still not over a hole, it rotates right 90°, then takes one step to the right, then rotates right 90°. This has the effect of changing the reflection to the other axis. If there still isn't a hole, then a corner or infinite loop has been reached, so the outer loop halts.
> 5 votes

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


title: tail: troll: file truncated

text:
# Question
Title: tail: troll: file truncated
# Background

When you run `tail -f file` in bash, the file is outputted and then any subsequent appends.

However, when you remove something that has already been displayed, `tail` outputs:

```
tail: nameoffile: file truncated

```

# Your Challenge

When given an input `f`, append `tail: [value of f]: file truncated` (with trailing & leading newline) to the file `f`. You can assume that file `f` exists, the device is not full, `f` is not empty, and that you have permissions to write to `f`.

# Test Cases

Input: `something`

File before:

```
Some
thing

```

File after:

```
Some
thing
tail: something: file truncated

```

Input `relative/path/to/file`

File before:

```
tail: relative/path/to/file: file truncated

```

File after:

```
tail: relative/path/to/file: file truncated
tail: relative/path/to/file: file truncated

```

# Reference Implementation (Node.js)

```
x=>require("fs").appendFileSync(x,`
tail: ${x}: file truncated
`)

```

# Answer
# Bash, 4̴0̴ 4̴6̴ 33 bytes

```
echo tail: $1: file truncated>>$1

```

Try it online!

Thanks @DigitalTrauma for `-7` bytes!
> 3 votes

# Answer
# Pyth - 33 bytes

```
.w%"\ntail: %s: file truncated"QQ

```
> 2 votes

# Answer
# Python 3, 61 bytes

```
f=input();open(f,"a").write("\ntail: %s: file truncated\n"%f)

```

~~Can't really try it online...~~ Try it online!
> 1 votes

# Answer
## Batch, 47 bytes

```
@echo(>>%1
@echo tail: %~1: file truncated>>%1

```

Assuming DOS newlines are acceptable on Windows...
> 1 votes

---
Tags: code-golf, string, file-system, bash
---


# Question
Title: Smallest multiple being run of 9 followed by optional run of 0
Given a positive integer, find its smallest positive integer multiple which is a run of 9 followed by an optional run of 0. In other words, find its smallest positive integer multiple which is matched by the regex `/^9+0*$/`.

For example, if the given positive integer is 2, then return 90, since 90 is a positive integer multiple of 2 and is the smallest which is matched by the regex `/^9+0*$/`.

Test cases:

```
n  f(n)
1  9
2  90
3  9
4  900
5  90
6  90
7  999999
8  9000
9  9
10 90
11 99
12 900
13 999999
14 9999990
15 90
16 90000

```

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
# Jelly, ~~13~~ 11 bytes

```
ṚḌ‘DS=ḍ@ð1#

```

Try it online!

### How it works

```
ṚḌ‘DS=ḍ@ð1#  Main link. Argument: n

        ð    Start a dyadic chain with arguments n and n.
         1#  Execute the chain to the left with left argument k = n, n+1, n+2, ...
             and right argument n until 1 match has been found. Return the match.
Ṛ                Get the decimal digits of k, reversed.
 Ḍ               Convert from base 10 to integer.
                 This essentially removes trailing zeroes. As a side effect, it
                 reverses the digits, which doesn't matter to us.
  ‘              Increment the resulting integer. If and only if it consisted
                 entirely of 9's, the result is a power of 10.
   DS            Compute the sum of the digits. The sum is 1 if and only if the
                 integer is a power of 10. Note that the sum cannot be 0.
      ḍ@         Test k for divisibility by n.
     =           Compare the results.

```
> 6 votes

# Answer
# Python 2, ~~55~~ 54 bytes

```
n=r=input()
while int(`10*r`.lstrip('9')):r+=n
print r

```

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), ~~47~~ ~~43~~ 42 bytes

*-4 bytes thanks to @Arnauld*
*-1 byte thanks to @Luke*

```
n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')

```

## Tests

```
let f=
n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n')

for(let i=1;i<=16;i++)console.log(`f(${i}) = `+f(i))
```

### Recursive solution (fails for 7, 13, and 14), 38 bytes

```
n=>g=(i=0)=>/^9+0*$/.test(i+=n)?i:g(i)

```

Called like `f(5)()`. Reaches the max call stack size in Chrome and Firefox for `n=7`, `n=13`, and `n=14`.

```
f=
n=>g=(i=0)=>/^9+0*$/.test(i+=n)?i:g(i)

for(let i=1;i<=16;i++){
 try { console.log(`f(${i}) = `+f(i)()) }
 catch(e) { console.log(`f(${i}) = FAILED`) }
}
```
> 5 votes

# Answer
# Python 2, 51 bytes

```
f=lambda n,r=9:r%n and f(n,10*r-10**n*r%-n/n*9)or r

```

Try it online!
> 5 votes

# Answer
# Ruby, 36 bytes

```
->x{r=0;1until"#{r+=x}"=~/^9+0*$/;r}

```

Brute-forcing - takes forever for x=17.

Try it online!
> 4 votes

# Answer
# Java 8, ~~61~~ 57 bytes

```
n->{int r=0;for(;!(""+r).matches("9+0*");r+=n);return r;}

```

-4 bytes (and faster execution) thanks to *@JollyJoker*.

**Explanation:**

Try it here.

```
n->{                              // Method with integer as parameter and return-type
  int r=0;                        //  Result-integer
  for(;!(""+r).matches("9+0*");   //  Loop as long as `r` doesn't match the regex
    r+=n                          //   And increase `r` by the input every iteration
  );                              //  End of loop
  return r;                       //  Return the result-integer
}                                 // End of method

```
> 4 votes

# Answer
# Python 3, 56 bytes

```
f=lambda n,r=0:{*str(r).strip('0')}!={'9'}and n+f(n,n+r)

```

Try it online!
> 4 votes

# Answer
# Brachylog, 16 bytes

```
;I×≜.ẹḅhᵐc~a₀90∧

```

Try it online!

This is pretty slow

### Explanation

```
;I×≜.              Output = Input × I
    .ẹḅ            Deconcatenate into runs of consecutive equal digits
       hᵐ          Take the head of each run
         c         Concatenate into a number
          ~a₀90∧   That number is a prefix of 90 (i.e. it's 9 or 90)

```
> 3 votes

# Answer
# 05AB1E, 10 bytes

```
0[+D9Û0«_#

```

Try it online!

It just keeps adding the input to 0, until the result minus leading 9's equals 0.
> 3 votes

# Answer
# RProgN 2, 18 bytes

```
x={x*'^9+0*$'E}éx*

```

## Explained

```
x={x*'^9+0*$'E}éx*
x=                  # Set the value of "x" to the input.
  {           }é    # Find the first positive integer in which passing it to the defined function returns truthy.
   x*               # Multiply the index by x, this essentially searches multiples now.
     '^9+0*$'       # A Regex defined by a literal string.
             E      # Does the multiple match the regex?
                x*  # Multiple the outputted index by x, giving the result.

```

Try it online!
> 2 votes

# Answer
# Ruby, 38 + 1 = 39 bytes

Uses `-p` flag.

```
$_=y=eval$_
1until"#{$_+=y}"=~/^9+0*$/

```

`-p` surrounds the program with:

```
while gets
    ...
end
puts $_

```

`gets` stores its result in `$_`. `eval` is used to convert it to a number, as it's shorter than `.to_i`, then brute force is used, incrementing $\_ until it matches the regex. `"#{}"` is sttring interpolation, it's shorter than a `.to_s` call as that would require parantheses around `$_+=y`. Finally, `$_` is printed.

Try it online!

Try all test cases!
> 2 votes

# Answer
# Mathematica, 127 bytes

```
Select[FromDigits/@Select[Tuples[{0,9},c=#],Count[#,9]==1||Union@Differences@Flatten@Position[#,9]=={1}&],IntegerQ[#/c]&][[1]]&

```

**Input**

> \[17\]

**Output**

> 9999999999999999

***here are the first 20 terms***

> {9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999, 9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900}
> 2 votes

# Answer
# Mathics, 71 bytes

```
(x=#;While[!StringMatchQ[ToString@x,RegularExpression@"9+0*"],x+=#];x)&

```

Try it online!

Not very intresting brute force solution, but it beats the other Mathematica answer, which uses some clever tricks.

The one redeeming quality Mathematica has in regards to this challenge is the fact that `StringMatchQ` requires a full match, so I can do `9+0*` rather than `^9+0*$`.
> 2 votes

# Answer
## Batch, 175 bytes

```
@set/pn=
@set s=
:g
@set/ag=-~!(n%%2)*(!(n%%5)*4+1)
@if not %g%==1 set s=0%s%&set/an/=g&goto g
@set r=1
:r
@set s=9%s%
@set/ar=r*10%%n
@if %r% gtr 1 goto r
@echo %s%

```

Takes input on STDIN. Not a brute force solution but in fact based on my answer to Fraction to exact decimal so it will work for 17, 19, etc. which would otherwise exceed its integer limit anyway.
> 2 votes

# Answer
# Haskell, 53 bytes

`f` takes and returns an integer.

```
f n=filter(all(<'1').snd.span(>'8').show)[n,n+n..]!!0

```

Try it online!

This times out for 17, which conveniently is just beyond the test cases. A faster version in 56 bytes:

```
f n=[x|a<-[1..],b<-[0..a-1],x<-[10^a-10^b],mod x n<1]!!0

```

Try it online!

# How it works

* `f` generates all multiples of `n`, converts each to a string, filters out those with the right format, then takes the first one.
* The faster version instead uses that the required numbers are of the form `10^a-10^b`, `a>=1`, `a>b>=0`. For golfing purposes it also uses the fact that for the minimal `a`, only *one* `b` can work, which allows it to generate the `b`s in the slightly shorter "wrong" order.
> 2 votes

# Answer
# Perl 5, 23 + 2 (-pa) = 25 bytes

**Brute Force Method**

```
$_+=$F[0]while!/^9+0*$/

```

Try it online!

It's slow, but it's tiny.

## More Efficient Method:

41 + 2 (-pa) = 43 bytes

```
$_=9;s/0/9/||($_=9 .y/9/0/r)while$_%$F[0]

```

Try it online!

It works well for any input, but it's longer code.
> 2 votes

# Answer
# Dyalog APL, 34 bytes

```
{∧/'0'=('^9+'⎕R'')⊢⍕⍵:⍵⋄∇⍵+r}n←r←⎕

```

Recursive dfns, based on Dennis' Python solution.
> 1 votes

# Answer
**C++, 106 bytes**

```
int main(){long N,T=9,j=10,M;cin>>N;while(T%N){if(T/j){T+=(M/j);j*=10;}else{T=(T+1)*9;j=10;M=T;}}cout<<T;}

```

Detailed Form:

```
int main()
{
    long N,T=9,j=10,M;
    cin >> N;

    while (T%N)
    {
        if (T/j)
        {
            T += (M/j);
            j *= 10;
        }
        else
        {
            T = (T+1)*9;
            j = 10;
            M = T;
        }
    }

    cout << T;
}

```

TRY it online!
> 1 votes

# Answer
# Python 2, 79 bytes

```
x=input();n=10;y=9
while y%x:
 b=n
 while(b-1)*(y%x):b/=10;y=n-b
 n*=10
print y

```

Try it online!

**Some explanations** It finds the smallest natural of form `10**n-10**b` with `n>b>=0` that divides the input.

**Some IO**

```
f(1) = 9
f(2) = 90
f(3) = 9
f(4) = 900
f(5) = 90
f(6) = 90
f(7) = 999999
f(8) = 9000
f(9) = 9
f(10) = 90
f(11) = 99
f(12) = 900
f(13) = 999999
f(14) = 9999990
f(15) = 90
f(16) = 90000
f(17) = 9999999999999999
f(18) = 90
f(19) = 999999999999999999

```
> 1 votes

# Answer
# PHP, 39 bytes

```
for(;ltrim($r=$argn*++$i,9)>0;);echo$r;

```

Try it online!

# PHP, 52 bytes

```
for(;!preg_match("#^9+0*$#",$r=$argn*++$i););echo$r;

```

Try it online!
> 1 votes

# Answer
## Swift 3.0, Bytes:121

```
var i=2,m=1,n=""
while(i>0){n=String(i*m)
if let r=n.range(of:"^9+0*$",options:.regularExpression){print(n)
break};m=m+1}

```

Try it online!
> 1 votes

# Answer
# Java (OpenJDK 8), 66 bytes, doesn't choke on 17

```
n->{long a=10,b=1;for(;(a-b)%n>0;b=(b<10?a*=10:b)/10);return a-b;}

```

Try it online!

Longer than @KevinCruijssen's solution but can handle slightly larger numbers. It calculates the candidate numbers like 10^6 - 10^3 = 999000. 64-bit longs are still the limit, breaking for n=23.

Can probably be golfed a bit but already took too long to make it work...
> 1 votes

# Answer
# Python 3, 62 bytes

This function takes an integer `n` and initializes `m` to zero. Then it removes all zeros from the ends of `m` and checks if the result only contains 9's, returning `m` if it does. If not, it adds `n` to `m` and checks again, etc.

```
def f(n,m=0):
 while{*str(m).strip('0')}!={'9'}:m+=n
 return m

```

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), ~~51~~ 49 bytes

```
let
f=(n,x=1,y=1)=>(x-y)%n?f(n,x,y*10):x-y||f(n,x*10)
```

```
<input type=number value=1 step=1 min=1 oninput=O.value=f(value)>
<input type=number value=9 id=O disabled>
```

Not the shortest approach, but it is wicked fast.
> 1 votes

# Answer
# , ~~19~~ 14 bytes

```
é0òÀ/[1-8]ü09

```

Try it online!

## Explanation

```
é0              ' <m-i>nsert a 0
  ò             ' <m-r>ecursively
   À            ' <m-@>rgument times
               ' <C-A> increment the number (eventually gives all multiples)
     /[1-8]ü09  ' find ([1-8]|09) if this errors, the number is of the form
                ' (9+0*) (because there won't ever be just zeros)
                ' implicitly end the recursion which breaks on the above error

```
> 1 votes

# Answer
# \>\<\>, 35 bytes

```
&a:v ;n-<
:,a/?(1:^!?%&:&-}:{
a*:\~

```

Try it online, or watch it at the fish playground!

Assumes the input is already on the stack. Works by looking for numbers of the form 10a − 10b, with a \< b (yes, that's a less than sign — it takes fewer bytes!) until that's divisible by the input, then printing 10b − 10a. This is much faster than the brute force method (which would be difficult in \>\<\> anyway).
> 1 votes

# Answer
## Mathematica, 82 bytes

Using the pattern of submission from @Jenny\_mathy 's answer...

```
(d=x=1;y=0;f:=(10^x-1)10^y;n:=If[y>0,y--;x++,y=d;d++;x=1];While[Mod[f,#]!=0,n];f)&

```

Input:

```
[17]

```

Output:

```
9999999999999999

```

And relative to the argument in comments at @Jenny\_mathy's answer with @Phoenix ... `RepeatedTiming[]` of application to the input `[17]` gives

```
{0.000518, 9999999999999999}

```

so half a millisecond. Going to a slightly larger input, `[2003]` :

```
{3.78, 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999}

```

a bit under 4 seconds.

Test table: On the first 30 positive integers, the results are

```
{9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999,
9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900,
999999, 990, 9999999999999999999999, 9000, 900, 9999990, 999,
99999900, 9999999999999999999999999999, 90}

```

Explanation: The only magic here is the custom iterator ("iterator" in the CS sense, not the M'ma sense)

```
n := If[ y>0  ,  y-- ; x++  ,  y=d ; d++ ; x=1]

```

which acts on the global variables `x`, the number of leading "9"s, `y`, the number of trailing "0"s, and `d`, the total number of digits. We wish to iterate through the number of digits, and, for each choice of number of digits, start with the most "0"s and the least "9"s. Thus the first thing the code does is initialize `d` to 1, forcing `x` to 1 and `y` to 0. The custom iterator checks that the string of "0"s can be shortened. If so, it shortens the string of "0"s by one and increases the string of "1"s by one. If not, it increments the number of digits, sets the number of "0"s to one less than the number of digits, and sets the number of "9"s to 1. (This is actually done in a slightly different order to shave a few characters, since the old value of `d` is the desired value of `y`.)
> 1 votes

# Answer
# Ti-Basic (TI-84 Plus CE), ~~48~~ 41 bytes

```
Prompt X
For(K,1,0
For(M,-K+1,0
<sub>10</sub>^(K)-<sub>10</sub>^(-M
If 0=remainder(Ans,X
Return
End
End

```

Input is `Prompt`-ed during the program; output is stored in `Ans`.

Explanation:

Tries numbers of the form (10n)(10m-1) = 10k-10m, where m+n=k starts at 1 and increases, and for each value of k, it tries m=1,n=k-1; m=2,n=k-2; ... m=k,n=0; until it finds a multiple of `X`.

This works up to 16; 17 gives a domain error because `remainder(` can only accept dividends up to 9999999999999 (13 nines), and 17 should output 9999999999999999 (16 nines).

```
Prompt X               # 3 bytes, input number
For(K,1,0              # 7 bytes, k in the description above; until a match is found
For(M,-K+1,0           # 10 bytes, start with n=1, m=(k-n)=k-1;
                           # then n=2, m=(k-n)=k-2, up to n=k, m=(k-n)=0
                           # (M=-m because it saved one byte)
<sub>10</sub>^(K)-<sub>10</sub>^(-M           # 8 bytes, n=(k-m) nines followed by m zeroes → Ans
If not(remainder(Ans,X # 8 bytes, If X is a factor of Ans (remainder = 0)
Return                 # 2 bytes, End program, with Ans still there
End                    # 2 bytes,
End                    # 1 byte (no newline)

```
> 1 votes

# Answer
# QBIC, 53 bytes

```
{p=p+1┘o=p*9_F!o$|┘n=!A!~(_l!n$|=_l!n+1$|)-(o%:)|\_Xo

```

## Explanation

```
{        infinitely DO
p=p+1    raise p (starts out as 0)
┘o=p*9   Get the mext multiple of 9 off of p
_F!o$|   Flip a string representation of p*9
┘n=!A!   and set 'n' to be an int version of the flipped p*9
         (this effectively drops trailing 0's)
~        This IF will subtract two values: the first is either 0 for n=x^10, or -1
         and the second bit does (p*9) modulo 'a' (input number): also 0 for the numbers we want
(
 _l!n$|  the length of n's string representation
=        is equal to
_l!n+1$| the length of (n+1)'s string rep (81 + 1 = 82, both are 2 long; 99 + 1 = 100, there's a difference)
)        The above yields -1 (Qbasic's TRUE value) for non-9 runs, 0 for n=x^10
-        Subtract from that
(o%:)    (p*9) modulo a     0 for p*9 = a*y
|       THEN (do nothing, since we want 0+0=0 in the conditionals above, execution of the right path jumps to ELSE
\_Xo    ELSE quit, printing (p*9)

```
> 1 votes

# Answer
# C (gcc), 126 bytes

```
#include<stdio.h>
main(x,n,y,b){n=10;y=9;scanf("%d",&x);while(y%x){b=n;while((b-1)*(y%x)){b/=10;y=n-b;}n*=10;}printf("%d",y);}

```

Try it online!

**Some explanations** It finds the smallest natural of form `10**n-10**b` with `n>b>=0` that divides the input.

**Some IO**

```
f(1) = 9
f(2) = 90
f(3) = 9
f(4) = 900
f(5) = 90
f(6) = 90
f(7) = 999999
f(8) = 9000
f(9) = 9
f(10) = 90
f(11) = 99
f(12) = 900
f(13) = 999999
f(14) = 9999990
f(15) = 90
f(16) = 90000

```
> 1 votes

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


title: A Simple Patttern

text:
# Question
Title: A Simple Patttern
**Inputs:**

Two single digits (let's call them `m` and `n`) and two chars (let's call them `a` and `b`) in your input format of choice.

**Output:**

For the walkthrough, pretend `m=2, n=5, a='a', b='b'`.

Your output will be a string built from your four inputs. Let's call the string `result`, with value `""`. First, concatenate `a` onto `result` `m` times, so concatenate `a` onto `result` `2` times. `result` now equals `aa`. Second, concatenate `b` onto `result` `m` times, so concatenate `b` onto `result` `2` times. `result` now equals `aabb`. Lastly, if result is already longer than `n`, truncate `result` so that it has length `n`. Otherwise, continue alternating with `m` length runs of `a` and `b` until `result` has length `n`. The final `result` is `aabba`, which has length `5`.

**Test Cases:**

```
Input: m = 2, n = 4, a = A, b = B

Output: AABB

Input: m = 3, n = 8, a = A, b = B

Output: AAABBBAA

Input: m = 4, n = 3, a = A, b = B

Output: AAA

Input: m = 2, n = 10, a = A, b = B

Output: AABBAABBAA

```

As all knows, lesser one will rule the world, so the smallest programs, in bytes, win! :)

# Answer
> 8 votes
# Python, 32 bytes

```
lambda m,n,a,b:((a*m+b*m)*n)[:n]

```

Try it online!

# Answer
> 6 votes
# MATL, 5 bytes

```
Y"i:)

```

Inputs are a string with the two characters, then `m`, then `n`.

Try it online!

### Explanation

```
Y"   % Implicit inputs: string and number m. Apply run-length decoding.
     % The second input is reused for each char in the first. Gives a
     % string
i    % Input number n
:    % Push vector [1 2 ... n]
)    % Index the string with the numbers in that vector. Indexing is
     % modular, so the chars are reused if necessary. Implicit display

```

# Answer
> 5 votes
## Haskell, ~~44~~ 40 bytes

```
f=(.cycle).take
(n#m)a=f n.(f m a++).f m

```

Try it online!

# Answer
> 5 votes
# Ruby, 29 characters

```
->m,n,a,b{((a*m+b*m)*n)[0,n]}

```

Sample run:

```
irb(main):001:0> ->m,n,a,b{((a*m+b*m)*n)[0,n]}[3, 8, 'A', 'B']
=> "AAABBBAA"

```

Try it online!

# Answer
> 5 votes
# Japt, 10 bytes

```
VîUçW +UçX

```

First try using a golfing language. Try it online!

## Explanation

```
Vî          // repeat the following until it reaches length V (second input)
  UçW       // third input repeated U (first input) times
      +UçX  // plus the fourth input, repeated U times

```

# Answer
> 3 votes
# , 13 bytes

```
ÀäjÀäêÍî
À|lD

```

Try it online!

`a` and `b` are taken on separate lines in the input, `m` and `n` are taken as argument, reversed (so `n` is the first argument and `m` is the second)

### Explanation

```
Àäj      ' duplicate the inputs [arg 1] times
a -> a
b    b
     a
     b
     ...
   Àäê   ' duplicate everything straight down [arg 2] times - À cycles arguments
a -> aaa
b    bbb
a    aaa
b    bbb
...  ...
      Íî ' remove all newlines
-> aaabbbaaabbb...
À|lD     ' delete from the [arg 1] + 1 column onwards
-> aaabbbaa

```

# Answer
> 3 votes
# Jelly, ~~6~~ 4 bytes

```
xFṁ⁵

```

Try it online!

Thanks to Jonathan Allan for better input format (-2).

# Answer
> 3 votes
# , ~~41~~ 39 bytes

```
function(d,m,n)cat(d[gl(2,m,n)],sep='')

```

An anonymous function; prints the result to stdout. Takes the characters as a vector `d=c(a,b)`. `gl` generates factors (integers) of (in this case) `2` levels of run length `m` with total length `n`! `cat` concatenates and prints them as a string.

Try it online!

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
×J×I£

```

Try it online!

**Explanation**

```
×      # repeat a and b m times each
 J     # join to string
  ×    # repeat the string n times
   I£  # take the first n characters

```

# Answer
> 3 votes
# Haskell, ~~36~~ ~~35~~ 29 bytes

Yet another Haskell solution (expects the characters given as a list):

```
(m#n)c=take n$cycle$c<*[1..m]

```

Try it online!

Thanks @Laikoni for -1 byte.

# Answer
> 2 votes
# Javascript, 55 bytes

```
(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

```

Example code snippet:

```
f=

(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

console.log(f(2, 4, 'A', 'B'))
console.log(f(3, 8, 'A', 'B'))
console.log(f(4, 3, 'A', 'B'))
console.log(f(2, 9, 'A', 'B'))
```

# Answer
> 2 votes
# Javascript, 53 bytes

```
(m,n,a,b)=>a.repeat(n).replace(/./g,(i,j)=>j/m&1?b:i)

```

# Answer
> 2 votes
# Husk, 3 bytes

Direct Port of my Haskell answer, except that the argument order is different:

```
↑¢Ṙ

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~48~~ 43 bytes

```
(m#n)a|r<-(<$[1..m])=take n.cycle.(r a++).r

```

Try it online!

# Answer
> 1 votes
# QBIC, ~~37~~ 27 bytes

```
[:|G=;+G+;][:|G=G+G]?_sG,d

```

## Explanation

```
          This takes its arguments as frequency m, A, B, length n
          For example: 2, A, B, 8
 :        Read a cmd line arg as number 'b' ('a' is used by the FOR declaration as loop counter)
[ |       Start a FOR loop, from 1 to b
G=  G     Set G to hold itself
  ;+      prepended by a cmd line arg read as strig and assigned to A$
     +;   and followed by a cmd line arg read as strig and assigned to B$
]         At the end of the FOR loop, G has had A added to the front twice, and B t the end x2: G$ = AABB
[:|       FOR c = 1 to n
G=G+G]      Add G to itself          G$ = AABBAABBAABBAABBAABBAABBAABBAABB
?_sG,d    PRINT the first n chars of G$   AABBAABB

```

---

Previous attempt:

```
(37b)  {Z=Z+;┘_LZ|~a=:|_X]~a%:|\C=A┘A=;┘B=C
Takes its arguments as `A, length n, frequency m, B`.
Basically adds A to Z until length % freq = 0, then swaps A for B. Loops until lengtn = n

```

# Answer
> 1 votes
# PHP\>=7.1, 77 bytes

```
for([,$x,$l,$f,$s]=$argv;$l-=$z;)echo str_repeat(++$i&1?$f:$s,$z=min($l,$x));

```

PHP Sandbox Online

# Answer
> 1 votes
# Java (OpenJDK 8), 75 bytes

```
void f(int m,int n,char[]s){for(int i=0;i<n;)System.out.print(s[i++/m%2]);}

```

Try it online!

# Answer
> 1 votes
# Cubix, ~~63~~ 58 bytes

```
.rr.@u:s?.\.sw).i|>v:.\nB;?(q:Is...;rr/s.uw/....sIB/\/?(qo

```

Try it online!

watch the interpreter

Takes input like `ab*m*n` where the `*` can be any non-digit character.

Cube version:

```
        . r r .
        @ u : s
        ? . \ .
        s w ) .
i | > v : . \ n B ; ? ( q : I s
. . . ; r r / s . u w / . . . .
s I B / \ / ? ( q o . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```
* `i|is` : read in the chars, and swap them (so `a` is on top)
* `I:q` : read in `m`, dup, and push to bottom (stack is now `m,b,a,m`)
* `)` : decrement
* `?` : turn right if positive, go straight if zero (duplicates `a`)
* positive branch (loop)
    + `s:rur(/w` : swap, dup, move `m-i` to the top of the stack, decrement `m-i`
* zero branch
    + `B` : reverse stack (which now has `m` copies of `a`: `a... b m`)
    + `n` : negate `m` (so we can use `?` to turn left)
    + `)` : increment
    + `?` : go straight if zero, turn left if negative
* negative branch (duplicates `b`)
    + `s:r\/rw)\` basically the same as the positive branch but with increment and left turns.
* zero branch (prints the output)
    + `>v;` : pop the `0` off the stack (looks like `a...b...`)
    + `/B` : reverse the stack
    + `I` : read `n`
    + `s` : swap print loop:
* `oq` : print and push to bottom of stack now looks like: `ab...a...n`
* `(` decrement `n`
* `?` : turn right if positive, go straight if zero
* If right, : `/su` : swap top of stack and continue the loop
* if zero, `/` reflects down and the code evaluated is `Iru@`; `@` terminates the program.

# Answer
> 0 votes
# Charcoal, 10 bytes

```
…⁺×ζＩθ×εＮＮ

```

Try it online! Link is to verbose version of code and includes fourth example. (Annoyingly the deverbosifer won't remove the separator if I add one before the last `InputNumber()`.)

# Answer
> 0 votes
# Mathematica , 61 bytes

```
T=Table;StringTake[""<>Flatten@T[{#3~T~#,#4~T~#},⌈#2/#⌉],#2]&

```

**input**

> \[2,10,"A","B"\]

# Answer
> 0 votes
# Mathematica, 44 bytes

```
StringPadRight[x={##3}~Table~#<>"",#2,x]&

```

# Explanation

is the three byte private use character `U+F3C7`, representing the postfix `\[Transpose]` operator in Mathematica. No TIO link because Mathics does not support , `\[Transpose]` has the wrong operator precedence, the second argument to `Table` is required to be a list, and most importantly, `StringPadRight` is not implemented.

```
                                         & (* Function *)
                 {##3}                     (* which takes the third and fourth arguments *)
                      ~Table~#             (* repeats them a number of times equal to the first argument *)
                                          (* takes the tranpose *)
                               <>""        (* then joins the strings with the empty string *)
               x=                          (* sets x equal to that string *)
StringPadRight[                            (* then pads x *)
                                   ,#2     (* to a length equal to the second argument *)
                                      ,x]  (* with x. *)

```

# Answer
> 0 votes
# APL (Dyalog), 5 bytes

```
⎕⍴⎕/⎕

```

Try it online!

Takes the two chars in a string as the first input, followed by `m` and then `n`.

### Explanation

Let the example input be `'ab'`, `2`, `10`.

```
⎕/⎕                 Replicate the two-char string `m` times
                    2/'ab' => 'aabb'
⎕⍴                  Shape it so that its length is `n`
                    10⍴'aabb' => 'aabbaabbaa'

```

# Answer
> 0 votes
# Pyth, 13 bytes

```
KE<*+*EQ*EQKK

```

Try it online!

**Explanation**

```
                 # Implicitly store m to Q
KE               # Store n to K
     *EQ         # Perform a * m
        *EQ      # Perform b * m
    +            # Concatenate the two strings
   *       K     # Multiply by n
  <         K    # Take the first n characters of the string

```

# Answer
> 0 votes
# k, 10 bytes

```
{y#,/x#'z}

```

Try it online!

# Answer
> 0 votes
# Chip, 588 bytes

```
*Z~vZ.*ZZZs  z. z. z. z. z. z. z. z.
  ,'|`-. ZZ--#<,#<,#<,#<,#<,#<,#<,#<
a/mAM/a| `~S `x'`x'`x'`x'`x'`x'`x'`x.
b/mBM/b|  *.)/')/')/')/')/')/')/')/'|
c/mCM/cZv--x^x-^x-^x-^x-^x-^x-^x-^x-'
d/mDM/d||A~#M',-',-',-',-',-',-',-'
e/mEM/e||B~#M-',-',-',-',-',-',-'
f/mFM/f||C~#M--',-',-',-',-',-'
g/mGM/g||D~#M---',-',-',-',-'
h/mHM/h||E~#M----',-',-',-'
 `v~v' ||F~#M-----',-',-'
* `mz  ||G~#M------',-'
Z  `---x'H~#M-------'
Z,--z--^----'
Z|z. z. z. z. z. z. z. z.
Zx#<,#<,#<,#<,#<,#<,#<,#<
 |`x'`x'`x'`x'`x'`x'`x'`xT
 |A| B| C| D| E| F| G| H|
 )\')\')\')\')\')\')\')\'
 `--^--^--^--^--^--^--'

```

Try it online!

Takes input as a 4-character string. The first two are the characters *a* and *b*, followed by the byte value *m*, and then the byte value *n*. For example, the TIO includes input `ab<tab>2`, this corresponds to 'a', 'b', 9, 50. (Since the codes for `<tab>` and `2` are 9 and 50.

### How?

This answer is a bit of a behemoth, but here's the highlights:

The upper left block, with the lowercase `a`-`h`, is the storage mechanism for the characters *a* and *b*, one line per bit. At its bottom, with the `v~v` and `mz` is the switching mechanism, to swap between the two.

In the middle is a column with a bunch of `~#M`'s. This reads in *m* and stores its negative. The big triangle to the right is just wires to bring this value into the upper accumulator.

The upper right block is the accumulator for *m*. It increments every cycle (starting from *-m*) until it reaches zero. When this happens, the output character is swapped, and counting restarts from *-m*.

Meanwhile, there is the lower block, which is the *n* accumulator. Since *n* is only read once, we don't need a bank of memory (`M` and `m`) to store this value. We simply negate it and start counting. When this value reaches zero, the whole shebang is simply terminated.

All the other guff is delays (`Z` and `z`), wiring (`-`, `|`, ...), and other miscellany.

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