title: Bucket interpreter

text:
# Question
Title: Bucket interpreter
Create a program that interprets the programming language Bucket.

Bucket works on two buckets: the first can hold A and the second can hold B units of liquid. The things you can do with these buckets are:

f: fill bucket A

F: fill bucket B

e: empty bucket A

E: empty bucket B

p: pour units of liquid from A to B until one is empty or the other is full, whichever happens first

P: same as the command p, but from B to A

o: output the value of bucket A

O: output the value of bucket B

These examples assume A is less than or equal to B in the tuple (A,B), which is the main tuple determining which variant of the language is to be interpreted. A is the lesser-or-equal value of a bucket here and B is the larger-or-equal value: substitute as you need.

Your program should ask for 3 inputs:

1. the element A in the tuple (A,B):
2. the element B in (A,B):
3. the program to interpret.

The tuple (A,B) determines which variant of the language Bucket is interpreted.

As a general rule, make sure the first two inputs can range from 0 to 2,147,483,647.

Any characters in the third input other than fFeEpPoO do not need to be handled. Assume no characters other than these will be in the source.

Any commands equal to pouring more liquid in any bucket than it can hold do not need to be handled.

Assume the program will never try to pour liquid from an empty bucket.

This is code golf, so the shortest solution wins.

Any programs made before I changed the specifications to be correct are now non-competing.

# Answer
> 0 votes
# Stax, 50 bytes

```
╖z≈]Y`Zîú¬♣↑e█■X▲håR⌐├~@»3é±óè♂╓_§8F|╢╖r╥ë$%6Æ▲¡↓!

```

Run and debug it

Unpacked and ungolfed it looks like this. You can nearly see some kind of structure in it even if you don't know stax. It loops over the program, and dispatches to a block based on the index of the instruction in the literal `"fFeEpPo"`. Capital O gives an index of -1.

```
sYdZZF
  "fFeEpPo"I
  {xs}
  {dy}
  {Z}
  {d0}
  {+cyG}
  {+cxGs}
  {nP}
  {Q}
  8l@!
}tc~-,

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~212~~ ~~170~~ ~~166~~ ~~164~~ ~~159~~ ~~157~~ ~~155~~ 153 bytes

```
A_~J~B_=Fold[Switch[{a,b}=#;#2,3,Echo@a;#,4,#+Min[a,B-b]z,5|6,{#2A-5A,b},7,Echo@b;#,8,#-Min[b,A-a]z,_,{a,#2B-9B}]&,z={-1,1};0z,ToCharacterCode@#~Mod~12]&

```

Try it online!

Calling `J[A,B]` returns an interpreter for the (A,B)-bucket system, which can be applied to a program with `J[A,B]["prog"]`. The "o" and "O" commands print using `Echo`, and the return value of the program is the final bucket state.

The program is a big `Switch` statement folded over the character codes (modulo 12) of the program, step-wise updating the contents of the buckets. Dispatching the `Switch` takes a shortcut by defaulting to E|F (9|10), as the spec says that there are no characters to be expected other than "fFeEpPoO".

Debugging is done by replacing `Fold` with `FoldList`, so that the return value of the program becomes the sequence of bucket states traversed during program execution. Un-golfed version:

```
J[A_,B_][prog_] :=
  FoldList[                (* debug version                                             *)
    Switch[{a,b}=#;        (* initialize a and b to the current bucket contents         *)
           #2,             (* switch as a function of the next character in the program *)
      "f", {A,b},          (* f: fill first bucket, leave second bucket unchanged       *)
      "F", {a,B},          (* F: fill second bucket, leave first bucket unchanged       *)
      "e", {0,b},          (* e: empty first bucket, leave second bucket unchanged      *)
      "E", {a,0},          (* E: empty second bucket, leave first bucket unchanged      *)
      "p", {a,b}+{-1,1}*Min[a,B-b],  (* p: pour first bucket into second bucket         *)
      "P", {a,b}+{1,-1}*Min[b,A-a],  (* P: pour second bucket into first bucket         *)
      "o", Echo@a;{a,b},   (* o: print contents of first bucket                         *)
      "O", Echo@b;{a,b}]&, (* O: print contents of second bucket                        *)
    {0,0},                 (* start with both buckets empty                             *)
    Characters[prog]]      (* fold over the characters in the program string            *)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 194 bytes

```
$x='if(e>$B-E){e-=$B-E;E=$B}l{E+=e;e=0}';$y=y/eEAB/EeBA/r;($A,$B,$_)=<>;s/[^fepo]//gi;s/e/$&=0;/gi;s/o/say$&|0;/gi;s/F/O=$B;/g;s/f/o=$A;/g;s/p/$x/g;s/P/$y/g;s'e|o'$a'g;s'E|O'$b'g;s/l/else/g;eval

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 129 bytes

Takes input as `([b, a])(code)` where `code` is a string. Returns an array of output values.

```
B=>c=>Buffer(c).map(h=j=>(i=j>>5&1,k=j&3)?k>2?o.push(b[i]):b[i]=~-k*B[i]:b[i]&&b[k=i^1]<B[k]&&h(j,b[i]--,b[k]++),b=[0,0],o=[])&&o

```

Try it online!

### Commented

```
B => c =>                 // B = [b, a]; c = code string
  Buffer(c)               // turn c into a buffer
  .map(h = j =>           // for each ASCII code j:
    ( i = j >> 5 & 1,     //   i = 1 for lower case, 0 for upper case
      k = j & 3           //   k = 0 for 'p', 1 for 'e', 2 for 'f', 3 for 'o'
    ) ?                   //   if k is not 0:
      k > 2 ?             //     if k = 3:
        o.push(b[i])      //       push b[i] in o[]
      :                   //     else:
        b[i] = ~-k * B[i] //       set b[i] to B[i] if k = 2, or 0 if k = 1
    :                     //   else (k = 0):
      b[i] &&             //     if b[i] is not empty
      b[k = i ^ 1] < B[k] //     and the other bucket b[k] is not full:
      && h(               //       do recursive calls
        j,                //       to pour as much as possible,
        b[i]--,           //       decrementing b[i]
        b[k]++            //       and incrementing b[k] at each iteration
      ),                  //
    b = [0, 0],           //   start with b = [0, 0]
    o = []                //   and initialize o[] to an empty array
  ) && o                  // end of map(); return o[]

```

# Answer
> 0 votes
# Charcoal, 66 bytes

```
ＮθＮηＦ⁺eEＳ≡ιf≔θζF≔ηεe≔⁰ζE≔⁰εpＦ∧ζ‹εη«≦⊖ζ≦⊕ε»PＦ∧η‹ζθ«≦⊖ε≦⊕ζ»o⟦Ｉζ⟧O⟦Ｉε

```

Try it online! Link is to verbose version of code. Implements the variant of Bucket specified in the question. For the original version, the s can be changed to s for the same byte count:

```
ＮθＮηＦ⁺eEＳ≡ιf≔θζF≔ηεe≔⁰ζE≔⁰εpＷ∧ζ‹εη«≦⊖ζ≦⊕ε»PＷ∧η‹ζθ«≦⊖ε≦⊕ζ»o⟦Ｉζ⟧O⟦Ｉε

```

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

```
ＮθＮη

```

Input the sizes of the buckets.

```
Ｆ⁺eEＳ

```

Loop over the commands, but prepend `eE` so that the buckets are in a known state.

```
≡ι

```

Switch over the current command.

```
f≔θζ

```

If `f` then fill the first bucket.

```
F≔ηε

```

If `F` then fill the second bucket.

```
e≔⁰ζ

```

If `e` then empty the first bucket.

```
E≔⁰ε

```

If `E` then empty the second bucket.

```
pＷ∧ζ‹εη«≦⊖ζ≦⊕ε»

```

If `p` then pour a unit from the first bucket to the second until the first becomes empty or the second becomes full. (Interestingly this seems to be the golfiest way to express the concept in Charcoal.)

```
PＷ∧η‹ζθ«≦⊖ε≦⊕ζ»

```

If `P` then pour a unit from the second bucket to the first until the second becomes empty or the first becomes full.

```
o⟦Ｉζ⟧

```

If `o` then output the first bucket on its own line.

```
O⟦Ｉε

```

If `O` then output the second bucket on its own line. (The  is implicit, as is the skipping of unrecognised characters in the input.)

# Answer
> 0 votes
# Retina 0.8.2, 184 bytes

```
\d+
$*1,
[^FfEePpOo](?=.*$)

{`(1+),1*¶((.+¶)f|F)
$1,$1¶$3
,1*¶((.+¶)e|E)
,¶$2
(1?)(¶\1(1*)1*,\3)¶p
$2$1¶
^((1*)(1?)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1
3A`

```

Try it online! Implements the variant of Bucket specified in the question. For the original version, the `?`s can be changed to `*`s for the same byte count:

```
\d+
$*1,
[^FfEePpOo](?=.*$)

{`(1+),1*¶((.+¶)f|F)
$1,$1¶$3
,1*¶((.+¶)e|E)
,¶$2
(1*)(¶\1(1*)1*,\3)¶p
$2$1¶
^((1*)(1*)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1
3A`

```

Try it online! Explanation:

```
\d+
$*1,

```

Convert the sizes to unary and add separators to provide space for the current values.

```
[^FfEePpOo](?=.*$)

```

Delete unrecognised commands.

```
{`
}

```

Loop over the commands.

```
(1+),1*¶(F|(.+¶)f)
$1,$1¶$3

```

For `f` or `F`, fill the appropriate bucket by copying its size.

```
,1*¶((.+¶)e|E)
,¶$2

```

For `e` or `E`, empty the appropriate bucket.

```
(1*)(¶\1(1*)1*,\3)¶p
$2$1¶

```

For `p`, pour from the first bucket to the second, taking care not to overflow it. `$1` = amount to pour, `$3` = amount already in second bucket.

```
^((1*)(1*)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶

```

For `P`, pour from the second bucket to the first, taking care not to overflow it. `$2` = amount already in first bucket, `$3` = amount to pour.

```
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1

```

For `o` or `O`, convert the appropriate bucket to decimal and append it to the end.

```
3A`

```

Delete the input at the end of the loop.

# Answer
> 0 votes
# Python 2, ~~194~~ 152 bytes

```
def f(A,B,s,a=0,b=0):
 while s:c='fFeEoOpP'.find(s[0]);W='a,b,A,B=b,a,B,A;'*c;exec W+['a=A','a=0','print a','v=min(a,B-b);a-=v;b+=v'][c/2]+';'+W;s=s[1:]

```

Try it online!

`c` is even when the command deals with the `A` bucket (`feop`) and odd when it deals with the `B` bucket (`FEOP`). So `W` creates a string which, when `exec`'d, swaps the roles of `A` and `B` either an even number of times (i.e., no effect), or an odd number of times (same as a single swap).

This allows the code to only list the commands once instead of twice - if needed, we swap `A` and `B` then execute the `A` based command, and then swap again if needed, to get both `A` and `B` functionalities.

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


title: Print an array as a table

text:
# Question
Title: Print an array as a table
Write a program that prints an associative array (key-value) to a table.

# Requirements

* Standard loopholes are forbidden
* Please include a link to an online interpreter and the byte count in the answer
* Use box drawing characters to draw the table.
* You can write both a full program or a function.
* Key or value can't contain multiline strings.
* Value/key can't be an array/associative array ( example: `["a"=>["a"=>"b"]] or ["a"=>["a","b"]]` )

## Special cases

* If the programming language lacks of associative array , you can use a list of pairs. Example:  `[[key1,value1],[key2,value2]]`
* You can insert horizontal lines between successive pairs.
* An input array can't be empty

### This is a code-golf, the answer with the shortest byte count wins!

# Challenge

Your code must draw a vertical table like in the example from a associative array . The key must be at left and value must be at right and them needs to be separed,you can choose how separe them. Every key-value pair must be in another row. There must be only 2 columns for the keys and value.

# Example

Array(PHP):

`["a"=>"b","c"=>"d","d"=>"d"]`

Output:

```
┏━━━┓
┃a┃b┃
┃c┃d┃
┃d┃d┃
┗━━━┛

```

# Answer
> 8 votes
# TryAPL, 1 byteSBCS

Anonymous tacit prefix function. As TryAPL has no associative arrays, this takes a list of pairs as argument.

Try APL!

mix the list of pairs into a table

# Answer
> 3 votes
# , 1 byte

```
>
```

So… to take strings as input they need to be in boxes already, and to make them pairs I *think* they need to be put into a box again so that they can be treated separately. I'm not too sure about the second part.

Anyway, unboxing the whole thing gives the desired form.

I get a sense that this could be a 0 byte answer if we twist the format enough (or maybe less, since a 2d array of boxes seems to be the proper input format instead of my weird format), but I don't understand boxing all that well.

Try it online!

# Answer
> 1 votes
# PHP, 563 bytes

```
<?php
    $t = ["a"=>"b","c"=>"d"];
    $k = $v = $i = $j = 0;
    foreach ($t as $a => $b){
        $k = (strlen($a) > $k ? strlen($a) : $k);
        $v = (strlen($b) > $v ? strlen($b) : $v);
    }
    echo "┏"; for(; $i++ < $k + $v + 3;) echo "━";
    echo "┓\n";
    foreach ($t as $a => $b){
        echo "|{$a} ";
        for($i = 0; $i < $k - strlen($a); $i++) echo " ";
        echo "| {$b}";
        for($i = 0; $i < $v - strlen($b); $i++) echo " ";
        echo "|\n";
    }
    echo "┗"; for(; $j++ < $k + $v + 3;) echo "━";
    echo "┛";
?>

```

Try it online!

# Answer
> 0 votes
# Charcoal, 62 bytes

```
Ｆ²⊞υ×━⌈ＥθＬ§κι⟦⪫┏┓⪫υ┳⟧Ｅθ⪫┃┃⪫Ｅι◨λＬ§υμ┃⪫┗┛⪫υ┻

```

Try it online! Link is to verbose version of code. Charcoal's code page doesn't include box-drawing characters so they cost 3 bytes but the code uses them instead of their three-byte encoding because it looks nicer. Takes input as an array of tuples as Charcoal doesn't have an iterable dictionary. Explanation:

```
Ｆ²⊞υ×━⌈ＥθＬ§κι

```

Find the length of the longest key and value and repeat  according to that length.

```
⟦⪫┏┓⪫υ┳⟧

```

Embed the s in `┏┳┓`.

```
Ｅθ⪫┃┃⪫Ｅι◨λＬ§υμ┃

```

For each tuple, pad the strings to the length of the s and wrap them with s.

```
⪫┗┛⪫υ┻

```

Embed the s in `┗┻┛`.

# Answer
> 0 votes
# Python 3, ~~189~~ ~~172~~ ~~168~~ ~~173~~ 169 bytes

```
def f(d):t=d.items();a,b=map(lambda*l:max(map(len,l)),*t);c='─'*a,'─'*b;print("┌%s┬%s┐"%c,*[f"│{k:{a}}│{v:{b}}│"for k,v in t],"└%s┴%s┘"%c,sep="\n")

```

Try it online!

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


title: Does this Foo machine halt?

text:
# Question
Title: Does this Foo machine halt?
Determining whether a Turing machine halts is well known to be undecidable, but that's not necessarily true for simpler machines.

A *Foo machine* is a machine with a finite tape, where each cell on the tape has an integer or the halt symbol `h`, e.g.

`2 h 1 -1`

The instruction pointer starts by pointing to the first cell:

```
2 h 1 -1
^

```

At every step, the instruction pointer moves forward by the number it points to, then negates that number. So, after one step, it would move forward `2` cells, and turn the `2` into a `-2`:

```
-2 h 1 -1
     ^

```

The Foo machine keeps doing this until the instruction pointer is pointing to the halt symbol (`h`). So, here is the full execution of this program:

```
2 h 1 -1
^

-2 h 1 -1
     ^

-2 h -1 -1
         ^

-2 h -1 1
      ^

-2 h 1 1
   ^

```

The tape is also circular, so if the instruction pointer moves off of one side of the tape, it goes to the other side, e.g.:

```
3 h 1 3
^
-3 h 1 3
       ^
-3 h 1 -3
     ^
-3 h -1 -3
         ^
-3 h -1 3
 ^
3 h -1 3
  ^

```

One interesting thing about these Foo machines is that some do not halt, e.g.:

```
1 2 h 2
^
-1 2 h 2
   ^
-1 -2 h 2
        ^
-1 -2 h -2
    ^
-1 2 h -2
        ^
-1 2 h 2
   ^

```

This program will continue looping in those last four states forever.

So, write a program which determines if a Foo machine halts or not! You can use any (reasonable) input format you like for the Foo machines, and you can choose to use `0` as the halt symbol. You can use any two distinct outputs for the case where it does halt and the case where it doesn't. Your program must, of course, output an answer in a finite amount of time for all valid inputs.

This is , so try to make your program as short as possible!

## Test cases

```
2 h 1 -1
Halts
3 h 1 3
Halts
h
Halts
1 1 1 1 h
Halts
2 1 3 2 1 2 h
Halts
3 2 1 1 4 h
Halts
1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 h -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36
Halts

2 h
Does not halt
1 2 h 2
Does not halt
8 1 2 3 3 4 8 4 3 2 h
Does not halt
1 2 4 3 h 2 4 5 3
Does not halt
3 1 h 3 1 1
Does not halt
1 2 h 42
Does not halt

```

# Answer
> 11 votes
# C# (Visual C# Interactive Compiler), 71 bytes

```
x=>{for(int i=0,k=0,f=x.Count;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;i/=x[k];}

```

Try it online!

I don't know if the following is valid, since it requires a custom delegate with a signature of `unsafe delegate System.Action<int> D(int* a);` and has to be wrapped in an `unsafe` block to be used, but here it is anyways:

# C# (.NET Core), 64 bytes

```
x=>f=>{for(int i=0,k=0;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;k/=x[k];}

```

Try it online!

This function takes in an int\* and returns a Action; in other words, it is a curried function. The only reason I use pointers is because of codegolf.meta.stackexchange.com/a/13262/84206, which allows me to save bytes by already having a variable already defined with the length of the array.

Saved 9 bytes thanks to @someone

# Answer
> 7 votes
# Jelly, ~~15~~ 11 bytes

```
N1¦ṙ⁸ḢƊÐLḢẸ

```

Try it online!

A monadic link that takes the input as a list of integers using 0 to mean halt. Returns 0 for halting inputs and 1 for those that don’t halt.

Avoids the issue of needing to work out number of iterations because of the use of `ÐL` which will loop until no new result seen.

Thanks to @JonathanAllan for saving a byte!

## Explanation

```
      ƊÐL   | Loop the following as a monad until the result has been seen before:
N1¦         | - Negate the first element
   ṙ⁸       | - Rotate left by each of the elements
     Ḣ      | - Take just the result of rotating by the first element
         Ḣ  | Finally take the first element
          Ẹ | And check if non-zero

```

# Answer
> 7 votes
# Python 3, ~~63~~ 89 bytes

```
def f(x):
 for i in range(2**len(x)):a=x[0];x[0]=-a;b=a%len(x);x=x[b:]+x[:b]
 return a==0

```

Try it online!

Also works for Python 2; a byte can be saved in Python 2 by replacing return with print and having the function print to stdout instead of returning. R turns `True` for halting and `False` for non-halting.

Thanks to @Neil and @Arnauld for noting that I needed to check longer for halting. Thanks to @Jitse for pointing out a problem with `[2,0]`. Thanks to @mypetlion for noting that the absolute of the tape values could exceed the tape length.

# Answer
> 4 votes
# Python 3, 91 bytes

```
def f(a):
	s={0,};i=0
	while{(*a,)}-s:s|={(*a,)};a[i]*=-1;i-=a[i];i%=len(a)
	return a[i]==0

```

Try it online!

-40 bytes thanks to JoKing and Jitse

# Answer
> 4 votes
# Perl 6, ~~46 43~~ 36 bytes

```
{$_.=rotate(.[0]*=-1)xx 2**$_;!.[0]}

```

Try it online!

Represents halt by `0` and returns true if the machine halts. This repeats the logic `2**(length n)` times, where if the pointer ends up on the halt cell, it stays there, otherwise it will be on a non-halt cell. ~~This works because there are only `2**n` possible states (ignoring halt cells) for the Foo machine to be in, since each non-halt cell has only two states.~~ Okay yes, there are states than that, but due to the limited possible transitions between pointers (and therefore states) there will be less than 2\**$\_ states... I think

### Explanation

```
{                                  }  # Anonymous codeblock
                     xx 2**$_         # Repeat 2**len(n) times
            .[0]*=-1                  # Negate the first element
 $_.=rotate(        )                 # Rotate the list by that value
                             ;!.[0]   # Return if the first element is 0

```

# Answer
> 3 votes
# Java 8, ~~78~~ ~~79~~ 73 bytes

```
a->{int k=0,l=a.length,i=0;for(;i++<1<<l;k%=l)k-=(a[k]*=-1)%l-l;k/=a[k];}

```

Straight-forward port of *@EmbodimentOfIgnorance*'s C# .NET answer, so make sure to upvote him!
Thanks to *@Arnauld* for finding two bugs (which also applies to some other answers).

Results in an `java.lang.ArithmeticException: / by zero` error when it's able to halt, or no error if not.

Try it online.

**Explanation:**

```
a->{                   // Method with integer-array as parameter and no return-type
  int k=0,             //  Index integer, starting at 0
      l=a.length,      //  The length `l` of the input-array
  i=0;for(;i++<1<<l;   //  Loop 2^length amount of times:
          k%=l)        //    After every iteration: take mod `l` of `k`
    k-=                //   Decrease `k` by:
       (a[k]*=-1)      //    Negate the value at index `k` first
                 %l    //    Then take modulo `l` of this
                   -l; //    And then subtract `l` from it
                       //  (NOTE: the modulo `l` and minus `l` are used for wrapping
                       //  and/or converting negative indices to positive ones
  k/=a[k];}            //  After the loop: divide `k` by the `k`'th value,
                       //  which will result in an division by 0 error if are halting

```

# Answer
> 3 votes
# 05AB1E, ~~14~~ 13 bytes

```
goFć©(š®._}®_

```

Try it online!

Takes the input as a list of integers with 0 as the halting instruction. Returns 1 for halting and 0 for not halting.

Thanks to @KevinCruijssen for saving 2 bytes!

# Answer
> 2 votes
# JavaScript (Node.js), ~~71~~ 67 bytes

```
x=>{for(p=l=x.length,i=2**l;i--;)p+=l-(x[p%l]*=-1)%l;return!x[p%l]}

```

Basically the same as *@EmbodimentOfIgnorance*'s C# .NET answer

4 byte save thanks to *@Arnaud*

Try it online!

# JavaScript (Node.js), 61 bytes

```
x=>{for(p=l=x.length,i=2**l;i--;p+=l-(x[p%l]*=-1)%l)x[p%l].f}

```

This version uses `undefined` as a halting symbol and throws a `TypeError: Cannot read property 'f' of undefined` when the machine halts and terminates quietly when the machine doesn't halt.

Try it online!

# Answer
> 2 votes
# Charcoal, 28 bytes

```
≔⁰ηＦＸ²Ｌθ«§≔θη±§θη≧⁻§θηη»¬§θη

```

Try it online! Link is to verbose version of code. Outputs using Charcoal's default Boolean output, which is `-` for true and nothing for false. Explanation:

```
≔⁰η

```

Initialise the instruction pointer.

```
ＦＸ²Ｌθ«

```

Loop as many times as there are theoretically possible states.

```
§≔θη±§θη

```

Negate the value at the instruction pointer.

```
≧⁻§θηη

```

Subtract the new value from the instruction pointer. Charcoal's array accesses are cyclic so this automatically emulates Foo's circular tape.

```
»¬§θη

```

At the end of the loop, output whether the program halted.

# Answer
> 2 votes
# Haskell, 79 bytes

```
s x|m<-length x,let g(n:p)=(drop<>take)(mod n m)(-n:p)=iterate g x!!(2^m)!!0==0

```

Try it online!

Returns `True` for halting machines, and `False` otherwise. Input in the form of a list, with `0` representing a halting state.

Assumes a version of GHC greater than 8.4 (released Feb 2018).

# Answer
> 1 votes
# Scala, 156 bytes

Still golfable IMO, but I'm okay with it for now. Returns `0` for non-halting `Foo`s and `1` for halting `Foo`s. Takes the input in `a` as an `Array[Int]`, so `h` is taken as `0`.

```
var u=Seq[Array[Int]]()//Keep track of all states
var i=0//Index
while(u.forall(_.deep!=a.deep)){if(a(i)==0)return 1//Check if we are in a previously encountered step ; Halt
u:+=a.clone//Add current state in the tracker
var k=i//Stock temp index
i=(a(i)+i)%a.length//Move index to next step
if(i<0)i+=a.length//Modulus operator in Scala can return a negative value...
a(k)*=(-1)}//Change sign of last seen index
0//Returns 0 if we met a previous step

```

It is pretty long to run (around 4 seconds for all the test cases) because of the multiple full-array lookups I did, plus the `.deep` that create copies... But you can still try it online.

# Answer
> 1 votes
# Stax, 11 bytes

```
Ç₧┬òE▐tµ|⌡1

```

Run and debug it

It takes input in the form of an integer array, with `0` representing halt.

It outputs `1` for a halting and `0` for a non-halting machine.

# Answer
> 1 votes
# Perl 5 `-ap`, 88 bytes

```
for(;$F[$i]&&!$k{"$i|$F[$i]"};$i=($i+$F[$i])%@F){$k{"$i|$F[$i]"}=1;$F[$i]*=-1}$_=!$F[$i]

```

Try it online!

# Answer
> 1 votes
# Pyth, 12 bytes

```
!hu.<+_hGtGh

```

Test suite!

Uses the straight-forward approach. Recurse until we see the list twice in an identical state. For programs that halt, the list will eventually have a leading `0` because that's where the recursion stops. For programs that don't halt, the list won't begin with the `0`, but rather be in a state from which the process would be periodic and therefore the Foo machine wouldn't halt.

# Answer
> 1 votes
# Attache, 40 bytes

```
Not@&N@Periodic[{On[0,`-,_]&Rotate!_@0}]

```

Try it online!

## Explanation

```
{On[0,`-,_]&Rotate!_@0}

```

This performs a single iteration of the Foo machine; it negates the first member, then rotates the array by the (original, non-negated) first element of the array.

`Periodic` will apply this function until a duplicate result is accumulated. A machine either halts, or goes into a trivial infinite loop. If it halts, the first element will be 0. Otherwise, it will be non-zero.

`&N` is a golfy way of obtaining the first element of a numeric array. Then, `Not` returns `true` for 0 (halting machines) and `false` for anything else (non halting machines).

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


title: Y2K... in 2019?

text:
# Question
Title: Y2K... in 2019?
It's August 10th, 2019, but your task still involves Y2K. Weird, right?

Create a program that prints itself, with a two digit number appended to it. The first time you run it, it should append 00 to its output (its source code, because this is a quine variant). When you run that output, the original program without a two digit number, it should output the original program, but with 01 appended to it. Run that output to get the OG program with 02 appended, then that to get the program with 03... This chain should continue until 99. That program should output `BREAKING NEWS: WORLD ENDS`.

If your program is `Y2Kparanoia: yes` then:

1. It should output `Y2Kparanoia: yes00`
2. That output should print `Y2Kparanoia: yes01`
3. That output should print `Y2K paranoia: yes02`
4. Repeat until step 100: this program outputs the doomsday news specified

This is code golf, so the shortest program that can print itself while following these steps wins.

# Answer
> 1 votes
# Pyth, ~~81~~ 80 bytes

```
.vh,K"?>J198\"BREAKING NEWS: WORLD ENDS\"s[\".vh,K\"N:KN+C92NN\"J\"?<J2*TT+J1"J1

```

Try it online!

Explanation:

```
.vh,K" ... "J1
.v               Eval pyth code
  h              Get the first item in list
   ,             Make a list of the next two items
            J1   Set J = 1 (J = 100 to 199 in future iterations)
    K" ... "     Set K to the given string

```

And the code in the string is (breaking news shortened):

```
?>J198"BNWE"s[".vh,K"N:KN+C92NN"J"?<J2*TT+J1
?                                              Ternary: If A then B else C
 >J198                                         Test if J > 198
      "BNWE"                                   String literal; If ternary was true, return this (which is then implicitly printed)
            s[".vh,K"N:KN+C92NN"J"?<J2*TT+J1   ternary else
            s                                  concatenate list of strings
             [                                 create list
              ".vh,K"                          string literal, list[0]
                     N                         N is set to the double-quote character, list[1]
                      :KN+C92N                 list[2]
                      :                        Regex substitution. In A, replace B with C
                       K                       Variable K (set to the string being eval'd)
                        N                      N is double-quote
                         +C92N                 A backslash followed by a double-quote
                         +                     concat two strings
                          C92                  character with code point 92 (backslash)
                             N                 N is double-quote
                              N                N is double-quote, list[3]
                               "J"             String literal, list[4]
                                  ?<J2*TT+J1   Inner ternary, list[5]
                                   <J2         If J < 2 ..
                                      *TT      return T * T (10 * 10), else
                                          +J1  return J+1

```

# Answer
> 7 votes
# Ruby, ~~158~~ ~~154~~ ~~146~~ ~~128~~ ~~122~~ 100 bytes

Inspired by this answer.

```
eval s=%{$><<(D>198?'BREAKING NEWS: WORLD ENDS':'eval s=%%{%s}<<D=%d'%[s[0..-2],D<2?100:D+1])#}<<D=1

```

EDIT: I was able to remove `(s.split(35.chr)[0]+35.chr).inspect` and replace it with `s[0..-2]` (range of every value except the last) and the `%{ ... }` string syntax I used before. Saved 22 bytes!

### Old version:

EDIT: Saved a pair of parens (and corresponding pair in the data section) by realizing that `"BREAKING NEWS: WORLD ENDS"` is a perfectly valid format string, and ruby ignores any extraneos parameters.

```
END{$><<(q=S>198?"BREAKING NEWS: WORLD ENDS":%{END{$><<(q=S>198?"BREAKING NEWS: WORLD ENDS":%%{%s})%%[q,S<2?0:S-99]}
S=1%02d})%[q,S<2?0:S-99]}
S=1

```

When starting this I realized that since the number *has* to go at the very end of the program, and ruby doesn't allow using variables before they are declared, I would have to make code run *after* the digits somehow. I could've done something like `def a(s) ... end;a 1` which would become `...end;a 100`, however using ruby's lesser-known `END` syntax uses fewer bytes. However, the block inside `END` is in a different scope, so `S` must be a global variable or constant.

Explanation:

* `END{ ... };S=1`: Run block of code just before program terminates; Set constant `S` to `1` (or `100` \- `199` in future iterations)
* `$><<( ... )`: `$>` is a shortcut in ruby for stdout, and `<<` on an IO writes to the IO. The parens are required, otherwise it becomes `($><<S)>198...`
* `S>198?"BREAKING NEWS: WORLD ENDS":(q=...)%[q,S<2?0:S-99]`: If I were to break this out into slightly more reasonable code it would be:

```
if S > 198
  "BREAKING NEWS: WORLD ENDS"
else
  q = ...
  number_to_append = if S < 2
    0
  else
    S - 100 + 1
  end
  q % [q, number_to_append]
end

```

The `%` operator applied to a string is effectively `printf`, with the LHS being the format string and the RHS being the arguments.
* `%{ ... (q=%%{%s}) ... S=1%02d}`: ruby has an interesting syntax for strings that also allows for pairs of curly brackets to appear *within* the string without any escaping as long as they are balanced. This is very helpful, as otherwise a similar quine would have to escape the string to put it into itself as a string literal. The two substitutions in the format string are `%s` for a regular string and `%02d` for a number right-padded to a size of 2 with the character `0`.

My thoughts on shortening further:

* ~~It'd be nice to be able to use `s` instead of `$s`, but defining s `s=$s;` or making a function `def a(s) ...` both use more bytes than they save, and I can't think of any other way to do it.~~ EDIT: Constants are global and can be one character!
* It'd be nice if `S` was always less then `100`, so that it could be compared using 2-digit numbers instead of 3-digit numbers. However, if I use `S=0` at the end, the next two digits are interpreted as octal, and `8` and `9` are invalid and all is bunk. `S=` simply isn't valid, and I don't know any other way to make a value valid both before and after appending two digits. Of note, `0` (and every other integer) is **truthy** in ruby.

Any thoughts on how to make this shorter, please let me know!

Try it online!

# Answer
> 7 votes
# Perl 6, ~~122 114~~ 106 bytes

*-8 bytes thanks to Shelvacu*

```
END {<print $!-199??"END \{<$_>~~.EVAL};\$!="~($!-1&&$!-99)+100!!"BREAKING NEWS: WORLD ENDS">~~.EVAL};$!=1

```

Try it online!

Takes the standard quine format and adds the breaking news string as well as a new function call with the appended number. This uses `END` to execute the function when the program ends.

# Answer
> 5 votes
# Go, ~~382 366 354 340 305 298~~ 272 bytes

Won't win but I had fun with the challenge.

```
package main
func main(){if n<199{s+="\x60,"
print(s[:135],s,100+(n/100)*(n%100+1))}else{print("BREAKING NEWS: WORLD ENDS")}}
var s,n=`package main
func main(){if n<199{s+="\x60,"
print(s[:135],s,100+(n/100)*(n%100+1))}else{print("BREAKING NEWS: WORLD ENDS")}}
var s,n=`,1

```

Try it on the Go Playground!

Based on a quine. If the variable `n` is less than 199, then it adds to the string variable `n` a grave accent (`\x60`), Go's character for multiline strings, followed by a comma `,`. It continues by printing the first 147 characters of `s` (to prevent printing the `,` because that only occurs at the end) then prints `s` as a whole, and finally prints `100` if `n == 1` and `n+1` otherwise. The result is that successive runs change the variable `n` at the end of the program to 100, 101, etc. If the variable `n` is 199 or more, then it prints breaking news.

# Answer
> 3 votes
# Haskell, ~~240~~ ~~232~~ ~~218~~ 216 bytes

```
p=putStr;h 1=100;h k=k+1;g _=p$"n="++show(h n);main|n>198=p"BREAKING NEWS: WORLD ENDS"|1>0=p<>print<>g$"p=putStr;h 1=100;h k=k+1;g _=p$\"n=\"++show(h n);main|n>198=p\"BREAKING NEWS: WORLD ENDS\"|1>0=p<>print<>g$"
n=1

```

Try it online!

Adapted from a quine

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

```
setTimeout(s="alert((n-1?++n:n=100)-200?`setTimeout(s=${JSON.stringify(s)}),n=`+n:'BREAKING NEWS: WORLD ENDS')"),n=1

```

**94 bytes, if stringifying functions is allowed**

```
f=_=>((p=`f=${f}`.split`|`)[4]=p[4]-1?-~p[4]:100)-200?p.join`|`:'BREAKING NEWS: WORLD ENDS'||1

```

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

```
x=>{var a=t>198?"BREAKING NEWS: WORLD ENDS":"x=>{{var a=t>198?{1}BREAKING NEWS: WORLD ENDS{1}:{1}{0}{1};Write(a,a,(char)34,t+(t<2?99:1));}};int t={2}";Write(a,a,(char)34,t+(t<2?99:1));};int t=1

```

Try it online!

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


title: Directory calculation

text:
# Question
Title: Directory calculation
For this challenge, you will be given an absolute path, and a "new" path (which can be absolute or relative), and you need to return the final path.

For example, if your current directory was `/var/tmp/test`:

`my_dir` or `my_dir/` should return `/var/tmp/test/my_dir`

`../../my_dir` should return `/var/my_dir`

`/my_dir/./` should return `/my_dir`

`../../../../../` should return `/`

To be more pedantic:

* A directory is a non-empty string consisting of alphanumeric characters and the symbols `-`,`_`, or `.`
* **A path is a list of 0 or more directories**, separated using `/`. An absolute path starts with a `/`, a relative path does not. Paths can include an ending `/`.

You need to "resolve" the second path, given the first path.

The process of resolving is:

1. Test if the second path is relative. If so, then insert the absolute path's directories to the beginning of the second path.
2. If any of the directories is `..`, then remove it and the preceding directory. If it is the first directory, then simply remove it.
3. If any of the directories is `.`, then remove it.
4. Output the final absolute path. You should not output an ending `/`.

You do not need to handle incorrect input. The commands should work, whether or not the directories passed actually exist on your machine. You can assume that everything is a directory, even if it has an extension.

# Test cases

```
Absolute      New          Output
"/a/b/c"      "d"       -> "/a/b/c/d"
"/a/b/c/"     "d"       -> "/a/b/c/d"
"/a/b/c/"     "d/"      -> "/a/b/c/d"
"/a/b/c"      "/d"      -> "/d"
"/a/b/c"      "/d/"     -> "/d"
"/../a/b/c/"  "d"       -> "/a/b/c/d"
"/a/../b/c/"  "d"       -> "/b/c/d"
"/a/b/../c"   "d"       -> "/a/c/d"
"/a/b/c/.."   "d"       -> "/a/b/d"
"/a/b/c/"     ".."      -> "/a/b"
"/a/b/c"      "../d"    -> "/a/b/d"
"/a/b/c"      "/../d"   -> "/d"
"/a/b/c"      ""        -> "/a/b/c"
"/a/b/c"      "."       -> "/a/b/c"
"/a/b/c"      "./d"     -> "/a/b/c/d"
"/a/b/c"      "/./d"    -> "/d"
"/a/b/c"      "d.txt"   -> "/a/b/c/d.txt"
"/a/b/c"      "d."      -> "/a/b/c/d."
"/a/b/c"      ".txt"    -> "/a/b/c/.txt"
"/a/b/c"      ".txt/d"  -> "/a/b/c/.txt/d"
"/a/b/."      "./././." -> "/a/b"
"/direc"      "tory"    -> "/direc/tory"
"/a-_.b/"     "__._-."  -> "/a-_.b/__._-."
"/a/b"        "../.."   -> "/"
"/a/b"        "../../.."-> "/"
"/a"          "../../.."-> "/"
"/"           ""        -> "/"
"/"           "a"       -> "/a"
"/.."         "a"       -> "/a"
"/."          ""        -> "/"

```

This is a , so make your submissions as short as possible in your favorite language!

# Answer
## Retina, 44 bytes

```
+`.+ /| |/\.?/
/
+1`/?[^/]*/\.\.|/\.?$

^$
/

```

Input is expected to be the two paths separated by a single space.

Try it online! (The first line enables a linefeed-separated test suite.)
> 7 votes

# Answer
## Batch, ~~282~~ ~~281~~ ~~279~~ 276 bytes

```
@echo off
set a=\
set r=%~2
if "%r%"=="" set r=%~1
if not %r:~,1%==/ set r=%~1/%~2
for %%a in (%r:/= %)do call:x %%a
if not %a%==\ set a=%a:~,-1%
echo %a:\=/%
exit/b
:x
if %1==. exit/b
if not %1==.. set a=%a%%1\&exit/b
if not %a%==\ for %%a in (%a:~,-1%)do set a=%%~pa

```

Annoyingly Batch expressions don't generally like empty variables. Edit: Saved 1 byte thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ and 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ (and a bunch of bytes on other answers too, although alas uncredited).
> 3 votes

# Answer
# Python, 53 bytes

```
from os.path import*;p=lambda a,n:normpath(join(a,n))

```
> 3 votes

# Answer
# Python 2, ~~265~~ ~~260~~ 254 bytes

```
y=lambda:[x for x in raw_input().split("/")if x!=""and x!="."]
a=y();n=y();m=len(a)-1
while m>0:
 if a[m]==".."and m>0:del a[m];del a[m-1];m-=1
 elif a[m]=="..":del a[m]
 m-=1
for i in n:
 if i==".."and len(a)>0:del a[-1]
 else:a+=i,
print"/"+"/".join(a)

```
> 2 votes

# Answer
## C#, 43 bytes

```
(x,y)=>Path.GetFullPath(Path.Combine(x,y));

```

Saved 1 byte thanks to @aloisdg

`Path.Combine` puts the arguments together, and `Path.GetFullPath` resolves the `..\`s
> 1 votes

# Answer
# Bash, 41 bytes

This bash script has the side effect of creating directories if they don't exist, but it should meet the requirements. Thanks Karl and Neil for your improvements.

```
mkdir -p $1;cd $1;mkdir -p $2;cd "$2";pwd

```

Usage: *bash getpath.sh "absolute" "new"*

If you don't like the stderr when second argument is an empty string, you can test for it as follows (48 bytes):

```
mkdir -p $1;cd $1;[ $2 ]&&mkdir -p $2&&cd $2;pwd

```

Previous 30 byte attempt (requires directories to exist): ~~*cd $1;\[ $2 \]&&cd $2;echo `pwd`*~~
> 1 votes

# Answer
# Python, 142 137 bytes

```
def p(a,n,r=[],S="/"):
 for s in[s for s in((n[:1]!=S)*a+S+n).split(S)if"."!=s and s]:e=s!="..";r=[s]*e+r[1-e:]
 return S+S.join(r[::-1])

```
> 1 votes

# Answer
# Node REPL, ~~8~~ 12 bytes

```
path.resolve

```

Luckily you don't have to `require()` standard modules in the REPL.

## Test Suite

https://repl.it/Cclo/1

(If the output at the end is `true`, it matched)
> 1 votes

# Answer
# Javascript, 210 bytes

```
function p(a,b){d='.';e=d+d;s='/';t='split';u='splice';r=(b[0]===s?[]:a[t](s)).concat(b[t](s));for(i=0;i<r.length;r[i]===e&&r[u](i?i-1:i,i?2:1)?(i&&i--):i++)(!r[i]||r[i]===d)&&r[u](i,1)&&i--;return s+r.join(s)}

```

Here is test suite

With linebreaks instead of semicolons:

```
function p(a,b) {
    d='.'
    e=d+d
    s='/'
    t='split'
    u='splice'

    r=(b[0]===s?[]:a[t](s)).concat(b[t](s))

    for(i=0;i<r.length;r[i]===e&&r[u](i?i-1:i,i?2:1)?(i&&i--):i++)
        (!r[i]||r[i]===d)&&r[u](i,1)&&i--

    return s+r.join(s)
}

```
> 1 votes

# Answer
# Java 7, 83 bytes

```
String p(String a,String b){return Paths.get(a).resolve(b).normalize().toString();}

```

`normalize` is needed to deal with relative references. `add` is used to handle the second path starting with `/`, which `Paths.get(a, b)` won't handle as specified.
> 0 votes

# Answer
# Bash, 38 bytes

```
[[ $2 = /* ]]||p=$1
realpath -sm $p/$2

```

Doesn't require root privileges and makes no assumptions about existing or non-existing files, directories or symbolic links.

Test it on Ideone.

### How it works

`[[ $2 = /* ]]` tests if the second command-line argument begins with `/`.

If it doesn't, the path is relative and `p=$1` sets variable **p** to the first command-line argument.

This way `$p/$2` is `/$2` if `$2` is an absolute path and `$1/$2` if it is a realtive one.

Finally, `realpath -sm $p/$2` prints the canonical absolute path of `$p/$2`. The `-s` switch makes *realpath* ignore symbolic links, and the `-m` switch missing components.
> 0 votes

# Answer
# GNU sed, ~~81~~ 59 + 1 = 60 bytes

+1 byte for `-r` flag. Expects input on STDIN separates by a single space.

```
s:.+ /::
s:/? :/:
:
s:/$|[^/]+/+\.\.|\.(/|$):\1:
t
s:^/*:/:

```

Try it online!

## Explanation

```
s:.+ /::  # If the second argument starts with a slash, drop the first argument
s:/? :/:  # Join the first and second arguments with a slash, dropping duplicate slashes
:
  s:/$|[^/]+/+\.\.|\.(/|$):\1:  # Drop trailing slashes, resolve double and single dots
  t                             # If the above substitution was made, branch to :
s:^/*:/:  # Ensure output begins with a single slash

```
> 0 votes

# Answer
# Ruby, 16 bytes

Since apparently using a method from the standard library is allowed:

```
File.expand_path

```

See the test suite on repl.it.
> 0 votes

# Answer
# Zsh, 15 bytes

```
a=$1/$2
<<<$a:a

```

The `:a` modifier does exactly this.

Try it online!
> 0 votes

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


# Question
Title: Incrementing Numbers, Over Multiple Sessions
Good Evening Golf Agents,

Your mission is on behalf of notorious entertainment giant Eviltronic Arts. As part of their nefarious plan for world enslavement and entertainment, they must sell as many copies of SimStation V as possible. This means that the software must mysteriously stop working, after starting it a few times.

Your goal is to write a program that counts the amount of times it has been run. The program must do nothing other then write the integer to stdout. The first time it is run, it should return "1". The next "2" and so on. The program must be able to at least reach the number "14", but there is no required upper limit.

However, your program must not write any new files. Accessing itself, or the registry, or even the internet is absolutely OK. But some of our users are suspicious of new files, and will merely overwrite them! The nerve! Defeating the limitations on software they legitimately purchased!

The program can not assume a stable interpreter or shell - the program must still work if the entire interpreter nay shell nay computer is restarted between running.

As it must be as undetectable as possible, the shortest source code will win.

Good luck agents. The entertainment industry is counting on you.

# Answer
> 21 votes
## bash script, 39,37,21 18

```
wc -l<$0;echo>>$0

```

Short and sweet, my first submission in code golf :)

# Answer
> 18 votes
# Python, 40, 39, 38 characters

Also there is no such upper limit on the runtime:

```
open(__file__,'a').write("+1");print 1

```

As you can see, the size of the program gradually increases but there was no such restriction in the original problem. I believe, size of the submitted program is all what matters

# Answer
> 10 votes
## PHP 48 bytes

```
<?=$n=1 ;fputs(fopen(__FILE__,c),'<?=$n='.++$n);

```

A simple self modifying approach. After running 99 times, it will crash spectacularly.

```
$ php increment.php
1
$ php increment.php
2
$ php increment.php
3

```

#

```
$ php increment.php
97
$ php increment.php
98
$ php increment.php
99
$ php increment.php
PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in increment.php on line 1

```

# Answer
> 7 votes
## bash script, 37

```
n=1;echo $n;sed -ie s/$n/$((n+1))/ $0

```

# Answer
> 6 votes
# Ruby: ~~31~~ 21 characters

(This is a rewrite of Abhijit's Python solution. If you like the base idea, upvote his answer, like I did.)

```
open($0,?a)<<"+1";p 1

```

Sample run:

```
bash-4.2$ ruby increment.rb
1

bash-4.2$ ruby increment.rb
2

bash-4.2$ ruby increment.rb
3

```

# Answer
> 5 votes
# \*sh, 14

```
curl copy.sh/x

```

Using a web service, a different approach than the other existing solutions so far. Limit: The memory of my machine.

# JavaScript, 40

```
alert(localStorage.a=~~localStorage.a+1)

```

Hardly counts as a program, but it's quite long anyways. Does not work in Firefox in a local file. Limit: 2^31.

# Answer
> 4 votes
# PHP 31 37 characters

Self modifying. It counts in unary. Be careful that your text editor doesn't try to be helpful and insert a newline character after the 1. It will only work (properly) in PHP \< 5.3.2 because it relies on php to close open file descriptors on shutdown. Or is it acceptable to leak file descriptors?

```
<?fputs(fopen(__FILE__,a),1)?>1

```

Original version (36 chars), all PHP versions:

```
<?file_put_contents(__FILE__,1,8)?>1

```

# Answer
> 2 votes
## Python, 50

```
n=1;
print n
open(__file__,'r+').write("n="+`n+1`)

```

It uses the same approach as primo's answer and similarly crashes on the 100th run.

# Answer
> 2 votes
## J (58)

You need to run this as a script, it will not work from the J command line obviously.

```
echo m=.1
exit(;:^:_1(<":m+1)(<3)};:1!:1[k)1!:2[k=.1{ARGV

```

In J, the tokenizer that the interpreter uses is available as the `;:` function, so if `x` contains J code, `;:x` contains the J tokens, i.e.:

```
    ;: 'echo 1 2 3+4 5 6'
+----+-----+-+-----+
|echo|1 2 3|+|4 5 6|
+----+-----+-+-----+

```

So:

* `echo m=.1`: set `m` to 1, and write it to the screen
* `k=.1{ARGV`: store the 2nd element in `ARGV` (the script name) in `k`.
* ...`1!:2[k`: write the following string to the file in `k`:
* `;:1!:1[k`: read `k`, the current script, and tokenize
* `(<":m+1)(<3)}`: replace the 3rd token by the string representation of `m + 1`
* `;:^:_1`: run the tokenizer in reverse, producing a string
* `exit`: exit the interpreter (it doesn't do that by itself even if you run a script)

# Answer
> 2 votes
# PHP, 34 33 chars

```
<?=$_SESSION[A]+=session_start();

```

Thanks to Tim for the update! My old solution:

```
<?=session_start()+$_SESSION[A]++;

```

The problem is that `$_SESSION[A]` is `""` \- empty string - in first iteration, but as `session_start()` returns 1, you can add it and kill two or three flies in one shot!

Solution with correct syntax (35 chars):

```
<?=session_start()+$_SESSION[A]++?>

```

# Answer
> 2 votes
# Haskell - 36 bytes

```
main=do appendFile"a.hs""+1";print$1

```

Simply adds `+1` to the end of the source file, which is assumed to be named `a.hs`. The `.hs` extension is mandatory in both ghc and ghci.

# Answer
> 1 votes
## Python, ~~49~~ 48 characters

I realized this will only be 48 chars on Windows due to the `\r\n`. Otherwise it should be 49.

```
n=1

print n;print>>open(__file__,'r+'),"n=",n+1

```

A cheap ripoff of the method by @grc

# Answer
> 1 votes
# C, 190 Characters . Works only on Win NT

```
#include <stdio.h>
int main(int c,char *v[]){
char f[100];sprintf(f,"%s:s",v[0]);
if (FILE *fp=fopen(f,"r"))fscanf(fp,"%d",&c);
FILE *fp=fopen(f,"w");printf("%d",c-1);fprintf(fp,"%d",++c);
}

```

# Answer
> 1 votes
# C#, 142 characters

```
int v=(Microsoft.Win32.Registry.CurrentUser.GetValue("c") as int?)??0+1;Console.Write(v);Microsoft.Win32.Registry.CurrentUser.SetValue("c",v);

```

# Answer
> 1 votes
# Tcl, 63 or 73 bytes

* With some web service it's 73:

```
package require http
puts [set [http::geturl http://example.com/c](data)]

```
* modifying itself is 63:

```
proc a a {puts [string le $a]};puts -nonewline [open $argv0 a] a; a a

```

# Answer
> 1 votes
## TI-Basic, 9 chars

```
:X+1->X:X

```

# Answer
> 1 votes
# C# - 201 239 234 chars

Works for the first 255 times, then wraps over to 0. It won't output anything on the first execution.

```
namespace System.IO{class s{static void Main (string[]a){char f='|';if(f!='|'){Console.Write (255);}string p=Reflection.Assembly.GetCallingAssembly().Location;byte[]d=File.ReadAllBytes(p);d[769]++;d[780]++;File.WriteAllBytes(p,d);}}}

```

Save as Main.cs, compile with

```
gmcs Main.cs

```

Tested with gmcs 2.10.8.1 and Mono runtime 2.10.8.1-5ubuntu2

# Answer
> 1 votes
## Batch - 41

Given the example use case I probably wouldn't assume that this technique is a viable one - It renames the .bat file containing the script -

```
@set/aa=%~n0+1
@echo %a%&@ren %0 %a%.bat

```

Save this to a file called `0.bat` \- and call using `0.bat 2>nul`. `2>nul` redirects stderr to nul which is necessary because this script will rename the file containing the script, once it does that cmd can obviously no longer see the script (before it hits EOF) and will return the error `The batch file cannot be found.`

Each consecutive call of the script will of course have to be `1.bat 2>nul ... 2.bat 2>nul ... 3.bat 2>nul ... etc ...`

# Answer
> 1 votes
# mIRC script, 28/22 bytes

If put in "aliases" tab, "alias " can be omitted making 22 bytes.

```
alias x inc %i | echo -ag %i

```

# Answer
> 1 votes
# Powershell, 47 Bytes

assumes script is named `a.ps1`

```
0
[int]$n,$t=(gc a.ps1)[0..1];,(++$n),$t>a.ps1

```

The script will overwrite itself replacing the `0` on the first line with `1`,`2`,`3` and so on.

could also save another 8 bytes by replaceing both instances of `a.ps1` with `1` and saving the script as a file named `1` although this is a bit far out for me.

Replace second line with this if the file is not saved as 'a.ps1'.

```
[int]$n,$t=(gc($s=$MyInvocation.MyCommand.Name))[0..1];,(++$n),$t>$s

```

---

`0` on first line to initialize the count

Linebreak provides the easiest way to split the file in two

```
[int]$n,$t=(gc a.ps1)[0..1]

```

this takes the file 'a.ps1' and reads it in as an array of lines, we then iterate through it with `[0..1]` and set that to the variables `$n` which is cast as `[int]` and `$t` respectively, so that the `0` on the first line becomes `$n` and the 'code' on the second line becomes `$t`

```
,(++$n),$t>a.ps1

```

This used the `,1,2` array notation, to create an array of two elements, one being the number stored in `$n` pre-incremented and outputted to stdout by the use of implicit brackets, the second being the second line of text from the file, and then also output it to the file named 'a.ps1'

as both input and output are arrays of strings there is minimal formatting required, and almost everything is assumed by the interpreter.

# Answer
> 1 votes
# Zsh (no coreutils), 32 bytes

```
a=`<$0`
<<<$[$#a/2-15]
>>$0<<<:

```

(Note the trailing newline) Uses the length of the script. On each invocation, the last line shown above will append `:` (identical to `true`) and a newline to the script, hence the `/2`.

Try it online!

# Answer
> 0 votes
## GNU sed, 13 + 1(n flag) = 14 bytes

```
$=;$eecho>>s

```

**Run:** sed -nf s s

The assumption is that the source filename is called `s`. A trailing newline is needed after the code, which was counted in the bytes total. Explanation:

```
$=           # print the number of lines of the input file
$eecho>>s    # a shell echo call that appends an empty line to the source file 's'

```

# Answer
> 0 votes
## Rust / cargo-script, 283 bytes

Oneliner:

```
use std::fs::File;use std::io::Write;fn main(){let c=     0; let mut v = vec![];::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);let mut q=&mut File::create("w").unwrap();q.write(&v[..53]);q.write(format!("{:6}",c+1).as_bytes());q.write(&v[59..]);println!("{}",c);}

```

Save as `w` and run with `cargo-script`:

```
$ cargo-script script w
   Compiling w v0.1.0 (file:///home/vi/.cargo/script-cache/file-w-b4d6541706fabb11)
    (warnings skipped...)
    Finished release [optimized] target(s) in 1.47 secs
0
$ cargo-script script w
    (compilation output skipped)
1
$ cargo-script script w
...
2
$ cargo-script script w 2> /dev/null
3
$ cargo-script script w 2> /dev/null
4
$ cargo-script script w 2> /dev/null
5
$ cargo-script script w 2> /dev/null
6
$ cargo-script script w 2> /dev/null
7
$ cargo-script script w 2> /dev/null
8
$ cargo-script script w 2> /dev/null
9
$ cargo-script script w 2> /dev/null
10
$ cargo-script script w 2> /dev/null
11

```

Don't iterate too fast or it'll get stuck.

Partially ungolfed:

```
use std::fs::File;use std::io::Write;fn main(){let c=     0;
    let mut v = vec![];
    ::std::io::Read::read_to_end(&mut File::open("w").unwrap(),&mut v);
    let mut q = &mut File::create("w").unwrap();
    q.write(&v[..53]);
    q.write(format!("{:6}",c+1).as_bytes());
    q.write(&v[59..]);
    println!("{}", c);
}

```

Will break after 99999;

---
Tags: code-golf
---


title: Create the least compressible picture

text:
# Question
Title: Create the least compressible picture
"A picture is worth a thousand words"—so the old saying goes. The average word is about four characters long, so a picture conveys 4kB of information. But how much *entropy*, rather than information, can a picture convey?

Your task is to generate an image, exactly 4,000 bytes in size, with the highest entropy possible. You may use any language, libraries, or image format you choose, and you may output to the console or to a file so long as you upload your image here.

# Scoring

Your score is the compression ratio (4000 ÷ compressed size) when your image is compressed with GNU `tar` version 1.28 and `gzip` version 1.6, using the DEFLATE algorithm and default settings — specifically, the command `tar -czvf out.tar.gz image`. The smallest compression ratio wins.

# Answer
# 0.9514747859 (4204-byte output)

Note: the image above is not the actual *file* I used, but it is the image.

Here is a hexdump of the file: https://gist.github.com/pommicket/cf2982e8ecf09a4de89d3a849526c64b

The file is in the netpbm format, and can be generated with this C code:

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

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Please pass in seed.\n");
        return EXIT_FAILURE;
    }
    srand(atoi(argv[1]));
    FILE *fp = fopen("image.pgm", "w");
    int width = 2, height = 1993;
    fprintf(fp, "P5 %d %d 255 ", width, height);
    for (int i = 0; i < width * height; i++) {
        fputc(rand() & 0xFF, fp);
    }
    fclose(fp);
    return 0;
}

```

The random seed must be passed into the program. After trying some seeds, I got one which produced a 4204 byte gzipped file. As Nnnes pointed out, `tar` will include metadata in the file, so your results might differ from mine.

netpbm isn't supported everywhere, but it works with imagemagick's `convert` (so just do `convert image.pgm image.png` to turn it into a png).

### Why this image/format?

A file which consists of entirely random bytes is very hard to compress (in fact, any possible compression algorithm will do on average, no better than not compressing for random files). The content of the actual file is just `P5 2 1993` followed by 3986 random bytes, which is why gzip has such a hard time compressing it.
> 4 votes

---
Tags: code-challenge, graphical-output, compression
---


title: One goes up, the other comes down

text:
# Question
Title: One goes up, the other comes down
# Introduction

In this challenge, your task is to decide whether a given sequence of numbers can be separated into two subsequences, one of which is increasing, and the other decreasing. As an example, consider the sequence `8 3 5 5 4 12 3`. It can be broken into two subsequences as follows:

```
  3 5 5   12
8       4    3

```

The subsequence on the first row is increasing, and the one on the second row is decreasing. Furthermore, you should perform this task efficiently.

# Input

Your input is a non-empty list `L` of integers in the range 0 – 99999 inclusive. It is given in the native format of your language, or simply delimited by spaces.

# Output

Your output is a truthy value if `L` can be broken into an increasing and a decreasing subsequence, and a falsy value otherwise. The subsequences need not be strictly increasing or decreasing, and either of them may be empty.

# Rules and bonuses

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. Furthermore, brute forcing is forbidden in this challenge: **your program must run in polynomial time in the length of the input**.

You are not required to actually return the two subsequences, but there is a **bonus of -20%** for doing so. To make the bonus easier to claim in statically typed languages, it is acceptable to return a pair of empty lists for the falsy instances.

# Test cases

Given in the format `input -> None` for falsy inputs and `input -> inc dec` for truthy inputs. Only one possible pair of subsequences is given here; there may be more.

```
[4,9,2,8,3,7,4,6,5] -> None
[0,99999,23423,5252,27658,8671,43245,53900,22339] -> None
[10,20,30,20,32,40,31,40,50] -> None
[49,844,177,974,654,203,65,493,844,767,304,353,415,425,857,207,871,823,768,110,400,710,35,37,88,587,254,680,454,240,316,47,964,953,345,644,582,704,373,36,114,224,45,354,172,671,977,85,127,341,268,506,455,6,677,438,690,309,270,567,11,16,725,38,700,611,194,246,34,677,50,660,135,233,462,777,48,709,799,929,600,297,98,39,750,606,859,46,839,51,601,499,176,610,388,358,790,948,583,39] -> None
[0,1,2,3,4] -> [0,1,2,3,4] []
[4,3,2,1,0] -> [] [4,3,2,1,0]
[1,9,2,8,3,7,4,6,5] -> [1,2,3,4,6] [9,8,7,5]
[71414,19876,23423,54252,27658,48671,43245,53900,22339] -> [19876,23423,27658,48671,53900] [71414,54252,43245,22339]
[10,20,30,20,30,40,30,40,50] -> [10,20,20,30,40,40,50] [30,30]
[0,3,7,13,65,87,112,43,22,1] -> [0,3,7,13,65,87,112] [43,22,1]
[7,4,4,7,4,7,7,4,7,4,4,4,7,7] -> [7,7,7,7,7,7,7] [4,4,4,4,4,4,4]
[7,997,991,957,956,952,7,8,21,924,21,923,22,38,42,44,920,49,58,67,71,83,84,85,917,89,907,896,878,878,90,861,115,860,125,128,140,148,858,155,160,836,164,182,826,191,824,805,195,792,205,782,206,210,769,213,756,748,214,745,724,701,234,241,693,268,685,293,679,297,334,671,336,669,341,652,356,648,362,364,370,375,386,630,622,388,389,618,398,408,468,615,470,533,611,539,544,609,586,582,572,565,547,602,536,619,624,528,512,631,640,649,669,671,677,505,678,723,743,489,489,473,454,757,446,445,758,759,764,445,431,770,429,426,418,409,790,383,379,366,363,791,358,795,809,827,835,356,353,841,844,333,867,323,317,879,311,881,309,896,282,281,897,263,904,237,236,226,202,195,914,186,177,917,920,157,926,936,154,138,943,131,945,100,98,947,957,964,95,973,989,57,43,32,21,16,13,11,8,0] -> [7,7,8,21,21,22,38,42,44,49,58,67,71,83,84,85,89,90,115,125,128,140,148,155,160,164,182,191,195,205,206,210,213,214,234,241,268,293,297,334,336,341,356,362,364,370,375,386,388,389,398,408,468,470,533,539,544,586,602,619,624,631,640,649,669,671,677,678,723,743,757,758,759,764,770,790,791,795,809,827,835,841,844,867,879,881,896,897,904,914,917,920,926,936,943,945,947,957,964,973,989] [997,991,957,956,952,924,923,920,917,907,896,878,878,861,860,858,836,826,824,805,792,782,769,756,748,745,724,701,693,685,679,671,669,652,648,630,622,618,615,611,609,582,572,565,547,536,528,512,505,489,489,473,454,446,445,445,431,429,426,418,409,383,379,366,363,358,356,353,333,323,317,311,309,282,281,263,237,236,226,202,195,186,177,157,154,138,131,100,98,95,57,43,32,21,16,13,11,8,0]

```

# Answer
# Pyth, 34 bytes

```
.N|!N|&ghNT:tNhNY&gYhN:tNThN:QZ^T5

```

Test Suite

Uses memoized recursion to keep the runtime down. Defines a 3 input function `:`, which takes inputs \`list suffix, end of increasing sequence, end of decreasing sequence.
> 3 votes

# Answer
# Brachylog, 16 bytes - 20% = 12.8 (but it's almost certainly not polynomial)

```
⊇≥₁X&⊇≤₁Y;X.cp?∧

```

Try it online!

Fails if there's no pair of compliant subsequences and outputs them through its output variable if there is one (but will just print `true.` if it's run as a program). I say it's *almost* certainly not polynomial because the beauty of Brachylog is that since it's a declarative language, you don't do so much in the way of implementing an algorithm as you do just describing relationships between variables and asking the computer to crank out results. So chances are this is hardcore brute force, but I spent long enough copy pasting the test cases (two of which it just times out on) that I feel like I should submit this anyhow, if for no other reason than to drag this challenge up from the back of the "Newest" list.

```
   X                X is a
 ≥₁                 non-increasing
⊇                   sublist of the input
    &               and
        Y           Y is a
      ≤₁            non-decreasing
     ⊇              sublist of the input
         ;X         which paired with X
           .        is the output variable
            c       which when its elements are concatenated
             p      is a permutation of
              ?     the input
               ∧    which is not unified with the output.

```
> 2 votes

# Answer
# Haskell, 65 bytes

```
(>[]).foldl(%)[(0,9^6)]
p%x=do(u,d)<-p;[(x,d)|x>=u]++[(u,x)|x<=d]

```

Try it online!

Iterates through the list, tracking the possible pairs `(u,d)` of the max of the increasing sequence and the min of the decreasing one. Each new element `x` replaces either `u` or `d`, which corresponds to it being append to that subsequence. It could be that both or neither options are valid. In the end, we check that the list of possibilities is nonempty.

The initial bounds `(0,9^6)` use that the problem specifies the numbers to be in the range 0 – 99999. A more general solution could do `(1/0,-1/0)` to makes `(-inf,inf)`.
> 2 votes

---
Tags: code-golf, array, subsequence, decision-problem, restricted-complexity
---


title: Telephone number in spoken words

text:
# Question
Title: Telephone number in spoken words
# Goal

Write a program or function that translates a numerical telephone number into text that makes it easy to say. When digits are repeated, they should be read as "double n" or "triple n".

# Requirements

## Input

A string of digits.

* Assume all characters are digits from 0 to 9.
* Assume the string contains at least one character.

## Output

Words, separated by spaces, of how these digits can be read out loud.

* Translate digits to words:

0 "oh"
1 "one"
2 "two"
3 "three"
4 "four"
5 "five"
6 "six"
7 "seven"
8 "eight"
9 "nine"
* When the same digit is repeated twice in a row, write "double *number*".
* When the same digit is repeated thrice in a row, write "triple *number*".
* When the same digit is repeated four or more times, write "double *number*" for the first two digits and evaluate the rest of the string.
* There is exactly one space character between each word. A single leading or trailing space is acceptable.
* Output is not case sensitive.

# Scoring

Source code with the least bytes.

# Test Cases

```
input        output
-------------------
0123         oh one two three
4554554      four double five four double five four
000          triple oh
00000        double oh triple oh
66667888     double six double six seven triple eight
19999999179  one double nine double nine triple nine one seven nine

```

# Answer
> 10 votes
# 05AB1E, ~~53~~ ~~52~~ ~~51~~ ~~50~~ 49 bytes

```
γε€T2äθ¬MÊi¨₃1ǝR]˜“Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‹¶½¿“#sè¸»

```

Try it online!

Explanation:

```
γ                      # split input in groups of consecutive equal digits
 ε              ]      # for each group
  €T                   #  add a 10 before each digit (66 -> [10, 6, 10, 6])
    2äθ                #  keep only the second half of that list
       ¬MÊi     ]      #  if the first element is not the maximum
           ¨           #   drop the last element
            ₃1ǝ        #   replace the second element with 95
               R       #   reverse the list
˜                      # flatten
 “...“                 # compressed string: "oh one two ... nine double triple"
      #                # split on spaces
       sè              # index (wraps around, so 95 yields "triple")
         ¸»            # join with spaces

```

# Answer
> 16 votes
# 8088 Assembly, IBM PC DOS, ~~164~~ ~~159~~ ~~156~~ 155 bytes

**Binary:**

```
00000000: d1ee 8a0c 03f1 53fd ac3a d075 0343 e2f7  ......S..:.u.C..
00000010: 85db 741c 5f8a d043 f6c3 0174 0a57 bd64  ..t._..C...t.W.d
00000020: 0155 83eb 0374 0957 bd5d 0155 4b4b 75f7  .U...t.W.].UKKu.
00000030: 8ad0 2c2f 7213 518a f0b0 24b1 31bf 6a01  ..,/r.Q...$.1.j.
00000040: fcf2 aefe ce75 fa59 57e2 bc5a 85d2 740c  .....u.YW..Z..t.
00000050: b409 cd21 b220 b402 cd21 ebef c364 6f75  ...!. ...!...dou
00000060: 626c 6524 7472 6970 6c65 246f 6824 6f6e  ble$triple$oh$on
00000070: 6524 7477 6f24 7468 7265 6524 666f 7572  e$two$three$four
00000080: 2466 6976 6524 7369 7824 7365 7665 6e24  $five$six$seven$
00000090: 6569 6768 7424 6e69 6e65 24              eight$nine$

```

Build and test executable using `xxd -r` from above, or download PHONE.COM.

**Unassembled listing:**

```
D1 EE       SHR  SI, 1              ; point SI to DOS PSP (80H) for input string
8A 0C       MOV  CL, BYTE PTR[SI]   ; load input string length into CX
03 F1       ADD  SI, CX             ; move SI to end of input
53          PUSH BX                 ; push a 0 to signal end of output stack
        CHAR_LOOP:
FD          STD                     ; set LODS direction to reverse
AC          LODSB                   ; load next char from [SI] into AL, advance SI
3A D0       CMP  DL, AL             ; is it same as previous char?
75 03       JNZ  NEW_CHAR           ; if not, it's a different char
43          INC  BX                 ; otherwise it's a run, so increment run length
E2 F7       LOOP CHAR_LOOP          ; move on to next char
        NEW_CHAR:
85 DB       TEST BX, BX             ; is there a run greater than 0?
74 1C       JZ   GET_WORD           ; if not, look up digit name
5F          POP  DI                 ; get name for the current digit
8A D0       MOV  DL, AL             ; save current char in DL
43          INC  BX                 ; adjust run count (BX=1 means run of 2, etc)
F6 C3 01    TEST BL, 1              ; is odd? if so, it's a triple
74 0A       JZ   IS_DBL             ; is even, so is a double
57          PUSH DI                 ; push number string ("one", etc) to stack
BD 0164     MOV  BP, OFFSET T       ; load "triple" string
55          PUSH BP                 ; push to stack
83 EB 03    SUB  BX, 3              ; decrement run count by 3
74 09       JZ   GET_WORD           ; if end of run, move to next input char
        IS_DBL:
57          PUSH DI                 ; push number string to stack
BD 015D     MOV  BP, OFFSET D       ; load "double" string
55          PUSH BP                 ; push to stack
4B          DEC  BX                 ; decrement by 2
4B          DEC  BX
75 F7       JNZ  IS_DBL             ; if not end of run, loop double again
        GET_WORD:
8A D0       MOV  DL, AL             ; save current char into DL
2C 2F       SUB  AL, '0'-1          ; convert ASCII char to 1-based index
72 13       JB   NOT_FOUND          ; if not a valid char, move to next
51          PUSH CX                 ; save outer loop counter
8A F0       MOV  DH, AL             ; DH is the index to find, use as scan loop counter
B0 24       MOV  AL, '$'            ; word string is $ delimited
B1 31       MOV  CL, 031H           ; search through length of word data (49 bytes)
BF 016A     MOV  DI, OFFSET W       ; reset word data pointer to beginning
FC          CLD                     ; set DF to scan forward for SCAS
        SCAN_LOOP:
F2/ AE      REPNZ SCASB             ; search until delimiter '$' is found in [DI]
FE CE       DEC  DH                 ; delimiter found, decrement counter
75 FA       JNZ  SCAN_LOOP          ; if counter reached 0, index has been found
59          POP  CX                 ; restore outer loop position
57          PUSH DI                 ; push string on stack
        NOT_FOUND:
E2 BC       LOOP CHAR_LOOP          ; move to next char in input
        OUTPUT_STACK:
5A          POP  DX                 ; get string from top of stack
85 D2       TEST DX, DX             ; it is the last?
74 0C       JZ   EXIT               ; if so, exit
B4 09       MOV  AH, 09H            ; DOS display string function
CD 21       INT  21H                ; write string to console
B2 20       MOV  DL, ' '            ; load space delimiter
B4 02       MOV  AH, 02H            ; DOS display char function
CD 21       INT  21H                ; write char to console
EB EF       JMP  OUTPUT_STACK       ; continue looping
        EXIT:
C3          RET                     ; return to DOS

D   DB "double$"
T   DB "triple"
W   DB "$oh$","one$","two$","three$","four$","five$","six$","seven$","eight$","nine$"

```

**TL;DR:**

The input string is read right to left to make it easier to find a triple. The output is pushed onto the x86 stack to simplify reversing out the display order and also facilitate rearranging the "double" and "triple" words to precede the digit's name.

If the next digit is different than the last, the name is looked up in the list of words and pushed on to the stack. Since there's no formal concept of an "indexed array of variable-length strings" in machine code, the list of words is scanned `i` (the word's index) number of times for the string delimiter (`$`) to find the corresponding word. Helpfully, x86 does have a pair of short instructions (`REPNZ SCASB` which is similar to `memchr()` in C), that simplifies this (thanks CISC!).

If the digit is the same as the previous one, the counter for the length of a "run" is incremented and continues looping leftward on the input. Once the run is over, the digit's name is taken from the stack since it will need to placed after the "double" or "triple" for each grouping. If the length of the run is odd (and run length is `> 1`), the digit's name followed by the string "triple" is pushed to the stack and the run length is reduced by 3. Since the run length will now be even, the step is repeated for "double" until the run length is 0.

When the input string has reached the end, the stack is dumped out with each saved string written to the screen in reverse order.

**I/O:**

A standalone PC DOS executable, input from command line output to console.

Download and test PHONE.COM.

# Answer
> 9 votes
# 05AB1E, ~~61~~ ~~56~~ ~~53~~ ~~52~~ 51 bytes

```
γvyDg;LàäRv… ‹¶½¿#ygè“Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“#yè])áðý

```

-9 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
γ               # Split the (implicit) input into substrings of equal adjacent characters
                #  i.e. "199999991779" → ["1","9999999","1","77","9"]
 v              # Loop over each substring `y`:
   Dg           #  Get the length of a copy of the substring
     ;          #  Halve it
      L         #  Create a list in the range [1, length/2], where odd lengths are
                #  automatically truncated/floored
                #   i.e. "1" (length=1) → 0.5 → [1,0]
                #   i.e. "9999999" (length=7) → 3.5 → [1,2,3]
       à        #  Pop and push the maximum of this list
  y     ä       #  Divide the string into that many parts
                #   → ["1"]
                #   → ["999","99","99"]
         R      #  Reverse the list
                #   → ["99","99","999"]
  v             # Inner loop over each item `y`:
   … ‹¶½¿       #  Push dictionary word: "  double triple"
         #      #  Split it on spaces: ["","","double","triple"]
          yg    #  Get the length of the current item `y`
            è   #  And use it to (0-based) index into the list
   “Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“
                #  Push dictionary string "oh two three four five six seven eight nine"
     #          #  Split it on spaces: ["oh","two","three",...,"nine"]
      yè        #  Use `y` to index into the string-list (with automatic wrap-around,
                #  so since there are 10 words, it basically indexes with a single digit
                #  due to an implicit modulo-10)
                #   i.e. "77" → "seven"
 ]              # Close both loops
  )             # Wrap all values on the stack into a list
   á            # Only keep letters, which removes the empty strings from the list
    ðý          # And join the list on spaces
                # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `… ‹¶½¿` is `" double triple"` and `“Šç€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š“` is `"oh two three four five six seven eight nine"`.

# Answer
> 7 votes
# QuadR, 137 bytesSBCS

Title case with a leading space.

```
∊¯2↑¨@(∊∘⎕A)⍵
(.)\1*
{⍺←(,¨⎕D)⎕R('OhOneTwoThreeFourFiveSixSevenEightNine'(∊⊂⊣)⎕A)⋄' '∊w←⍺,⊃⍵:⍬⋄1=≢⍵:⍺⍵⋄3=≢⍵:'Triple',w⋄'Double',w,∇2↓⍵}⍵M

```

Try it online!

**ϵ**nlist (flatten)
`¯2↑¨` take the last two characters (padding on left with a space) of each characters
`@` at positions where
`(∊∘⎕A)` characters are members of the uppercase **A**lphabet
in the result of the below PCRE Replace operation…

`(.)` any character
`\1` followed by itself
`*` zero or more times, is replaced by the result of the following…

`{…}⍵M` "dfn";  is the **M**atch of the above pattern

`('OhOneTwoThreeFourFiveSixSevenEightNine'(``)⎕A)` apply the following anonymous tacit function with the long string and the uppercase **A**lphabet as left arguments:

membership (of letters in the long string in the uppercase alphabet)

partitions (with a new partition beginning whenever is-a-member

the left argument (i.e. the long string)

`(``)⎕R` PCRE **R**eplace the following patterns with those words:

`⎕D` the digits 0 through 9

treat each as a separate pattern

`⍺←` assign this replacement function to  (for **a**lphabetise)

then,

`⊃⍵` the first character of the match

`,` as a string

apply  to it

`w←` assign this to `w` (for **word**)

`' '∊``:` if space is a member thereof (i.e. if the match was empty):

return nothing (becomes the empty string)

else,

`1=≢⍵:` if one equals the tally of characters in the match (i.e. its length):

`⍺⍵` alphabetise that digit

else,

`3=≢⍵:` if three equals the tally of characters in the match (i.e. its length):

`'Triple',w` prepend "Triple" to the **w**ord

else,

`2↓⍵` drop to digits from the match

recurse on that

`w,` prepend the word

`'Double',` prepend "Double"

# Answer
> 6 votes
# JavaScript (ES6),  ~~161 160 152~~  144 bytes

The output includes a single leading space.

```
s=>[n=>' '+'oh/one/two/three/four/five/six/seven/eight/nine'.split`/`[n],'$1 double$2','triple$2'].map(r=>s=s.replace(/(\S*)( \S+)\2|\d/g,r))&&s

```

Try it online!

or See the formatted source code

## How?

The conversion is processed in three steps:

1. replace each digit with the corresponding English word, preceded by a space
2. replace each pattern `"X X"` with `"double X"`
3. replace each pattern `"double X X"` with `"triple X"`

To save bytes, we use the same regular expression for all steps:

```
/(\S*)( \S+)\2|\d/g

```

which works as follows:

```
(\S*)  -> 1st capturing group: any word, or nothing at all
( \S+) -> 2nd capturing group: a space, followed by a word
\2     -> a copy of the 2nd capturing group
|\d    -> or try to capture a digit instead (for step 1)

```

At step 1, we use a callback function that picks the correct word from a lookup table:

* `"799999"``" seven nine nine nine nine nine"`

At step 2, we replace with `"$1 double$2"`:

* `" (seven)( nine)( nine)"``" seven double nine"`
* `"( nine)( nine) nine"``" double nine nine"`

At step 3, we replace with `"triple$2"`:

* `" (double)( nine)( nine)"``" triple nine"`

# Answer
> 4 votes
# Wolfram Language (Mathematica), 115 bytes

```
{Switch[L=Tr[1^{##}],1," ",3," triple ",_," double "],If[#<1,"oh",IntegerName@#],If[L>3,#0@##3,""]}&@@@Split@#<>""&

```

Try it online!

Takes a list of digits as input. Output includes a leading space.

# Answer
> 4 votes
# Stax, 56 bytes

```
ÇÖ◘⌡¿╒ô╞Γ▓8m☻t7♦3├(Ä⌂≤(┬Ω☻9▲ç╕C╞⌡òσ╗─╣╥─☻╪▼⌡5■ÿ,(┬¥?☺÷•±

```

Run and debug it

# Answer
> 3 votes
# Python 2, ~~171~~ ~~169~~ 168 bytes

```
s=input()
while s:c=s[0];n=(s[1:2]==c)+(s[:3]==c*3!=s[1:4]);print'   eellpbiurotd'[-n:0:-2]+'oh one two three four five six seven eight nine'.split()[int(c)],;s=s[1+n:]

```

Try it online!

-1 byte, thanks to Jitse

# Answer
> 3 votes
# Scala, 213 bytes

Got it. Somehow the recursive version I was trying to build was strongly more verbose-y than this one (still recursive though, but only in one case). Function `f` takes as an input string the phone number and outputs its phonetics with a trailing whitespace.

```
var u="oh one two three four five six seven eight nine" split " "
"(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched
var k=u(o(0)-48)+" "
o.length match{case 3=>"triple "+k
case 1=>k
case _=>"double "+k+f(o drop 2)}})

```

Try it online!
**Edit** : -8b thanks to DrY Wit!

# Scala, 215 bytes

And here comes the leading whitespace version, two bytes longer for some reason (even with massive refactoring).

```
var u="oh one two three four five six seven eight nine" split " "
"(.)\\1*".r.replaceAllIn(s,x=>{var o=x.matched
var k=u(o(0)-48)
" , double , triple ".split(",")(if(o.length>3){k+=f(o drop 2);1}else o.length-1)+k})

```

Try it online!

# Answer
> 3 votes
# PHP, ~~174~~ ~~169~~ ~~166~~ 159 bytes

```
for(;$s=strspn($argn,$d=$argn[$i],$i++);$s==3?($i+=2)+print'triple ':$s<2?:++$i+print'double ',print[oh,one,two,three,four,five,six,seven,eight,nine][$d].' ');

```

Try it online!

For each digit at index of `$i` starting from 0:

* If span of the same digit starting from location of `$i` is equal to 3, prints `'triple '` and adds 2 to `$i` so next iteration will have 2 digits jumped over.
* If span of the same digit starting from location of `$i` is equal to or more than 2 but is not 3, prints `'double '` and adds 1 to `$i` so next iteration will have 1 digit jumped over.
* Prints word for the digit and a space.
* `$i++`.

# Answer
> 3 votes
# Perl 5 `-p`, 111 bytes

```
s/(\d)\1/ double$1/g;s/\w+(\d)\1/triple$1/g;s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge

```

Try it online!

Explanation:

```
s/(\d)\1/ double$1/g; # Replace non-overlapping double digits with " double<digit>"
s/\w+(\d)\1/triple$1/g; # Replace remaining double digits preceded by "double" with "triple<digit>"
s/\d/' '.qw(oh one two three four five six seven eigth nine)[$&]/ge # Replace digits with " <word>"

```

# Answer
> 2 votes
# Perl 6, ~~96~~ 93 bytes

```
{S:g/(.)$0?[$0{}<!$0>]?/{(<triple double>X$)[3-$/.comb]}{+$/??uniname(~$0).words[1]!!'oh'} /}

```

Try it online!

This is an anonymous code block that takes a number and returns a string with the numbers in uppercase, e.g. `0123 => oh ONE TWO THREE` with a single trailing space.

This was deleted for a while until I found out how to use captures in a lookahead, but it should be fixed now.

# Answer
> 2 votes
# T-SQL 2017, 238 bytes

Added some linebreaks to make it readable

```
WHILE''<left(@,1)SELECT @=stuff(@,1,iif(p<4,p,2),'')+
iif(p=1,' ',iif(p=3,' triple ',' double '))
+trim(substring('oh  one  two  threefour five six  seveneightnine',left(@,1)*5,5))
FROM(SELECT~-patindex('%[^'+left(@,1)+']%'+'^',@)p)z
PRINT @

```

**Try it online**

# Answer
> 2 votes
# Retina 0.8.2, 105 bytes

```
+`(.)\1
=$1
.
 $&
= =
triple
=
double
9
nine
8
eight
7
seven
6
six
5
five
4
four
3
three
2
two
1
one
0
oh

```

Try it online! Outputs a leading space. Explanation: I originally tried a regex that automatically matches 2 or 3 digits but @Arnauld's approach of turned out to be golfier. Explanation:

```
+`(.)\1
=$1

```

Match pairs of identical digits and replace the first with a `=`. Then repeat, so that for an odd number the second last digit is also replaced with a `=`.

```
.
 $&

```

Space the digits (and `=`s) out.

```
= =
triple

```

Handle the case of three identical digits.

```
=
double
9
nine
8
eight
7
seven
6
six
5
five
4
four
3
three
2
two
1
one
0
oh

```

Replace all remaining characters with words.

# Answer
> 2 votes
# Jelly, 59 bytes

```
⁵;`,0;$Ɗ€Ẏ;`Ø0ṭ;-œṣjƭƒV€‘$ị“¡ıc⁴Ṛ⁽]@ɱ2¦Ż©Ẉḷ$Æ!)ɗ[ı8ɱḃ%ċ»Ḳ¤K

```

Try it online!

A monadic link that takes a string of digit characters as its argument and returns a Jelly string of space-separated words. When called as a full-program, outputs implicitly.

# Answer
> 2 votes
# C++, 382 bytes

It's not superclever, but someone needed to write a C++ version. The recursive function R goes through the input string and counts repeated values. If there are more than 3 repeats, it pretends there were 2 repeats, then rewinds and tries again.

A few more source chars could probably be squeezed out with `#define` major, but I'm sure a better algo could squeeze out more.

```
#include <iostream>
#include <sstream>
using namespace std;
char*n[]={"oh","one","two","three","four","five","six","seven","eight","nine"};
void R(ostream& s,const char*r,char p='x',int c=0){if(*r==p)R(s,r+1,p,c+1);else
{if(c>1){if(c>= 4){s<<"double ";r-=(c-2);}else if(c==3)s<< "triple ";else if(c==2)s<< "double ";
}if(c >0)s<<n[p-'0']<<" ";if(!*r)return;R(s,r+1,*r,1);}}

void check(const char* in, const char* out)
{
    std::stringstream ss;
    R(ss,in);
    if (out == ss.str()) std::cout << "PASS: "; else std::cout << "FAIL! ";
    std::cout << in << "\n< " << out << "\n> " << ss.str() << std::endl;
}

int main(int c,char**argv)
{
    if (argv[1] == std::string("test"))
    {
        check("0123"         ,"oh one two three ");
        check("4554554"      ,"four double five four double five four ");
        check("000"          ,"triple oh ");
        check("00000"        ,"double oh triple oh ");
        check("66667888"     ,"double six double six seven triple eight ");
        check("19999999179"  ,"one double nine double nine triple nine one seven nine ");
    }
    else
    {
        char* v = argv[1];
        R(std::cout,v);
        std::cout << std::endl;
    }
}

```

and verification of test cases:

```
pa-dev01$ ./a.out test
PASS: 0123
< oh one two three
> oh one two three
PASS: 4554554
< four double five four double five four
> four double five four double five four
PASS: 000
< triple oh
> triple oh
PASS: 00000
< double oh triple oh
> double oh triple oh
PASS: 66667888
< double six double six seven triple eight
> double six double six seven triple eight
PASS: 19999999179
< one double nine double nine triple nine one seven nine
> one double nine double nine triple nine one seven nine

```

# Answer
> 1 votes
# (Roblox) Lua 5.1, 166 bytes

```
for I,N in('111 triple 11 double 1 '):gmatch'(%d+)(%D+)'do for i,n in('0oh1one2two3three4four5five6six7seven8eight9nine'):gmatch'(.)(%l+)'do s=s:gsub(i*I,N..n)end end

```

*Ensure `s` is a predefined string value populated only with digits; that will be the variable to be modified. The result will include a leading space* `[\u20]` *character.*

# Answer
> 1 votes
# Red, 242 bytes

```
func[s][b:[copy t skip t]parse s[any[change[b t ahead not t](rejoin["triple "t])|
change b(rejoin["double "t])| skip]]foreach c s[prin either i:
find"0123456789"c[rejoin[pick[:oh:one:two:three:four:five:six:seven:eight:nine]index? i" "]][c]]]

```

Try it online!

# Answer
> 1 votes
# Scala, 253 bytes

```
def g(s:String):String={val t="oh one two three four five six seven eight nine".split(" ")(s(0)-48)
s.length match{case 3=>"triple "+t;case 2=>"double "+t;case 1=>t;case _=>"double "+t+" "+g(s drop 2)}}
s=>"(.)\\1*".r.findAllIn(s).map(g(_)) mkString " "

```

Try it online!

# Answer
> 1 votes
# Oracle SQL, 578 bytes (in formatted form)

Solution is not concise by any means so posting it in formatted way.

```
with r(s) as
(select x from t
  union all
 select case
           when length(regexp_substr(s, '(.)(\1)+')) = 3
           then regexp_replace(s, '^...')
           else regexp_replace(s, '^(.)\1|^.')
        end
   from r
  where s is not null)
select listagg(decode(length(r),  2, 'double ',  3, 'triple ') ||
               decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ')
               within group (order by rownum)
  from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r
          from r order by length(s) desc);

```

Test in SQL\*Plus

```
SQL> create table t(x) as select /*'45547777777774'*/ '1999999910079' from dual;

Table created.

SQL> set pages 0
SQL> with r(s) as
  2  (select x from t
  3    union all
  4   select case
  5             when length(regexp_substr(s, '(.)(\1)+')) = 3
  6             then regexp_replace(s, '^...')
  7             else regexp_replace(s, '^(.)\1|^.')
  8          end
  9     from r
 10    where s is not null)
 11  select listagg(decode(length(r),  2, 'double ',  3, 'triple ') ||
 12                 decode(substr(r, 1, 1), 0, 'oh', to_char(to_date(substr(r, 1, 1), 'j'), 'jsp')), ' ')
 13                 within group (order by rownum)
 14    from (select regexp_replace(s, lag(s) over (order by length(s)) || '$') r
 15            from r order by length(s) desc);
one double nine double nine triple nine one double oh seven nine

```

The main trick is that digits converted into words using Oracle format models instead of hard-coded literals "one" ... "nine".

# Answer
> 1 votes
# JavaScript, 142 bytes

```
s=>s.replace(/(.)(\1\1(?!\1)|\1|)/g,t=>(t[2]?' triple ':t[1]?' double ':' ')+'oh one two three four five six seven eight nine'.split` `[t[0]])

```

Try it online!

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


title: An array battle with odd secret powers

text:
# Question
Title: An array battle with odd secret powers
Here is a relatively simple two dimensional array challenge.

Imagine a battlefield of 625 foot soldiers. You command the ***odd*** troops, but unfortunately the strength of the ***even*** troops overwhelms you. Thankfully, your soldiers have a secret power: If the power of each odd troop and the fellow odd allies surrounding them is divisible by a secret power number, they unleash their *ultimate attack* and win! You must honor each victorious soldier.

**Rules**

Given a 25 x 25 integer array where each element contains the product of its x and y position plus 1, return the coordinates of every "victorious" odd element that meets the following criteria:

The sum of the element's value and its adjacent odd elements (up, down, left, and right) is divisible by the input (secret power number). It must have elements adjacent to it on all four sides and not be on an edge.

Submissions can be either a function or full program that requires a single input. The output can be in any order.

Our 25 x 25 array, the battlefield, looks like this:

```
1, 1, 1, 1,...
1, 2, 3, 4,...
1, 3, 5, 7,...
1, 4, 7, 10,...
etc.

```

**Example**

Here is a 3 x 3 example:

```
43, 57, 71
46, 61, 76
49, 65, 81

```

To determine if an element (61, in the center) wins, we sum the values of it and the adjacent odd elements.

```
61 + 57 + 65 = 183

```

If the total is divisible by the input, the element's x and y position is printed. If our input is 3, because 183 is divisible by 3, "1, 1" is printed.

**Output**

If the input (secret power number) is 37, the elements returned (victorious soldiers to be commended) must be:

```
2, 18
3, 12
4, 9
5, 22
6, 6
8, 23
9, 4
10, 11
11, 10
12, 3
18, 2
22, 5
23, 8

```

If the input is 191, the elements returned must be:

```
10, 19
19, 10

```

An input of 3:

```
1, 2
1, 4
1, 6
1, 8
1, 10
1, 12
1, 14
1, 16
1, 18
1, 20
1, 22
2, 1
2, 3
2, 4
2, 5
2, 7
2, 9
2, 10
2, 11
2, 13
2, 15
2, 16
2, 17
2, 19
2, 21
2, 22
2, 23
3, 2
3, 4
3, 6
3, 8
3, 10
3, 12
3, 14
3, 16
3, 18
3, 20
3, 22
4, 1
4, 2
4, 3
4, 5
4, 7
4, 8
4, 9
4, 11
4, 13
4, 14
4, 15
4, 17
4, 19
4, 20
4, 21
4, 23
5, 2
5, 4
5, 6
5, 8
5, 10
5, 12
5, 14
5, 16
5, 18
5, 20
5, 22
6, 1
6, 3
6, 5
6, 7
6, 9
6, 11
6, 13
6, 15
6, 17
6, 19
6, 21
6, 23
7, 2
7, 4
7, 6
7, 8
7, 10
7, 12
7, 14
7, 16
7, 18
7, 20
7, 22
8, 1
8, 3
8, 4
8, 5
8, 7
8, 9
8, 10
8, 11
8, 13
8, 15
8, 16
8, 17
8, 19
8, 21
8, 22
8, 23
9, 2
9, 4
9, 6
9, 8
9, 10
9, 12
9, 14
9, 16
9, 18
9, 20
9, 22
10, 1
10, 2
10, 3
10, 5
10, 7
10, 8
10, 9
10, 11
10, 13
10, 14
10, 15
10, 17
10, 19
10, 20
10, 21
10, 23
11, 2
11, 4
11, 6
11, 8
11, 10
11, 12
11, 14
11, 16
11, 18
11, 20
11, 22
12, 1
12, 3
12, 5
12, 7
12, 9
12, 11
12, 13
12, 15
12, 17
12, 19
12, 21
12, 23
13, 2
13, 4
13, 6
13, 8
13, 10
13, 12
13, 14
13, 16
13, 18
13, 20
13, 22
14, 1
14, 3
14, 4
14, 5
14, 7
14, 9
14, 10
14, 11
14, 13
14, 15
14, 16
14, 17
14, 19
14, 21
14, 22
14, 23
15, 2
15, 4
15, 6
15, 8
15, 10
15, 12
15, 14
15, 16
15, 18
15, 20
15, 22
16, 1
16, 2
16, 3
16, 5
16, 7
16, 8
16, 9
16, 11
16, 13
16, 14
16, 15
16, 17
16, 19
16, 20
16, 21
16, 23
17, 2
17, 4
17, 6
17, 8
17, 10
17, 12
17, 14
17, 16
17, 18
17, 20
17, 22
18, 1
18, 3
18, 5
18, 7
18, 9
18, 11
18, 13
18, 15
18, 17
18, 19
18, 21
18, 23
19, 2
19, 4
19, 6
19, 8
19, 10
19, 12
19, 14
19, 16
19, 18
19, 20
19, 22
20, 1
20, 3
20, 4
20, 5
20, 7
20, 9
20, 10
20, 11
20, 13
20, 15
20, 16
20, 17
20, 19
20, 21
20, 22
20, 23
21, 2
21, 4
21, 6
21, 8
21, 10
21, 12
21, 14
21, 16
21, 18
21, 20
21, 22
22, 1
22, 2
22, 3
22, 5
22, 7
22, 8
22, 9
22, 11
22, 13
22, 14
22, 15
22, 17
22, 19
22, 20
22, 21
22, 23
23, 2
23, 4
23, 6
23, 8
23, 10
23, 12
23, 14
23, 16
23, 18
23, 20
23, 22

```

An input of 5:

```
1, 4
1, 14
2, 2
2, 4
2, 6
2, 7
2, 8
2, 10
2, 12
2, 14
2, 16
2, 17
2, 18
2, 20
2, 22
3, 8
3, 18
4, 1
4, 2
4, 4
4, 6
4, 8
4, 10
4, 11
4, 12
4, 14
4, 16
4, 18
4, 20
4, 21
4, 22
6, 2
6, 4
6, 6
6, 8
6, 9
6, 10
6, 12
6, 14
6, 16
6, 18
6, 19
6, 20
6, 22
7, 2
7, 12
7, 22
8, 2
8, 3
8, 4
8, 6
8, 8
8, 10
8, 12
8, 13
8, 14
8, 16
8, 18
8, 20
8, 22
8, 23
9, 6
9, 16
10, 2
10, 4
10, 6
10, 8
10, 10
10, 12
10, 14
10, 16
10, 18
10, 20
10, 22
11, 4
11, 14
12, 2
12, 4
12, 6
12, 7
12, 8
12, 10
12, 12
12, 14
12, 16
12, 17
12, 18
12, 20
12, 22
13, 8
13, 18
14, 1
14, 2
14, 4
14, 6
14, 8
14, 10
14, 11
14, 12
14, 14
14, 16
14, 18
14, 20
14, 21
14, 22
16, 2
16, 4
16, 6
16, 8
16, 9
16, 10
16, 12
16, 14
16, 16
16, 18
16, 19
16, 20
16, 22
17, 2
17, 12
17, 22
18, 2
18, 3
18, 4
18, 6
18, 8
18, 10
18, 12
18, 13
18, 14
18, 16
18, 18
18, 20
18, 22
18, 23
19, 6
19, 16
20, 2
20, 4
20, 6
20, 8
20, 10
20, 12
20, 14
20, 16
20, 18
20, 20
20, 22
21, 4
21, 14
22, 2
22, 4
22, 6
22, 7
22, 8
22, 10
22, 12
22, 14
22, 16
22, 17
22, 18
22, 20
22, 22
23, 8
23, 18

```

This is , the lowest byte-count code without using standard loopholes is the winner.

As this is my first submission, any advice is greatly appreciated. Thanks!

# Answer
# JavaScript (ES6),  ~~83 81 80~~  76 bytes

The output is a space-delimited string of coordinates \\$x,y\\$.

```
f=(n,x=y=23,k=5,v=x*y)=>y?(v&1|~v*k%n?[]:[x,y]+' ')+f(n,--x||23|!y--,k^6):[]

```

Try it online!

### How?

Let \\$c\_{x,y}=xy+1\\$ be the value of the cell located at \\$(x,y)\\$.

Since the cells on the edge are not accounted, we assume \\$0\<x\<24\\$ and \\$0\<y\<24\\$.

\\$c\_{x,y}\\$ is odd if either \\$x\\$ or \\$y\\$ is even (or both of them).

If \\$x\\$ is odd, then \\$c\_{x-1,y}\\$ and \\$c\_{x+1,y}\\$ are odd. But in that case, \\$y\\$ must be even, and so are \\$c\_{x,y-1}\\$ and \\$c\_{x,y+1}\\$. The sum of the cell and its odd surrounding neighbors is:

$$s\_{x,y}=c\_{x,y}+c\_{x-1,y}+c\_{x+1,y}=3c\_{x,y}$$

Similarly, if \\$y\\$ is odd:

$$s\_{x,y}=c\_{x,y}+c\_{x,y-1}+c\_{x,y+1}=3c\_{x,y}$$

If both \\$x\\$ and \\$y\\$ are even, all surrounding neighbors are odd:

$$s\_{x,y}=c\_{x,y}+c\_{x-1,y}+c\_{x+1,y}+c\_{x,y-1}+c\_{x,y+1}=5c\_{x,y}$$

This multiplier (\\$3\\$ or \\$5\\$) is named \\$k\\$ in the JS code.

### Commented

```
f = (                // f is a recursive function taking:
  n,                 //   n      = input
  x = y = 23,        //   (x, y) = current coordinates, starting at (23, 23)
  k = 5,             //   k      = multiplier (3 or 5)
  v = x * y          //   v      = x * y (value of the current cell - 1)
) =>                 //
  y ?                // if y is greater than 0:
    ( v & 1 |        //   if v is odd (meaning that v + 1 is not)
      ~v * k % n ?   //   or n is not a divisor of -(v + 1) * k:
        []           //     append nothing
      :              //   else:
        [x, y] + ' ' //     append the coordinates followed by a space
    ) +              //
    f(               //   append the result of a recursive call:
      n,             //     pass n unchanged
      --x ||         //     decrement x; if the result is 0:
        23 | !y--,   //       pass 23 instead and decrement y
      k ^ 6          //     update k (5 -> 3 -> 5 -> ...)
    )                //   end of recursive call
  :                  // else:
    []               //   stop recursion

```
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~97~~ ~~93~~ ~~91~~ 90 bytes

```
x=>{for(int i=0,d=0,j;++i<24;d=5)for(j=0;++j<24;d^=6)if(i*j%2+(i*j+1)*d%x<1)Print((i,j));}

```

Saved 6 bytes thanks to @Kevin Cruijssen!

Try it online!
> 3 votes

# Answer
# Python 2, 83 bytes

```
lambda n:[(x,y)for x in R for y in R if~(x*y)*[5,3][x+y&1]%n<1>x*y%2]
R=range(1,24)

```

Try it online!

Thanks to Arnauld for saving a byte.
> 2 votes

# Answer
# Stax, 25 bytes

```
âÖÅ{┼îÄï$εS╢,σδXú(Γ°#↑√nG

```

Run and debug it

This is mostly just brute force, with one marginally clever observation. All odd troops have either 2 or 4 odd neighbors. And the total sum of these plus the original solder is either `3p` or `5p` where `p` is the soldier's power. The coefficient (3 or 5) can be determined by `gcd(2, x, y) * 2 + 1)` where `x` and `y` are the soldier's coordinates.
> 2 votes

# Answer
# JavaScript (SpiderMonkey), 69 bytes

```
x=>{for(i=24;--i;)for(j=24,d=5;--j;d^=6)i*j%2+~(i*j)*d%x||print(j,i)}

```

Try it online!
> 1 votes

# Answer
# Jelly, 22 bytes

```
23×þ`‘µḤḤÐeÐe+×Ḃ³ḍaƊŒṪ

```

Try it online!

A full program that takes a single argument, the secret power number, and implicitly prints a list of `[x, y]` pairs. Uses the observation others have made about multiples of 3 and 5.
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~60~~ 58 bytes

```
Position[If[2∣+##,5,3](1+1##)&~Array~{23,23},a_/;#∣a]&

```

Try it online!

Looked around after posting and realized I really needed to turn my brain on...
> 1 votes

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