title: Overflow-Proof Buffer

text:
# Question
Title: Overflow-Proof Buffer
## Background

Programmers these days can't seem to keep their buffers straight! A common source of error is trying to use an array index that is too large for the buffer. Your task is to implement a buffer where large indices are reduced to a size that the buffer can handle. Because I decide exactly what's best for everyone, you will implement this buffer to my precise specifications.

## Overview

You have a insert-only buffer that grows in size as elements are added to it. The buffer is zero-indexed, and also indexed *modulo* its current size. The special rule for this challenge is this:

* **To insert an item at index *i* means to compute *j*, `j = i % buffer.length()` and insert the new item after the *jth* item in the list.**

The only special case is if the buffer is empty, as arithmetic modulo zero doesn't work. Thus, if the buffer is currently empty, the new item will be index *0*.

If the buffer has only one item, then you are always inserting after the *0th* item. This is just one instance of the general case.

If the buffer contains 6 items: `[4, 9, 14, 8, 5, 2]` and you are told to insert a new item `10` at index *15*, you find that `15 % 6 == 3`, and then insert the new `10` after the `8` at index *3* which gives a resulting buffer of `[4, 9, 14, 8, 10, 5, 2]`

## Problem

Write a function or program that takes in an ordered list of positive integers, and positive integer indices at which to insert them.

Start with an empty buffer, and add the specified integers to the buffer at the corresponding indices.

Output the ordered list of integers that are in the buffer after all the specified insertions have been made.

This is a code-golf challenge, so shortest code wins.

## Input guidelines

You may take the input lists however you see fit. Examples:

* List of pairs: `[ [1,1], [2,4], [3,9], [4,16], [5,25]...]`
* Item list and index list: `[1, 2, 3, 4, 5...], [1, 4, 9, 16, 25]`
* Flattened: `[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 ...]`
* etc.

You may assume the input always contains at least one item and corresponding index.

## Test cases

Squares case from above:

```
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64)] -> [1, 2, 8, 7, 6, 5, 4, 3]

```

I generated these randomly:

```
[(11, 9), (13, 14)] -> [11, 13]
[(1, 18), (11, 7), (3, 35), (16, 22)] -> [1, 11, 16, 3]
[(3, 16), (16, 37), (0, 28), (18, 24)] -> [3, 18, 0, 16]
[(7, 26), (8, 20), (11, 39), (1, 23), (17, 27)] -> [7, 8, 11, 1, 17]
[(15, 35), (17, 7), (16, 15), (1, 13), (2, 6), (11, 34)] -> [15, 17, 1, 2, 16, 11]
[(2, 13), (1, 20), (16, 25), (8, 21), (5, 2), (16, 37), (3, 0)] -> [2, 3, 8, 1, 16, 5, 16]
[(6, 20), (15, 15), (12, 26), (10, 27), (17, 13), (7, 18), (4, 16)] -> [6, 10, 17, 12, 7, 4, 15]
[(18, 9), (5, 34), (15, 4), (12, 29), (2, 5), (7, 0), (7, 10), (16, 38)] -> [18, 7, 15, 2, 16, 5, 7, 12]
[(0, 12), (12, 0), (4, 16), (15, 12), (6, 28), (8, 10), (11, 24), (0, 25)] -> [0, 11, 8, 6, 15, 0, 4, 12]
[(6, 12), (14, 13), (10, 33), (11, 35), (1, 3), (0, 28), (15, 27), (8, 10), (1, 2)] -> [6, 14, 10, 1, 11, 8, 15, 0, 1]
[(2, 29), (19, 30), (18, 17), (13, 3), (0, 21), (19, 19), (11, 13), (12, 31), (3, 25)] -> [2, 13, 3, 11, 0, 12, 19, 18, 19]

```

## Python3 reference implementation

```
def f(inputs):
    # `inputs` is a list of pairs
    buff = []
    for item, index in inputs:
        if len(buff) == 0:
            buff.insert(0, item)
        else:
            insert_after = index % len(buff)
            buff.insert(insert_after+1, item)
    return buff

```

# Answer
> 4 votes
# MATL, ~~24~~ 22 bytes

```
"N?@2)yn\Q:&)@1)wv}@1)

```

Input is a matrix (with `;` as row separator) containing the values in the first row and the indices in the second.

Output is a column array, displayed as numbers separated by newlines.

**Try it online!** Or **verify all test cases**, with each result displayed on a single line.

### Explanation

```
"          % Input matrix (implicit). For each column
  N        %   Number of elements in the stack
  ?        %   If nonzero (true for all iterations but the first)
    @2)    %     Push second element of current column: new index
    yn     %     Duplicate current buffer; push its number of elements
    \      %     Modulo
    Q      %     Add 1
    :&)    %     Split buffer at that point. This gives two pieces, one
           %     of which may be empty
    @1)    %     Push first element of current column: new value
    wv     %     Swap; concatenate all stack. This places the new value
           %     between the two pieces of the buffer
  }        %   Else (this is executed only in the first iteration)
    @1)    %     Push first element of current column: new value
           %   End (implicit)
           % End (implicit)
           % Display (implicit)

```

# Answer
> 8 votes
# Perl, 37 bytes

35 bytes of code + 2 bytes for `-lp` flags.

```
splice@F,1+<>%(@F||1),0,$_}{$_="@F"

```

Try it online!

The implementation is quite straight forward, `splice` inserts in array `@F` at index `1+<>%(@F||1)` (note that `@F||1` handles the case of the array being empty).

Just a few words about the (seemingly) unmatched braces `}{` (because I had a comment about it, and I think it's quite weird for people who don't know Perl), and it's a quite common trick in Perl golfings:
`-p` flag surrounds the code with (roughly) `while(<>){ CODE } continue { print }`, (the `continue` is executed after each iteration). So with those *unmatched* `}{`, I change my code to `while(<>) { CODE}{ } continue { print }`. So it creates an empty block right after my code (but that's not a problem), and the `continue` is executed only once, after the `while` (ie. when the all the input has been read).

# Answer
> 5 votes
# ES6 (Javascript), ~~58~~,~~57~~,~~53~~, 50 bytes

**Golfed**

```
a=>a.map((e,i)=>b.splice(1+e[1]%i,0,e[0]),b=[])&&b

```

Takes an array of index-value pairs, as input.

EDITS

* Use `&&` to return value, -1 byte
* Removed `|0` (as splice apparently can handle NaN just well), -2 bytes
* Made `b=[]` a second "argument" to *map()*, -2 bytes (Thx @ETHproductions !)
* Replaced b.length with map() index (i), -3 bytes (Thx @Patrick Roberts !)

**Test**

```
F=a=>a.map((e,i)=>b.splice(1+e[1]%i,0,e[0]),b=[])&&b

F([[11, 9], [13, 14]])
[ 11, 13 ]

F([[2, 29], [19, 30], [18, 17], [13, 3], [0, 21], [19, 19], [11, 13], [12, 31], [3, 25]])
[ 2, 13, 3, 11, 0, 12, 19, 18, 19 ]

```

# Answer
> 5 votes
# Haskell, ~~70~~ 69 bytes

```
b!(x,i)|b==[]=[x]|j<-1+i`mod`length b=take j b++x:drop j b
foldl(!)[]

```

Try it online! Usage: `foldl(!)[] [(1,5),(2,4),(3,7)]`. Saved one byte thanks to @nimi!

Explanation:

```
b!(x,i)                         -- b!(x,i) inserts x into list b at position i+1
 | b==[] = [x]                  -- if b is empty return the list with element x
 | j <- 1 + i `mod` length b    -- otherwise compute the overflow-save insertion index j
     = take j b ++ x : drop j b -- and return the first j elements of b + x + the rest of b
foldl(!)[]                      -- given a list [(1,2),(3,5),...], insert each element with function ! into the initially empty buffer

```

---

Solution without computing the modulus: (90 bytes)

```
f h t(x,-1)=h++x:t
f h[]p=f[]h p
f h(c:t)(x,i)=f(h++[c])t(x,i-1)
g((x,_):r)=foldl(f[])[x]r

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~62~~ 60 bytes

Takes input as a list of pairs, prints the result. *Edit: Outgolfed by Dennis*

```
b=[]
for x,y in input():b.insert(1+y%(len(b)or 1),x)
print b

```

**Try it online!**

This is quite simple - loop through the input, inserting the items into the correct place, and then print the result. Deciding which index to insert into is done with `1+y%(len(b)or 1)`. This is the standard way to do modular indexing, with the `or 1` to handle the edge case of an empty list.

# Answer
> 4 votes
# Python 2, ~~64~~ ~~62~~ ~~58~~ 56 bytes

```
x=[]
for n,i in input():x[i%(len(x)or 1)+1:0]=n,
print x

```

*Thanks to @xnor for golfing off 2 bytes!*

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 60 bytes

```
f=([[q,r],...a],z=[])=>z.splice(r%z.length+1,0,q)+a?f(a,z):z

```

### Test snippet

```
f=([[q,r],...a],z=[])=>z.splice(r%z.length+1,0,q)+a?f(a,z):z

I.textContent = I.textContent.replace(/(.+) -> (.+)/g, (_,a,b) => _ + " (" + (f(eval(a.replace(/\(/g, "[").replace(/\)/g, "]"))) + "" == eval(b) + "") + ")")
```

```
<pre id=I>[(11, 9), (13, 14)] -> [11, 13]
[(1, 18), (11, 7), (3, 35), (16, 22)] -> [1, 11, 16, 3]
[(3, 16), (16, 37), (0, 28), (18, 24)] -> [3, 18, 0, 16]
[(7, 26), (8, 20), (11, 39), (1, 23), (17, 27)] -> [7, 8, 11, 1, 17]
[(15, 35), (17, 7), (16, 15), (1, 13), (2, 6), (11, 34)] -> [15, 17, 1, 2, 16, 11]
[(2, 13), (1, 20), (16, 25), (8, 21), (5, 2), (16, 37), (3, 0)] -> [2, 3, 8, 1, 16, 5, 16]
[(6, 20), (15, 15), (12, 26), (10, 27), (17, 13), (7, 18), (4, 16)] -> [6, 10, 17, 12, 7, 4, 15]
[(18, 9), (5, 34), (15, 4), (12, 29), (2, 5), (7, 0), (7, 10), (16, 38)] -> [18, 7, 15, 2, 16, 5, 7, 12]
[(0, 12), (12, 0), (4, 16), (15, 12), (6, 28), (8, 10), (11, 24), (0, 25)] -> [0, 11, 8, 6, 15, 0, 4, 12]
[(6, 12), (14, 13), (10, 33), (11, 35), (1, 3), (0, 28), (15, 27), (8, 10), (1, 2)] -> [6, 14, 10, 1, 11, 8, 15, 0, 1]
[(2, 29), (19, 30), (18, 17), (13, 3), (0, 21), (19, 19), (11, 13), (12, 31), (3, 25)] -> [2, 13, 3, 11, 0, 12, 19, 18, 19]</pre>
```

# Answer
> 2 votes
# PHP, ~~72~~ 92 bytes

```
for($b=[];++$i<$argc;)array_splice($b,$b?$argv[$i]%count($b)+1:0,0,$argv[++$i]);print_r($b);

```

takes input flattened from command line arguments. Run with `-nr`.

# Answer
> 2 votes
# , ~~38~~ ~~40~~ 35 bytes

This answer bends the definition of list, and isn't normally a language you'd use for list manipulation, but I wanted to use `[count]/{regex}` which I recently added to V. The input is taken like `[index] [num] [index] [num] ...` and returned like `[num] [num] [num]`.

```
Í ¨ä«© ½/¯ÜdÜ+òhea ±^
Hdd2xdG@"
X

```

Try it online!

Hexdump for 2 hidden characters:

```
00000000: cd20 a8e4 aba9 20bd 2faf dc64 dc2b f268  . .... ./..d.+.h
00000010: 6561 20b1 161b 5e0a 4864 6432 7864 4740  ea ...^.Hdd2xdG@
00000020: 220a 58                                  ".X

```

### Explanation

The code up to `dG@"` formats all `\d+ \d+` pairs so that a list 1 2 3 4 5 6 would end up like

```
a 2^[^3/\d\+
hea 4^[^5/\d\+
hea 6^[^

```

and then the `dG@"` executes all of that as V code like the following:

```
a 2^[                 | insert " 2" and return to command mode
     ^                | LOOP: go to the first number
      3/\d\+          | find the 3rd number (0 indexed)
h                     | move one character left
 e                    | go to the end of the next word
  a 4^[               | append " 4" and return to command mode
       ^5/\d\+        | basically the same as LOOP on, just with different numbers

```

# Answer
> 2 votes
# Java 7, ~~125~~ 124 bytes

```
import java.util.*;List z(int[]a){List r=new Stack();for(int i=0,q=a.length/2;i<q;)r.add(i<1?0:a[i+q]%i+1,a[i++]);return r;}

```

Accepts a flat list of values followed by indexes. For the squares test case the input would be `new int[] {1, 2, 3, 4, 5, 6, 7, 8, 1, 4, 9, 16, 25, 36, 49, 64}`

Try it online!

# Answer
> 1 votes
## Mathematica, 62 bytes

```
Fold[Insert[#,#2[[1]],Mod[Last@#2,Tr[1^#]]+2/.0/0->-1]&,{},#]&

```

Pure function with first argument `#` expected to be a list of pairs. Starting with the empty list `{}`, left `Fold` the input list `#` with the following function:

```
Insert[                                            Insert
       #,                                          into the first argument
         #2[[1]],                                  the first element of the second argument
                 Mod[                              at the position given by the modulus of
                     Last@#2,                      the second element of the second argument
                             Tr[1^#]               with respect to the length of the first argument
                                    ]+2            plus 2 (plus 1 to account for 1-indexing, plus 1 because we are inserting after that position)
                                       /.          then replace
                                         0/0       Indeterminate
                                            ->     with
                                              -1   negative 1
                                                ]& End of function

```

# Answer
> 1 votes
# Perl 6, 51 bytes

```
{my @a;.map:{splice @a,(@a??$^b%@a+1!!0),0,$^a};@a}

```

Takes the flattened input.

# Answer
> 1 votes
## Clojure, 87 bytes

```
#(reduce(fn[r[v i]](let[[b e](split-at(+(mod i(max(count r)1))1)r)](concat b[v]e)))[]%)

```

---
Tags: code-golf
---


title: Guide the Alphabet

text:
# Question
Title: Guide the Alphabet
# Guide the Alphabet

Given an array of directions, where the directions are defined as follows:

```
NW  N  NE
W   .   E
SW  S  SE

```

Or as indexes (you may use these indices for directions instead of the strings above):

```
0 1 2
3 . 4
5 6 7

```

You may choose either format, supporting both is not required by the challenge. Generate the corresponding alphabet String that represents the drawn path, starting with A. The number of directions will never exceed 25, meaning that it can never go past `Z`, so you don't have to handle this scenario. No other input formats will be accepted unless you can explain why these formats do not work due to a language limitation. This is easier to explain using a verbosely worked out example.

---

So, lets look at a quick example:

```
[E,SE,N,S,S,S,NW,W,N] or [4,7,1,6,6,6,0,3,1]

```

Always start with A.

```
A

```

Go East to B.

```
A-B

```

Go South East to C.

```
A-B
   \
    C

```

Go North to D.

```
A-B D
   \|
    C

```

Go back South to E, overwriting C.

```
A-B D
   \|
    E

```

Continue South for 2 cycles to both F and G.

```
A-B D
   \|
    E
    |
    F
    |
    G

```

Go North West to H.

```
A-B D
   \|
    E
    |
  H F
   \|
    G

```

Go West to I.

```
A-B D
   \|
    E
    |
I-H F
   \|
    G

```

End to the North at point J.

```
A-B D
   \|
J   E
|   |
I-H F
   \|
    G

```

---

The final value you would return is by reading the final graph left to right, top to bottom:

```
ABD
JE
IHF
G

```

Resulting in:

```
ABDJEIHFG

```

---

This is , lowest byte-count wins.

# Answer
> 6 votes
# MATL, ~~64~~ ~~58~~ ~~57~~ ~~50~~ ~~46~~ ~~40~~ ~~37~~ ~~36~~ ~~35~~ 30 bytes

```
O'!":<TUV '59-G)hYsIH$6#u64+c!

```

Try it at MATL Online

**Explanation**

```
O           % Push the number 0 to the stack
'!":<TUV '  % String literal
59-         % Converts this string literal into [-26 -25 -1 1 25 26 27 -27]. These
            % are deltas for the linear indexes into the matrix corresponding to each
            % of the directions. Note that the -27 is at the end since a 0 index wraps
            % around to the end
i)          % Grab the input and use it to index into the delta array
h           % Horizontally concatenate this with the 0 (our starting point)
Ys          % Take the cumulative sum to get the absolute linear index (location) of
            % each successive letter
IH$6#u      % Find the index of the last (sorted) occurrence of each location
64+         % Add 64 to this index to create ASCII codes
c!          % Convert to character, transpose, and display

```

# Answer
> 12 votes
## JavaScript (ES6), ~~108~~ ~~107~~ ~~94~~ 87 bytes

*Saved a whopping 13 bytes, thanks to Titus!*
*Saved 7 more bytes, thanks to edc65!*

```
let f =

a=>[i=9,...a].map(d=>r[p+=(d+=d>3)*9-d%3*8-28]=(++i).toString(36),r=[],p=646)&&r.join``

console.log(f([4,7,1,6,6,6,0,3,1]));
```

### How it works

The formula `(d += d > 3) * 9 - d % 3 * 8 - 28` translates the directions `0..7` into the following offsets:

```
0   1   2       -28 -27 -26
3   x   4  -->   -1  x   +1
5   6   7       +26 +27 +28

```

We use these offsets to move the pointer `p` into the one-dimensional array `r` and write the letters at the resulting positions.

We iterate on `[i = 9, ...a]` rather than just `a` in order to insert the starting letter 'a'. Because we initialize `i` to `9` at the same time, we introduce a special offset of 54 (the result of the above formula for `d = 9`). After the first iteration, `p` equals `646 + 54 = 700`, which leaves just enough space to support up to 25 moves to North-West: `25 * -28 = -700`. That's why `p` is initialized to `646`.

Then we just have to join the array to get our final string. Undefined values in between letters are simply ignored by `join()`.

# Answer
> 5 votes
# Octave, ~~145~~ ~~138~~ ~~131~~ ~~123~~ ~~105~~ ~~103~~ ~~90~~ ~~87~~ 85 bytes

```
@(a){[~,k]=unique(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1),'rows');[k'+64 '']}{2}

```

Try It Online

Thanks to Suever 2 bytes saved!

Previous answer 103 bytes:

```
@(a)[nonzeros(accumarray(cumsum([1 fix((z=a+(a>3))/3);1 mod(z,3)]'-1)+30,65:nnz(++a)+65,[],@max)')' '']

```

Try It Online!

First try 145 byts

```
@(a){[x y]=find(~impad(1,1,1));c=cumsum([0 0;([y x]-2)(++a,:)]);c=c-min(c)+1;n=nnz(a);[nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' '']}{5}

```

Some Explanations

```
@(a){
    [x y]=find([1 0 1]|[1;0;1]);                            %generate 2d coordinates corresponding to 1d input indices
    XY = [y x]-2;
    c=cumsum([0 0;XY(++a,:)]);                              %cumulative sum of coordinates to find position of characters
    c=c-min(c)+1;n=nnz(a);
    [nonzeros(sparse(c(:,1),c(:,2),65:n+65,'unique')')' ''] %using sparse matrix to place characters at specified positions
    }{5}

```

# Answer
> 5 votes
## MATLAB, ~~87~~ 85 bytes

*saved 2 bytes thanks to Luis Mendo*

```
function a=f(s);i='()*BD\]^'-67;[~,a]=unique([0 cumsum(i(s+1))],'last');a=[a'+64,''];

```

# Answer
> 4 votes
# PHP, 93 bytes

Operating on a single array like Kodos Johnson´s answer.
But this has so many more ideas that I posted on my own.

```
for($r=[$c=A];""<$d=$argv[++$i];)$r[$p+=($d+=$d>3)*9-$d%3*8-28]=++$c;ksort($r);echo join($r);

```

takes numbers from command line arguments. Run with `-nr`.

**moving the cursor**

initial calculation:

```
$d+=$d>3;           // if $d>3, add 1
$p+= ($d/3-1|0)*26  // add/subtract 26 for line change
    +$d%3-1;        // add/substract 1 for column change

```

golfing:

```
$d+=$d>3;$p+=($d/3-1|0)*27+$d%3-1;          // +0: multiple of 3 instead of 26
$d+=$d>3;$p+=($d/3|0)*27-27+$d%3-1;         // +1: distribute `line-1`
$d+=$d>3;$p+=($d/3)*27-$d%3/3*27-27+$d%3-1; // +8: distribute `|0`
$d+=$d>3;$p+=$d*9-$d%3*9-27+$d%3-1;         // -8: `/3*27` -> `*9`
$d+=$d>3;$p+=$d*9-$d%3*8-28;                // -7: combine duplicates

```

merging the assignments doesn´t save anything, but kind of improves readability:

```
for(init;input loop;$p=$d...)$d+=$d>3;
for(init;input loop;)$p=($d+=$d>3)...;

```

**breakdown**

```
for($r=[$c=A];                  // init result, init letter
    ""<$d=$argv[++$i];)         // loop through command line arguments
    $r[
        $p+=($d+=$d>3)*9-$d%3*8-28  // move cursor
    ]=++$c;                         // increment letter, plot
ksort($r);                      // sort result by index
echo join($r);                  // print result

```

# Answer
> 3 votes
## Python 2, ~~180 178~~ 176 bytes

```
def f(d,a=[[""]*26 for _ in[1]*26],x=0,y=0,j=66):
 a[0][0]="A"
 for i in d:y+=(i>4)-(i<3);x+=(`i`in'247')-(`i`in'035');a[y][x]=chr(j);j+=1
 return"".join("".join(i)for i in a)

```

# Answer
> 2 votes
## PHP, 121 bytes

```
$r[0]=chr(65);for(;($n=$argv[1][$i])!=null;)$r[$c+=[-27,-26,-25,-1,1,25,26,27][$n]]=chr($i+++66);ksort($r);echo join($r);

```

This runs in the command line with the `-r` flag and takes a char array (string) of indices as an argument.

# Answer
> 1 votes
# R, 160 bytes

```
a=scan()
e=f=26
x=matrix(0,51,51)
x[e,f]="A"
for(i in a){g=function(q)grepl(q,i)
T=T+1
f=f-g("N")+g("S")
e=e-g("W")+g("E")
x[e,f]=LETTERS[T]}
cat(x[x>0],sep="")

```

---
Tags: code-golf, alphabet
---


# Question
Title: Partial factorisations of a positive integer
A collection of positive integers `d_1 d_2 ... d_k` is a *factorisation* of a positive integer `n` if

```
d_1 * d_2 * ... * d_k = n

```

Each positive integer has a unique *prime factorisation*, but in general they also have factorisations in which some of the terms are composite. E.g.

```
12 = 6 * 2 = 4 * 3 = 3 * 2 * 2

```

Write a program, function, verb, or similar which takes as input a single positive integer and returns or prints a complete list of its distinct factorisations. The factorisations may be produced in any order, and their terms may be in any order, but no two should be permutations of each other. Factorisations may not include `1` with two exceptions: for input `n` you may give the factorisation `n*1` instead of `n`; and for input `1` you may give the factorisation `1` instead of the empty list.

You may assume that the input will be in the range of a signed 32-bit integer. If the output is as a string, there should be a clear distinction between the delimitation of numbers within a factorisation and the delimitation of the factorisations, but it is not necessary (for example) for the factors to be joined with an `*`.

Your code should be capable of handling any valid input within 10 minutes on a reasonable desktop machine.

### Examples

```
1                  [[]]
                or [[1]]
                or [[1 1]]

7                  [[7]]
                or [[7 1]]
                or [[1 7]]

12                 [[12] [6 2] [4 3] [2 3 2]]
                or variants

16                 [[2 2 2 2] [2 2 4] [2 8] [4 4] [16]]
                or variants

901800900          a list of 198091 factorisations

1338557220         a list of 246218 factorisations

```

# Answer
# Haskell, 56 bytes

```
_!1=[[]]
i!n=[j:f|j<-[i..n],mod n j<1,f<-j!div n j]
(2!)

```

`(2!)(1338557220::Int)` prints in five minutes on my laptop, when compiled with `ghc -O3`.

# Haskell, 62 bytes, but much faster

```
i!n|i*i>n=[[n]]|0<1=[i:f|mod n i<1,f<-i!div n i]++(i+1)!n
(2!)

```

`(2!)(1338557220::Int)` prints in a quarter of a second on my laptop, when compiled with `ghc -O3`.
> 12 votes

# Answer
# Pyth, 29 bytes

```
Msam+Ldgd/Hdf!%HT>S@H2tG]]Hg2

M                                def g(G, H):
                   @H2             square root of H
                  S                1-indexed range up to floor
                 >    tG           all but first G − 1 elements
            f                      filter for elements T such that:
              %HT                    H mod T
             !                       is false (0)
   m                               map for elements d:
       gd/Hd                         g(d, H/d)
    +Ld                              prepend d to each element
  a                     ]]H        append [[H]]
 s                                 concatenate
                           g2Q   print g(2, input)

```

Try it online

Runs in twenty seconds for `1338557220` on my laptop.
> 7 votes

# Answer
# Python, ~~252~~ ~~313~~ ~~312~~ ~~311~~ ~~145~~ ~~141~~ ~~137~~ ~~135~~ ~~103~~ ~~84~~ 83 bytes

This is largely based on Anders Kaseorg's Pyth answer. Any golfing suggestions welcome. Try it online!

**Edit:** 19 bytes golfed thanks to Dennis. Fixed a typo in the code and added a TIO link.

```
g=lambda n,m=2:[[n]]+[j+[d]for d in range(m,int(n**.5)+1)if n%d<1for j in g(n/d,d)]

```

**Ungolfed:**

```
def g(n, m=2):
    a = [[n]]
    s = int(n**.5) + 1
    for d in range(m, s):
        if n%d == 0:
            for j in g(n/d, d):
                a.append([d]+j)
    return a

```
> 6 votes

# Answer
## JavaScript (ES6), 83 bytes

```
f=(n,a=[],m=2,i=m)=>{for(;i*i<=n;i++)n%i<1&&f(n/i,[...a,i],i);console.log(...a,n)}

```

Only borrowed @AndersKaseorg's square root trick because it ended up saving me bytes overall. Prints `1` for an input of `1`, otherwise doesn't print `1`s.
> 4 votes

# Answer
# Ruby 1.9+, ~~87~~ ~~89~~ 87 bytes

This answer is based on Anders Kaseorg's Pyth answer. This code only works for versions after Ruby 1.9, as stabby lambdas `->` were only introduced in 1.9. Any golfing suggestions are welcome.

```
g=->n,m=2{(m..Math.sqrt(n)).select{|i|n%i<1}.flat_map{|d|g[n/d,d].map{|j|[d]+j}}+[[n]]}

```

**Ungolfed:**

```
def g(n, m=2)
  a = [[n]]
  s = (m..Math.sqrt(n))
  t = s.select{|i|n%i<1}
  t.each do |d|
    g[n/d,d].each do |j|
      a.push([d]+j)
    end
  end
  return a
end

```
> 2 votes

# Answer
# J, 52 bytes

```
[:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}:

```

Not as efficient as it could be since some factorizations may be repeated and a final pass has to be done after sorting each factorization and then de-duplicating.

Try it online! (But try to keep the input values small).

On my desktop, the timings are

```
   f =: [:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}:
   timex 'r =: f 1338557220'
3.14172
   # r
246218
   timex 'r =: f 901800900'
16.3849
   # r
198091

```

## Explanation

This method relies on generating all set partitions for the prime factors of the input integer *n*. The performance is best when *n* is square-free, otherwise duplicate factorizations will be created.

```
[:~.q:<@/:~@(*//.)"$~#@q:_&(;@]<@(,~"{~0,#\@~.)"1)}:  Input: integer n
                                                  }:  Curtail, forms an empty array
                       q:                             Prime factorization
                     #@                               Length, C = count prime factors
                         _&(                     )    Repeat that many times on x = []
                                 (            )"1       For each row
                                            ~.            Unique
                                         #\@              Enumerate starting at 1
                                       0,                 Prepend 0
                                  ,~"{~                   Append each of those to a
                                                          copy of the row
                               <@                         Box it
                            ;&]                         Set x as the raze of those boxes
                                                      These are now the restricted growth
                                                      strings of order C
    q:                                                Prime factorization
            (    )"$~                                 For each RGS
               /.                                       Partition it
             */                                         Get the product of each block
        /:~@                                            Sort it
      <@                                                Box it
[:~.                                                  Deduplicate

```
> 1 votes

---
Tags: code-golf, number-theory, combinatorics, set-partitions
---


title: Perfect powers in more than one way?

text:
# Question
Title: Perfect powers in more than one way?
# Challenge

Your task is to write a program or function which, given a positive integer \\$N\\$, finds all positive integers less than or equal to \\$N\\$ that can be expressed as a perfect power in more than one way.

# Definition

A perfect power is defined as a number \\$i\\$ found by \\$m^k\\$, where:

* \\$m\\$ and \\$i\\$ are positive integers
* \\$m \ne k\\$

# Test Cases

```
input -> output
1000 ->  16, 64, 81, 256, 512, 625, 729
56 -> 16
999 -> 16, 64, 81, 256, 512, 625, 729
81 -> 16, 64, 81
1500 -> 16, 64, 81, 256, 512, 625, 729, 1024, 1296

```

Please provided a readable, commented version as well.

# Answer
> 3 votes
## Mathematica: 103 chars

Spaces can be removed

```
Select[Flatten@
       Table[
        Solve[Log@#/Log@b == k, k, Integers] /. k -> #, {b, 2, #}] & /@ Range@#,
Length@# > 2 &][[All, 1, 1]] &

```

Usage:

```
%[81]
{16, 64, 81}

```

# Answer
> 3 votes
# Jelly, 11 meaningful bytes, language postdates challenge

```
ḊḟÆR *@þ Ḋ  F  fḊ

```

Try it online!

Here's an entirely different solution. This one's a curious hybrid of efficient and inefficient, using an efficient core algorithm in a very inefficient wrapper (so much so that it can't handle very large numbers). As before, all whitespace is meaningless.

Here's how it works.  (which appears several times) is a list of numbers from 2 to the input inclusive:

```
ḊḟÆR *@þ Ḋ  F  fḊ
ḊḟÆR                Ḋ, with all primes between 2 and the input removed
                    (i.e. all composite numbers from 4 to the input)
     *@þ Ḋ          Exponentiate all Ḋ elements with all ḊḟÆR elements
            F       Flatten the result (it had a nested structure)
               fḊ   Keep only elements in Ḋ

```

The basic observation here is that a number is a perfect power in multiple ways, only if it's a perfect power with a composite exponent (that isn't 1). We generate a list of those where the base is from 2 to the input, and the exponent is a composite number from 4 to the input; this is really slow because it generates some really big numbers, all of which are an answer to the question. Then we only keep the answers which are in range.

It'd easily be possible to modify this into a highly efficient answer, by working out what the maximum power in range was and not iterating any further, but that'd be a lot more bytes, and this is code-golf.

# Answer
> 1 votes
# Perl: 68 chars

Gets the maximum (1000) in `$N` and returns the answer in `@a`.

```
for $x ( 2..$N ) {
    $c{$x**$_}++ for 2..log($N)/log$x
}
@a = grep { $c{$_} > 1 } keys %c

```

For a whole program, I need another 18 chars:

```
$m = shift;
for $x ( 2..$m ) {
    $c{$x**$_}++ for 2..log($m)/log$x
}
print join ' ', grep { $c{$_} > 1 } keys %c

```

# Answer
> 0 votes
# Ruby - 101 chars (without whitespace)

```
f=->l{c=Hash.new{0}
2.upto(1E4){|i|2.upto(20){|j|c[i**j]+=1}}
c.map{|k,v|v>1&&k<=l&&k||p}.compact.sort}

```

Works for `1 <= limit <= 100,000,000` within 5 seconds.

Test

```
> f[10000]
[16, 64, 81, 256, 512, 625, 729, 1024, 1296, 2401, 4096, 6561, 10000]

```

# Answer
> 0 votes
# Jelly, 13 meaningful characters, language postdates challenge

```
R  µ  ọḊ *@Ḋ ċ >2  µ  Ðf

```

Try it online!

All whitespace here is insignificant. I used it to show the structure of my answer, as the question asks.

Here's how it works:

```
R  µ  ọḊ *@Ḋ ċ >2  µ  Ðf
R                     Ðf    Find all numbers n from 1 to the input, such that:
   µ               µ          (grouping marks, like {} in C)
       Ḋ   Ḋ                  Take the range from 2 to n
      ọ                       Find the number of times each divides n
         *@                   Raise the range from 2 to n to these powers
             ċ                Count the number of times n appears
               >2             and the result must be greater than 2

```

So for example, when testing n=256, we check the number of times each of the numbers from 2 to 256 divides into 256. The only numbers that divide more than once are 2 (which divides 8 times), 4 (which divides 4 times), 8 (which divides twice), and 16 (which divides twice). So when we raise the number of divisions to the powers determined there, we get:

```
2⁸, 3, 4⁴, 5, 6, 7, 8², 9, 10, 11, 12, 13, 14, 15, 16², 17, ..., 255, 256

```

This produces the original value, 256, a number of times equal to the way that 256 is a perfect power, plus one (the last element produces 256 because 256 = 256¹). So if we see 256 more than twice in the array (and we do in this case; 8² is 64 but the other "interesting" elements all produce 256), it must be a perfect power.

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


title: What time is it in unicode?

text:
# Question
Title: What time is it in unicode?
The challenge is simplistic, given an input time ***as a string*** in any one of the following formats:

`hh`, `hh:mm` or `hh:mm:ss` with `0 ≤ hh ≤ 23`, `0 ≤ mm ≤ 59` and `0 ≤ ss ≤ 59`.

Output what time it currently is using the following symbols:

```
AA  LABEL FOR CHARACTER     CODE POINT   HEXADECIMAL
==  ====================    ==========   ===========
  Clock Face 01 Oclock    128336       0x1F550
  Clock Face 02 Oclock    128337       0x1F551
  Clock Face 03 Oclock    128338       0x1F552
  Clock Face 04 Oclock    128339       0x1F553
  Clock Face 05 Oclock    128340       0x1F554
  Clock Face 06 Oclock    128341       0x1F555
  Clock Face 07 Oclock    128342       0x1F556
  Clock Face 08 Oclock    128343       0x1F557
  Clock Face 09 Oclock    128344       0x1F558
  Clock Face 10 Oclock    128345       0x1F559
  Clock Face 11 Oclock    128346       0x1F55A
  Clock Face 12 Oclock    128347       0x1F55B

```

In the following format:

```
It is currently {Clock Face 1} with {mm} minutes and {ss} seconds until {Clock Face 2}.

```

---

**Examples (Including all fringe cases):**

Case with only hours...

```
f("12") = "It is currently ."

```

---

Case with hours and minutes...

```
f("12:30") = "It is currently  with 30 minutes until ."

```

---

Case with only hours, but has minutes included as 00...

```
f("12:00") = "It is currently ."

```

---

Case with hours, minutes and seconds...

```
f("12:30:30") = "It is currently  with 29 minutes and 30 seconds until ."

```

---

Case with hours and minutes, but has seconds included as 00...

```
f("12:30:00") = "It is currently  with 30 minutes until ."

```

---

Case with hours and minutes, with less than a minute until the next hour...

```
f("12:59:59") = "It is currently  with 1 seconds until ."

```

**You do not have to change from plural to singular.**

---

Case with hours and minutes, with 1 minute to the next hour...

```
f("12:59") = "It is currently  with 1 minutes until ."

```

**You do not have to change from plural to singular.**

---

Case using military time (yes you must handle this)...

```
f("23:30:30") = "It is currently  with 29 minutes and 30 seconds until ."

```

---

Invalid cases...

```
f("PPCG") = This cannot occur, you are guaranteed a valid format by the definition of the problem.
f(66:66:66) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.
f(24:60:60) = This cannot occur, you are guaranteed valid numbers by the definition of the problem.

```

You do not have to conform to any style of output for invalid cases, errors are fine.

---

Overall the challenge is rather simplistic, but seemed to be dynamic enough to be fun in my opinion. The shortest code here is the winner as there isn't much variable aspect to the code other than length.

# Answer
> 3 votes
# JavaScript (ES6), 201

```
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):''))

```

*Less golfed*

```
t=>(
  T=h=>String.fromCodePoint(128336+h%12),
  [h,m,s]=t.match(/\d+/g),
  'It is currently '+T(h-=~10)
   +(
      // if seconds is not 0, increment m else just convert to number
      // have to use '- -' to force conversion to number
     (m -= - !!-s)
-s?++m:m)
      ? ` with ${60-m ? 60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h)
      : ''
    )
)

```

**Test**

```
F=
t=>(T=h=>String.fromCodePoint(128336+h%12),[h,m,s]=t.match(/\d+/g),'It is currently '+T(h-=~10)+((m-=-!!-s)?` with ${60-m?60-m+' minutes'+(-s?' and ':''):''}${-s?60-s+' seconds':''} until `+T(-~h):'')
)

var tid=0

function getTime(t)
{
  var a=t.match(/\d+/g)
  if (a) {
    var [h,m,s]=a
    h|=0, s|=0, m|=0
    if(h>=0 & h<24 & m>=0 & m<60 & s>=0 & s<60)
      return [h,m,s]
  }
  return null
}

function update()
{
  clearTimeout(tid)
  var t=I.value, a=getTime(t)
  if (a) {
    O.textContent = F(t)
    tid = setTimeout(again,5000)
  }
  else {
    O.textContent = 'invalid ' + t
  }
}
function again()
{
  var t=I.value, a=getTime(t)
  if (a) {
    var [h,m,s]=a
    ++s>59?(s=0,++m>59?(m=0,++h):0):0
    h%=24
    s<10?s='0'+s:0
    m<10?m='0'+m:0
    t = h+(-m-s?':'+m+(-s?':'+s:''):'')
    I.value = t
    O.textContent=F(t)
    tid = setTimeout(again, 1000)
  }
}

update()
```

```
#O { font-size:16px }
```

```
Time <input id=I value='12' oninput='update()' onkeydown='update()'>
(modify current time as you wish - but use valid values)
<pre id=O></pre>
```

# Answer
> 3 votes
# Befunge, ~~256~~ 250 bytes

```
>&~85+`v
8~-&"<"_00v`+5
0v%\-&"<<"_
v>:00p!!-"<"%10p65++:66+%0" yltnerruc si tI">:#,_$"Hu 5x"2*,3*,+,2*+,10g00g+
_".",@,".",+*2,+,*3,*2"x5 uH"%+66+1$_,#!>#:<v0
" litnu  htiw ",,,,,,10g:>#v_$"sdnoces"00g.^>
_>,,,,,,,>" dna ">,,,,,00^ >."setunim"00g!#^

```

Try it online!

The results are encoded as utf-8, since that works best with TIO, but if you're testing locally, you may need to adjust your system's default code page to see the clock faces correctly. Otherwise just redirect the output to a file and open that in a utf-8 compatible editor.

**Explanation**

The first three lines read the hours minutes and seconds from stdin, checking for EOF or a linefeed after each value, and substituting zeros for the componenents that are missing from the input. On line four, we adjust the minute value if the seconds are non-zero, convert the hour value into the range 0 to 11 (to match the appropriate unicode character for each hour), and write out the initial part of the output, including the the first clock face.

It's at this point that we need to follow different branches depending on what components are non-zero. The first test, at the start of line five, just checks if both minutes and seconds are zero. If so, we write out a final `.` and exit. Otherwise lines six and seven deal with the remaining cases - writing out the appropriate text and values, before the paths all combine again on line five to write out the final clock face (executing right to left).

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

```
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minutes`:``}${+s&&m?` and `:``}${+s?60-s+` seconds`:``} until `+c(-~h):``}.`

```

226 bytes if you take plurals into account:

```
f=
(i,[h,m,s]=i.split`:`,c=n=>String.fromCodePoint(128336+(n+11)%12))=>`It is currently ${c(+h)}${m|s?` with ${(m=59+!+s-m)?m+` minute`+(m-1?`s`:``):``}${+s&&m?` and `:``}${+s?60-s+` second`+(59-s?`s`:``):``} until `+c(-~h):``}.`
```

```
<input oninput=o.textContent=f(this.value)><div id=o>
```

# Answer
> 1 votes
# PowerShell, ~~250~~ 243 bytes

```
$h,$m,$s=$args-split':'
$f={[char]::ConvertFromUtf32(128336+(11+$args[0])%12)}
$u=(60-$s)%60
$v=(59-$m+!$u)%60
"It is currently $(&$f $h;"with $(("$v minutes"|?{$v}),("$u seconds"|?{$u})-match'.'-join' and ') until $(&$f (1+$h))"|?{$u-or$v})."

```

Try it online!

# Answer
> 1 votes
## C, 241 bytes

Writes UTF-8 to stdout.

```
#define p printf(
c(v,h){p"%s \xf0\x9f\x95%c",v,144+h%12);}f(t){int h=0,m=0,s=0;sscanf(t,"%d:%d:%d",&h,&m,&s);m=(59-m+!s)%60;c("It is currently",h-1);m&&p" with %d minutes",m);s&&p" %s %d seconds",m?"and":"with",60-s);m|s&&c(" to",h);p".");}

```

Try it online!

Code with whitespace:

```
#define p printf(

c(v, h) {
    p"%s \xf0\x9f\x95%c", v, 144 + h % 12);
}

f(t) {
    int h = 0, m = 0, s = 0;

    sscanf(t, "%d:%d:%d", &h, &m, &s);
    c("It is currently", h - 1);
    m = (59 - m + !s) % 60;
    m && p" with %d minutes", m);
    s && p" %s %d seconds", m ? "and" : "with", 60 - s);
    m | s && c(" to", h);
    p".");
}

```

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


title: Your very own "for" instruction, redux

text:
# Question
Title: Your very own "for" instruction, redux
Inspired by Sygmei's question, I'm interested in finding out what languages can "do this properly".

Your task is to write a "for loop" function / macro / instruction. The arguments should be:

* an initializer
* a test
* an increment
* a body

All of these are "pieces of code" and should be able to access variables in the context of the call. The body should be able to include multiple statements.

The aim is to have the fewest lexical tokens excluding comments, except that `#define` and friends (using a dumb preprocessor) are worth 50, and `eval` and friends (taking a string argument) are worth 100. Feel free to make your code readable with comments, whitespace and meaningful names.

You should include a "test harness" which is not counted towards length.

The C version definitely won't win:

```
// the do {...} while (0) idiom enables a code block to be a single C statement, so it can safely be followed by a semicolon
#define my_for(init, test, inc, body) do {  \
    init; \
    while (test) { \
        body; \
        inc; \
    } \
} while (0)

// test harness:
#include <stdio.h>

main()
{
    int i, total;
    my_for((i=1, total=0), i<=3, ++i, {printf("%d\n", i); total=total+i;});
    printf("total: %d\n", total);
}

```

Edit to add: the meaning of "lexical token" depends on your language. Here's how the scoring breaks down for my C version:

`//`\[...\]: 0
`#define`: 1 occurrence, 50 points
`my_for`: 1
`(`: 3
`init`: 2
`,`: 3
`test`: 2
`inc`: 2
`body`: 2
`)`: 3
`do`: 1
`{`: 2
`\`: 6
`;`: 3
`while`: 2
`}`: 2
`0`: 1

*TOTAL*: 85

# Answer
## Python, ~~11~~ 26 tokens:

```
def f(n, t, i, l):
    n()
    while t():
        l()
        i()

```

This is my first time doing , so forgive me if I got the token counting wrong.

**EDIT**: Hugh Allen informed me that I got the token counting wrong.
> 2 votes

# Answer
# Perl 6, 24 tokens

```
sub my-for (&init, &test, &inc, &body) {
    init;
    while (test) { body; inc }
}

```

Tokens:

```
while   1   keyword
sub     1   keyword
my-for  1   function name (declaration)
&init   1   function parameter (declaration)
&test   1   function parameter (declaration)
&inc    1   function parameter (declaration)
&body   1   function parameter (declaration)
init    1   function name (implicit call)
test    1   function name (implicit call)
inc     1   function name (implicit call)
body    1   function name (implicit call)
,       3   parameter list separator
;       2   statement separator
{       2   block opener
}       2   block closer
(       2   parameter list opener
)       2   parameter list closer

```

Test:

```
my ($i, $total);
my-for {$i=1; $total=0}, {$i <= 3}, {++$i}, {
    say $i;
    $total = $total + $i;
}
say "total: $total";

```
> 1 votes

# Answer
# tcl, could I say 0 due to point 1.?

If the question was "how many ways your language allow you to do it", tcl would certainly score a good amount.

1. for

The language's normal `for` works this way; it should me noted that tcl has no keywords, so `for` works exactly like a function *(side note: its behaviour can even be redefined!)*. Then, there is no need to implement it:

```
for {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```
2. proc

Implement a function, strictly according to the question.

2.1. uplevel

The `uplevel 1` will execute its contents 1 level up in the call stack, to allow there the access to the variables of the `for` input; otherwise we could not access `$total`, because it would be not defined.

```
proc F {s t i b} {uplevel 1 [list for $s $t $i $b]}
F {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```

2.2. tailcall

From `tailcall` documentation: "The tailcall command replaces the currently executing procedure, lambda application, or method with another command."

```
proc P args {tailcall for {*}$args}
P {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```
3. interp alias

You can say to one of the interpreters currently existing on interpreters tree that a command has an alias. I didn't create any interpreter, so I am interested on the tree's root interpreter, which path is an empty string, represented by `{}`. The following line means: "Create the alias `R` on the *root* interpreter, which will re-route calls to it to `for` on the *root* interpreter.

```
interp alias {} R {} for
R {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```
4. set

You can define a var that will have the same value has `for` command:

```
set S for
$S {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```
5. rename

You can change the name of the function. Note: From now on, you can not call `for` directly again! Now you must always call `f`, until you rename it back!

```
rename for f
f {set i 0;set total 1} {$i<=3} {incr i} {puts $i; incr total $i}
puts total:\ $total

```

demo
> 0 votes

---
Tags: atomic-code-golf
---


title: Hello World socket server

text:
# Question
Title: Hello World socket server
Write the shortest program that answers "Hello, World" to a network connection.

Conditions:

* Program shall listen on port 12345
* When a client connects, program shall write "Hello, World" to the newly opened socket connection and then close the connection
* Program shall accept connections in a loop, i.e. handle any number of connects
* Program does not need to handle parallel connections

Test:

```
prompt> telnet localhost 12345
Hello, World
prompt>

```

# Answer
## Bash (34)

```
nc -l 12345 <<<Hello,\ World;. $0

```
> 6 votes

# Answer
# Java, 268 Bytes

```
import java.io.*;import java.net.*;
class S{public static void main(String[]args)throws Exception{ServerSocket s=new ServerSocket(12345);while(1>0){Socket t=s.accept();PrintWriter u=new PrintWriter(t.getOutputStream());u.println("Hello World!");u.flush();t.close();}}}

```

Ungolfed:

```
import java.io.*;import java.net.*;
class S{
    public static void main(String[]args)throws Exception{
        ServerSocket s = new ServerSocket(12345);
        while(true) {
            Socket t = s.accept();
            PrintWriter u = new PrintWriter(t.getOutputStream()) ;
            u.println("Hello World!");
            u.flush();
            t.close();
        }
        s.close();
    }
}

```
> 3 votes

# Answer
## Tcl, 78 chars

```
socket -server r 12345;proc r {s a b} {puts $s Hello,\ World;close $s};vwait r

```

the `vwait r` enters the event loop (not necessary with Tk) until the variable `r` is set. Usually you use the variable `forever`.
And the `Hello,\ World` is the same as `{Hello, World}` or `"Hello, World"`
> 2 votes

# Answer
# Go, 133 bytes

```
package main
import(n"net")
func main(){l,_:=n.Listen("tcp",":12345")
for{c,_:=l.Accept()
c.Write([]byte("Hello, World"))
c.Close()}}

```
> 2 votes

# Answer
# LiveScript (node.js), 73 bytes

```
(require(\net)createServer ->it.write 'Hello, World';it.end!)listen 12345

```
> 2 votes

# Answer
# C# 220

```
using System.Text;namespace System.Net.Sockets{class P{static void Main(){var s=new TcpListener(IPAddress.Any,12345);s.Start();while(true){using(var c=s.AcceptSocket()){c.Send(Encoding.UTF8.GetBytes("Hello World"));}}}}}

```

Ungolfed:

```
using System.Text;
namespace System.Net.Sockets
{
    class P
    {
        static void Main()
        {
            var s = new TcpListener(IPAddress.Any, 12345);
            s.Start();
            while (true)
            {
                using (var c = s.AcceptSocket())
                {
                    c.Send(Encoding.UTF8.GetBytes("Hello World"));
                }
            }
        }
    }
}

```

Pretty straightforward. I could have saved 14 characters by removing `IPAddress.Any,` but that would rely on using deprecated API ...
> 2 votes

# Answer
# Clojure, ~~153~~ 148 bytes

-5 byte using macros. See comments.

```
(let[s(java.net.ServerSocket. 12345)](while 1(with-open[c(.accept s)](doto(java.io.PrintWriter.(.getOutputStream c))(.write"Hello, World").flush))))

```

Full program that listens in a loop for incoming connections, and outputs as required. The Java-interop is killer here. I don't need the same libraries enough to justify an import though.

Pregolfed:

```
(defn server []
  (let [ss (java.net.ServerSocket. 12345)]
    (while 1
      ; Auto closes the client
      (with-open [c (.accept ss)]
         ; Passes the PrintWriter as the first argument to each function
         (doto (java.io.PrintWriter. (.getOutputStream c))
           (.write "Hello, World\n")
           ; Parentheses are optional if the function only takes 1 argument
           ; Ugly, but shorter
           .flush)))))

```
> 2 votes

# Answer
# Groovy, 119 bytes

```
{s=new java.net.ServerSocket(12345);while(1){(u=(t=s.accept()).getOutputStream())<<"Hello, World";u.flush();t.close()}}

```

Port of my java answer.
> 2 votes

# Answer
# Racket, 111 bytes

```
(do([l(tcp-listen 12345)])(#f)(let-values([(i o)(tcp-accept l)])(display"Hello, World"o)(close-output-port o)))

```

It always surprises me when the `do` form is shorter than explicit recursion. I'm not entirely certain if I'm required to close the input port. Please comment if you think I need to.

## Ungolfed

```
(do ([l (tcp-listen 12345)]) (#f)
  (let-values ([(i o) (tcp-accept l)])
    (display "Hello, World" o)
    (close-output-port o)))

```
> 2 votes

# Answer
# Python, 103

```
import socket
s=socket.socket()
s.bind(('',12345))
s.listen(1)
s.accept()[0].sendall(b'Hello, World')

```
> 2 votes

# Answer
# Perl, 118 bytes

```
$s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo}

```

Example:

```
$ perl -MIO::Socket -e '$s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo}'

$ telnet localhost 12345
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello WorldConnection closed by foreign host.
$

```
> 1 votes

# Answer
# Wolfram (102)

`#[[2]]` contains `OutputStream` of the incoming socket

```
<<SocketLink`;
CreateAsynchronousServer[CreateServerSocket@12345,(#[[2]]~Write~"Hello world";Close/@#)&]

```
> 1 votes

# Answer
# Ruby, 83 bytes

```
require'socket';s=TCPServer.new 12345;loop{t=s.accept;t<<"Hello, World\n";t.close}

```
> 0 votes

---
Tags: code-golf, hello-world
---


title: The Tax Historian

text:
# Question
Title: The Tax Historian
# Introduction

There is a tax collector that has some trouble managing the taxes of his kingdom: the historical records have burnt down in a great fire.

He wants to find out how many possible pasts there could be in terms of where the current money was inherited from. Luckily, his kingdom is very simple.

The kingdom can be modelled by a 2D boolean matrix, where `l` represents someone who has inherited money, and `O` represents someone who has not. For example:

```
l O l l

O O O l

l O l O

O O O l

```

(It will always be a rectangle)

In the next generation, the kingdom is smaller (The wolves are strong!).

The next generation would look like this, superimposed on the previous generation (`x` is a placeholder for a descendent in the next generation)

```
l O l l
 x x x
O O O l
 x x x
l O l O
 x x x
O O O l

```

A descendent will look at the ancestors that are directly around them (So the top-left `x` will see {`l`, `O`, `O`, `O`}, called an Unaligned rectangular neighbourhood)

If only one ancestor has inherited money, the descendant will inherit money from them. If more than one ancestor has inherited money, they will squabble and the descendant will end up not inheriting money. If no one has inherited money, the descendant will not inherit any money.

(More than one descendant can inherit from one ancestor)

So, the next generation would look like:

```

 l l O

 l l O

 l l O

```

# Challenge

## Input

The current state of the generation, as an array of arrays of any two distinct values, where the inner arrays are all of the same length.

E.g., for the example above, it could be:

```
[
  [True, True, False],
  [True, True, False],
  [True, True, False]
]

```

## Output

An integer representing the number of unique previous generations where the next generation is the input.

You can assume that the answer will always be less than 2^30 - 1. (or 1073741823).

The previous generation would be called a "preimage" and this challenge would be to count the preimages.

## Scoring

This is a challenge, so each submission will be tested on my computer, and the submission that takes the least time will be the winner.

# Example Input and Output

(Where `1` is a descendent who inherited money, and `0` is a descendent who did not inherit money)

## Input:

```
[[1, 0, 1],
 [0, 1, 0],
 [1, 0, 1]]

```

### Output:

```
4

```

## Input:

```
[[1, 0, 1, 0, 0, 1, 1, 1],
 [1, 0, 1, 0, 0, 0, 1, 0],
 [1, 1, 1, 0, 0, 0, 1, 0],
 [1, 0, 1, 0, 0, 0, 1, 0],
 [1, 0, 1, 0, 0, 1, 1, 1]]

```

### Output:

```
254

```

## Input:

```
[[1, 1, 0, 1, 0, 1, 0, 1, 1, 0],
 [1, 1, 0, 0, 0, 0, 1, 1, 1, 0],
 [1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
 [0, 1, 0, 0, 0, 0, 1, 1, 0, 0]]

```

### Output:

```
11567

```

# Answer
> 4 votes
## C++ using the BuDDy library

This seemed like a nice excuse to play with binary decision diagrams. The kingdom is converted into a big boolean formula where we have to count the number of ways in which it can be satisfied. That can (sometimes) be done more efficiently than it sounds.

The kingdom must be given as a program constant as a flat array and explicitely given dimensions. (Nice input is left as an execise for the reader :-)

Here is the embarrassingly simple code:

```
#include <iostream>
#include <bdd.h>

// describe the kingdom here:

constexpr int ROWS = 4;
constexpr int COLS = 10;

constexpr int a[] = {
   1, 1, 0, 1, 0, 1, 0, 1, 1, 0,
   1, 1, 0, 0, 0, 0, 1, 1, 1, 0,
   1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
   0, 1, 0, 0, 0, 0, 1, 1, 0, 0,
};

// end of description

// check dimensions
static_assert(ROWS*COLS*sizeof(int)==sizeof(a),
          "ROWS*COLS must be the number of entries of a");

// dimensions of previous generation
constexpr int R1 = ROWS+1;
constexpr int C1 = COLS+1;

// condition that exactly one is true
bdd one(bdd a, bdd b, bdd c, bdd d){
  bdd q = a & !b & !c & !d;
  q |= !a & b & !c & !d;
  q |= !a & !b & c & !d;
  q |= !a & !b & !c & d;
  return q;
}

int main()
{
  bdd_init(1000000, 10000); // tuneable, but not too important
  bdd_setvarnum(R1*C1);
  bdd q { bddtrue };
  for(int j=COLS-1; j>=0; j--) // handle high vars first
    for (int i=ROWS-1; i>=0; i--){
      int x=i+R1*j;
      bdd p=one(bdd_ithvar(x), bdd_ithvar(x+1),
                bdd_ithvar(x+R1), bdd_ithvar(x+R1+1));
      if (!a[COLS*i+j])
        p = !p;
      q &= p;
    }
  std::cout << "There are " << bdd_satcount(q) << " preimages\n";
  bdd_done();
}

```

To compile with debian 8 (jessie), install `libbdd-dev` and do `g++ -std=c++11 -o hist hist.cpp -lbdd`. (Optimizing options make almost no difference because the real work is done in the library.)

Big examples can lead to messages about garbage collection. They could be suppressed, but I prefer to see them.

`bdd_satcount` returns a `double`, but that is good enough for the expected range of results. The same counting technique is possible with exact (big) integers.

The code is optimized for `ROWS<COLS`. If you have a lot more rows than columns, it might be a good idea to transpose the matrix.

# Answer
> 3 votes
# Python 2.7

This is just a naïve first attempt. It's not particularly fast, but it is correct.

The first observation is that each cell is dependent on exactly four cells in the previous generation. We can represent those four cells as a 4-bit number (0-15). According to the rules, if exactly one neighboring cell in the previous generation is `1`, then a given cell in the current generation will be `1`, otherwise, it will be `0`. Those correspond to the powers of two, namely, `[1, 2, 4, 8]`. When the four ancestors are represented as a 4-bit number, any other number will result in a `0` in the current generation. With this information, upon seeing a cell in the current generation, we can narrow down the possibilities of the neighborhood in the previous generation to one of four or one of twelve possibilities respectively.

I've chosen to represent the neighborhood as follows:

```
32
10

```

where 0 is the least-significant bit, and so on.

The second observation is that for two adjacent cells in the current generation, the two neighborhoods from the previous generation overlap:

```
32  32
10  10

```

or:

```
32
10

32
10

```

In the horizontal case, the `2` from the left neighborhood overlaps with the `3` from the right neighborhood, and similarly with the `0` on the left and the `1` on the right. In the vertical case, the `1` from the top neighborhood overlaps with the `3` from the bottom neighborhood, and similarly with the `0` on the top and the `2` on the bottom.

This overlap means that we can narrow down the possibilities for yet-unchosen neighborhoods based on what we've already chosen. The code works it's way from left to right, top to bottom, in a recursive depth-first search for possible preimages. The following diagram indicates which previous neighborhoods we have to consider when looking at the possible neighborhoods of a current cell:

```
f = free choice
h = only have to look at the neighborhood to the left
v = only have to look at the neighborhood to the top
b = have to look at both left and top neighborhoods

[f, h, h, h, h],
[v, b, b, b, b],
[v, b, b, b, b],
[v, b, b, b, b]

```

Here's the code:

```
def good_horizontal(left, right):
    if (left & 4) >> 2 != (right & 8) >> 3:
        return False
    if left & 1 != (right & 2) >> 1:
        return False
    return True

def good_vertical(bottom, top):
    if (bottom & 8) >> 3 != (top & 2) >> 1:
        return False
    if (bottom & 4) >> 2 != (top & 1):
        return False
    return True

ones = [1, 2, 4, 8]
zeros = [0, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]
h = {}
v = {}

for i in range(16):
    h[i] = [j for j in range(16) if good_horizontal(i, j)]
    v[i] = [j for j in range(16) if good_vertical(i, j)]

def solve(arr):
    height = len(arr)
    width = len(arr[0])

    if height == 1 and width == 1:
        if arr[0][0] == 1:
            return 4
        else:
            return 12
    return solve_helper(arr)

def solve_helper(arr, i=0, j=0, partial=None):
    height = len(arr)
    width = len(arr[0])

    if arr[i][j] == 1:
        poss = ones
    else:
        poss = zeros

    if i == height - 1 and j == width - 1:  # We made it to the end of this chain
        if height == 1:
            return sum([1 for p in poss if p in h[partial[-1][-1]]])
        else:
            return sum([1 for p in poss if partial[-2][-1] in v[p] and p in h[partial[-1][-1]]])

    if j == width - 1:
        new_i, new_j = i + 1, 0
    else:
        new_i, new_j = i, j + 1

    if i == 0:
        if j == 0:
            # first call
            return sum([solve_helper(arr, new_i, new_j, [[p]]) for p in poss])
        # still in the first row
        return sum([solve_helper(arr, new_i, new_j, [partial[0] + [p]]) for p in poss if p in h[partial[0][-1]]])
    if j == 0:  # starting a new row
        return sum([solve_helper(arr, new_i, new_j, [r for r in partial + [[p]]]) for p in poss if partial[i - 1][0] in v[p]])
    return sum([solve_helper(arr, new_i, new_j, [r for r in partial[:-1] + ([partial[-1] + [p]])]) for p in poss if p in h[partial[i][-1]] and partial[i - 1][j] in v[p]])

```

To run it:

```
test3 = [
    [1, 1, 0, 1, 0, 1, 0, 1, 1, 0],
    [1, 1, 0, 0, 0, 0, 1, 1, 1, 0],
    [1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 1, 0, 0, 0, 0, 1, 1, 0, 0]
]

expected3 = 11567

assert(solve(test3) == expected3)

```

---
Tags: fastest-code, cellular-automata
---


title: Mondrian Puzzle Sequence

text:
# Question
Title: Mondrian Puzzle Sequence
Partition an `n X n` square into multiple non-congruent integer-sided rectangles. `a(n)` is the least possible difference between the largest and smallest area.

```
 ___________
| |S|_______|
| | |   L   |
| |_|_______|
| |     |   |
| |_____|___|
|_|_________| (fig. I)

```

The largest rectangle (`L`) has an area of `2 * 4 = 8`, and the smallest rectangle (`S`) has an area of `1 * 3 = 3`. Therefore, the difference is `8 - 3 = 5`.

**Given an integer `n>2`, output the least possible difference.**

All known values of the sequence at the time of posting:

```
2, 4, 4, 5, 5, 6, 6, 8, 6, 7, 8, 6, 8, 8, 8, 8, 8, 9, 9, 9, 8, 9, 10, 9, 10, 9, 9, 11, 11, 10, 12, 12, 11, 12, 11, 10, 11, 12, 13, 12, 12, 12

```

So `a(3)=2`, `a(4)=4`, ...

**OEIS A276523**

Related \- this related challenge allows non-optimal solutions, has time constraints, and is not code-golf.

*For more information, watch this video by Numberphile*

# Answer
# CJam, 178

```
ri_1a*a*L{_:+1&{_[3{_\zW%}*]{_z}%:e<_@={:A0=_1#:X0<{;A1>j}{X>0+0#AzX=0+0#,\,m*1ff+{[_$\~1a*0aX*\+a*A\..-_])s'-&{;}&}%{~j\:X;{Xa&!},Xaf+:$~}%_&}?}{j}?}{;La}?}j{,(},{::*$)\0=-}%:e<

```

Try it online. It's veeery slow though, I wouldn't recommend going above 6.

To verify that it's really doing the work, you can check this slightly modified program that prints all the possible partitions (each partition is shown as an array of rectangle dimension pairs).
> 4 votes

# Answer
# Befunge, 708 bytes

```
p&>:10p1-:>20p10g:20g\`v`\g02:-1\p00+1g<>g-#v_10g:*30p"~":40p50p060p070p$>^
1#+\#1<\1_^# !`0::-1$  _:00g3p\:00g2p00^^00:>#:

>>:2-#v_$30p50p60p70g1-70p
^<<<<<:#<<<<<<$$$_v#:!g87g78g79$  _v#!\-1:g88$<_ 98p87g97g*00 v:+!\`*84g++7<
^>$1-:77p1g:2g\3g1>78p97p87p10g97g->88p10g87g-0^!\-1:g89_v#-!\_$1-:v>/88g+7^
^|!-3$<   >\87g/88g+77++p:#v_$
^>:5->v   ^+g89%g78:\g77:-1<>98g88g48*577g387g97g98g88v ^>77g87g97v:^g78\+g<
^ v-4:_$77p88p98p:97p\:87p*^^g79g7>#8\#$_40pv5+"A"g77g< ^14g88g89g<>:87g%98^
^v_$88p98p97p87p:77p60g50g-:40g\`#^_$$>>>>>>>
 >#4!_::80p2g\3g*:90p30g`!v>>>#@>#.>#g^#0
^v:g06p03:-g09\2:g03g05g06_^^_7#<0#<g#<3#<1#<<`g04_$00g1->:#-8#10#\g#1`#:_>$
^>90g\-:0`*+:60p50g:90g-:0`*-:50p-80g70g:1+70p1p\!^

```

Try it online!

This is obviously not going to win any awards for size, but it's actually reasonably fast considering it's a basic bruce force implementation in an esoteric language. On the Befunge reference interpreter it can handle up to n=6 in a couple of seconds. With a compiler it can handle up to n=8 before it starts getting sluggish; n=9 takes a couple of minutes and n=10 is close on 2 hours.

In theory the upper limit is n=11 before we run out of memory (i.e. there's not enough space left in the playfield to fit a larger square). However, at that point, the time taken to calculate the optimal solution is probably longer than anyone would be willing to wait, even when compiled.

The best way to see how the algorithm works is by running it in one of the Befunge "visual debuggers". That way you can watch as it attempts to fit the various rectangle sizes into the available space. If you want to "fast forward" to the point where it has a good match, you can put a breakpoint on the `4` in the sequence `$_40p` near the middle of the tenth line (9 if zero-based). The value at the top of the stack at that point is the current area difference.

Below is an animation showing the first few frames of this process for n=5:

Each distinct rectangle is represented by a different letter of the alphabet. However, note that the final rectangle is never written out, so that section of the square will just be blank.

I've also written a debug version of the code that outputs the current layout each time it finds a new best match (Try it online!). For the smaller sizes, the first match is often the optimal solution, but once you get past n=6 you'll likely get to see several valid but non-optimal layouts before it settles on the final solution.

The best layout found for n=10 looks like this:

```
H F F F A A A C C I
H F F F A A A C C I
H J G G A A A C C I
H J G G A A A C C I
H J D D D D D C C I
H J D D D D D C C I
H J K K K K K K K I
H J B B B E E E E I
H J B B B E E E E I
H J B B B L L L L L

12 - 4 = 8

```
> 6 votes

---
Tags: code-golf, sequence, tiling
---


title: Recognize ASCII art numbers

text:
# Question
Title: Recognize ASCII art numbers
### Challenge

Recognize ASCII art numbers. To make things interesting, three random points in the image might be flipped. For example:

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

   **
  **
 **

```

### Input

A 7x7 ASCII art number generated by the below Python script.

### Output

A digit.

### Testing script

Here's a Python script (2.6+) to generate the test cases:

```
import random

digits = '''\
  ***
 ** **
**   **
**   **
**   **
 ** **
  ***

   *
 ***
   *
   *
   *
   *
 *****

  ***
 *  **
     *
    **
   **
  **
 ******

  ***
 *  **
     *
  ***
     *
 *  **
  ***

   **
  ***
 * **
*  **
******
   **
   **

 *****
 **
 ****
     *
     *
 *   *
  ***

  ****
 **
 *****
 *   *
 **  **
 **  *
  ****

 *****
    **
    **
   **
   **
  **
 **

  ****
 **  **
 **  **
  ****
 **  **
 **  **
  ****

  ***
 ** **
**   **
 **  *
  ****
    **
 ****  '''.split('\n\n')

def speckle(image, num_speckles):
    grid = [list(row) for row in image.split('\n')]

    for i in range(num_speckles):
        row = random.choice(grid)
        row[random.randint(0, 6)] = random.choice([' ', '*'])

    return '\n'.join([''.join(row) for row in grid])

digit = random.choice(digits)

print(speckle(digit, 3))

```

# Answer
## APL (~~87~~ 85)

```
1-⍨⊃⍒(,↑{7↑'*'=⍞}¨⍳7)∘(+.=)¨{49↑,(16/2)⊤⎕UCS⍵}¨↓10 3⍴'嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢'

```

Explanation:

Each possible ASCII number is encoded in 48 bits. (The 49th bit is always zero anyway). The string `嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢` has three characters per ASCII number, each of which encodes 16 bits.

* `↓10 3⍴`: split the data string into 10 3-char groups, each of which encodes a number.
* `{`...: for each of the groups:
    + `(16/2)⊤⎕UCS⍵`: get the first 16 bits of each of the three characters
    + `,`: concatenate the bit arrays into one array
    + `49↑`: take the first 49 elements. There are only 48, so this is equivalent to adding a `0` at the end.
* `,↑{7↑'*'=⍞}¨⍳7`: read 7 lines of 7 characters from the keyboard, make a bit array for each line where `1` means the character was a `*`, and join them together.
* `(+.=)¨`: for each possible digit, calculate how much bits the input had in common with the digit.
* : get the indices for a downwards sort of that list, so that the first item in the result is the index of the largest number in the previous list.
* : take the first item, which is the index of the digit
* `1-⍨`: subtract one, because APL indices are 1-based.
> 9 votes

# Answer
## Python

I'm sure there will be OCR solutions, but the probability of mine being accurate is much higher.

```
import difflib as x;r=range;s='2***3**1**1**3****3****3**1**1**3***23*4***6*6*6*6*4*****12***3*2**6*5**4**4**4******2***3*2**6*3***7*2*2**3***23**4***3*1**2*2**2******4**5**21*****2**5****7*6*2*3*3***22****2**5*****2*3*2**2**1**2*3****11*****5**5**4**5**4**4**42****2**2**1**2**2****2**2**1**2**2****12***3**1**1**3**1**2*3****5**2****2'
for c in r(8):s=s.replace(str(c),' '*c)
s=map(''.join,zip(*[iter(s)]*7));a=[raw_input("") for i in r(7)];l=[[x.SequenceMatcher('','|'.join(a),'|'.join(s[i*7:(i+1)*7])).ratio()] for i in r(10)];print l.index(max(l))

```

Input one line of text at a time.

Not sure of a better way to deal with the asterisks without increasing the character count.
> 5 votes

# Answer
# JavaScript (ES6), 89

```
f=n=>(a=1,[a=(a+a^c.charCodeAt())%35 for(c of n)],[4,25,5,16,0,11,32,13,10,1].indexOf(a))

```

**Usage:**

```
> f("  ***  \n *  ** \n     * \n    ** \n   **  \n  **   \n ******")
2

```

**Un-golfed version:**

```
f = (n) => (
  // Initialize the digit's hash.
  a=1,
  // Hash the digit.
  // 35 is used because the resulting hash is unique for the first ten digits.
  // Moreover, it generates 4 1-digit hashes.
  [a = (a + a ^ c.charCodeAt()) % 35 for(c of n)],
  // Compare the hash to pre-computed digit hash.
  // The matching hash index is the digit.
  [4,25,5,16,0,11,32,13,10,1].indexOf(a)
)

```
> 4 votes

# Answer
# Bash+ImageMagick+tesseract, 316 chars

Here's a stab at an OCR solution. Its not very accurate though, even when telling tesseract that we have just one char and it is a digit. Moderately golfed, but still somewhat readable:

```
w=0
c()((w=${#2}>w?${#2}:w))
mapfile -c1 -Cc -t l
h=${#l[@]}
{
echo "# ImageMagick pixel enumeration: $w,$h,1,gray"
for y in ${!l[@]};{
for((x=0;x<w;x++));{
[ "${l[$y]:$x:1}" != " " ]
echo "$x,$y: ($?,$?,$?)"
}
}
}|convert txt:- i.png
tesseract i.png o -psm 10 <(echo "tessedit_char_whitelist 0123456789")
cat o.txt

```

The script takes input from stdin, so we can pipe from the test script.

Note I have put `tee >( cat 1>&2 )` in the pipeline just so we can see what the test script actually generated.

### Example output (This was a pretty good run with only 1 incorrect char out of 6):

```
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
  ***
 ** **
*    **
 **  *
  ****
    ***
 ****
Tesseract Open Source OCR Engine v3.02 with Leptonica
9

$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
   *
 ***  *
   *
   *
   *
   *
 *****
Tesseract Open Source OCR Engine v3.02 with Leptonica
1

$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
  ***
 ** **
**   **
**   **
**   **
  * **
  ***
Tesseract Open Source OCR Engine v3.02 with Leptonica
0

$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
 *****
 **
 ****
     *
     *
 **  *
  ***
Tesseract Open Source OCR Engine v3.02 with Leptonica
5

$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
  ****
 **
 *****
 *   *
*** ***
 **  **
  ****
Tesseract Open Source OCR Engine v3.02 with Leptonica
5

$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
  ***
 *  **
     *
    **
   ***
  **
 ******
Tesseract Open Source OCR Engine v3.02 with Leptonica
2

$

```
> 3 votes

# Answer
## LÖVE2D, 560 Bytes

```
t=...;g=love.graphics g.setNewFont(124)g.setBackgroundColor(255,255,255)A=g.newCanvas()B=g.newCanvas()x=1 y=1 g.setColor(255,255,255)g.setCanvas(B)g.clear(0,0,0)for i=1,#t do x=x+1 if t:sub(i,i)=="\n"then x=1 y=y+1 end if t:sub(i,i)=="*"then g.rectangle("fill",x*16,y*16,16,16)end end u=B:newImageData()g.setCanvas(A)S={}for i=0,9 do g.clear(0,0,0,0)g.print(i,48,0)r=A:newImageData()s={i=i,s=0}for x=0,16*8 do for y=0,16*8 do a=u:getPixel(x,y)b=r:getPixel(x,y)s.s=s.s+math.abs(a-b)end end S[i+1]=s end table.sort(S,function(a,b)return a.s<b.s end)print(S[1].i)

```

First, draws a blocky representation of the input text, then, for each number 0 - 9, overlays a number, checks how many similar pixels there are, and prints the number which got the closest. Very basic OCR. It matches all the Test Cases, and performs reasonably well with mutations.

Call with:

```
love.exe "" "INPUT"

```
> 1 votes

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


title: Validate Random Die Tippers

text:
# Question
Title: Validate Random Die Tippers
Almost six years ago, fellow PPCG member steenslag posted the following challenge:

> In a standard dice (die) the numbers are arranged so that opposite faces add to seven. Write the shortest possible program in your preferred language which outputs a random throw followed by 9 random tippings. A tipping is a quarter turn of the dice, e.g. if the dice is facing 5, all possible tippings are 1,3,4 and 6.
>
> Example of desired output:
>
> > 1532131356

So, now that everybody has completely forgotten about it and the winning answer has long since been accepted, we'll be writing a program to validate the die tipping sequences generated by the submitted solutions. (This makes sense. Just pretend it does.)

# Challenge

Your program or function is given a sequence such as `1532131356`. Validate that each consecutive digit is:

* Not equal to the previous digit
* Not equal to *7* minus *the previous digit*

(You don't have to validate the first digit.)

## Rules

* Your program must return a truthy value if the input is valid and a falsey value otherwise.
* You can assume that the input consists of only the digits 1-6 and is at least 1 character long. Sequences won't have a fixed length like in steenslag's challenge.
* You can take the input as a string (`"324324"`), an array or array-like datastructure (`[1,3,5]`) or as multiple arguments (`yourFunction(1,2,4)`).

Standard I/O and loophole rules apply.

# Test cases

## Truthy

```
1353531414
3132124215
4142124136
46
4264626313135414154
6
2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323
5414142

```

## Falsey

* Repeated digit

```
11
3132124225
6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245
553141454631
14265411

```
* Opposing side of die

```
16
42123523545426464236231321
61362462636351
62362462636361

```

# Answer
> 13 votes
# Python 2, 43 45 bytes

```
lambda s:reduce(lambda p,n:n*(7-p!=n!=p>0),s)

```

# 43 bytes (inspired heavily by @Zgarb)

```
lambda s:reduce(lambda p,n:n*(p>0<n^p<7),s)

```

This function combines my reduce statement with the bit-flicking logic from @Zgarb's answer, for a combination that is shorter than both.

Both answers output the following:

* 0 if the input is not a valid sequence
* The last digit of the sequence if it is valid

# Answer
> 9 votes
## Python, 44 bytes

```
lambda x:all(0<a^b<7for a,b in zip(x,x[1:]))

```

Bitwise magic! This is an anonymous function that takes a list of integers, and checks that the XOR of every two consecutive elements is between 1 and 6 inclusive.

## Why it works

First, the XOR is always between 0 and 7 inclusive, since 7 is `111` in base 2, and our numbers have at most 3 binary digits. For the equality, `a^b == 0` if and only if `a == b`. Also, we have `7-a == 7^a` when `0 ≤ a ≤ 7`, and thus `a^b == 7` if and only if `a == 7^b == 7-b`.

# Answer
> 7 votes
# 05AB1E, ~~11~~ 9 bytes

***-2 bytes for Osable's smart idea of using a product.***

```
¥¹D7-Á+«P

```

Try it online!

```
¥           # Push deltas.
 ¹D7-Á      # Push original array, and 7 - [Array] shifted right once.
      +     # Add original to the 7 - [Array] shifted right.
       «    # Concat both.
        P   # Product, if either contain a zero, results in 0, meaning false.

```

Third approach using 05AB1E, that doesn't use the pairwise command:

* `0` if it violates the tipsy properties.
* `Not 0` if there was nothing preventing it from being tipsy.

# Answer
> 6 votes
# R, ~~39~~ ~~37~~ ~~32~~ 31 bytes

```
all(q<-diff(x<-scan()),2*x+q-7)

```

Try it online!

Takes input from stdin. Uses `diff` to see if any two consecutive digits are the same; then compares each digit to 7 minus the previous digit. Returns `TRUE` or `FALSE`.

Saved 5 bytes thanks to Jarko Dubbeldam, and another thanks to JayCe.

# Answer
> 5 votes
# 05AB1E, 10 bytes

```
$ü+7Ê¹üÊ*P

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 5 votes
## R, 49 44 bytes

```
!any(rle(x<-scan())$l-1,ts(x)==7-lag(ts(x)))

```

Reads input from stdin (separated by space) and outputs `TRUE/FALSE`. Will give a warning if input is of length one but still works.

Edit: saved a couple of bytes thanks to @rturnbull

# Answer
> 4 votes
## Ruby, 34 bytes

```
->s{!s[/[16]{2}|[25]{2}|[34]{2}/]}

```

# Answer
> 4 votes
# 05AB1E, 15 bytes

```
ü+7å¹ü-0å¹g_~~_

```

Try it online! or as a Test suite

# Answer
> 4 votes
## JavaScript (ES6), ~~43~~ 40 bytes

Returns `0` / `true`.

```
f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)

```

### Test cases

```
f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)

console.log('Testing truthy cases ...');
console.log(f('1353531414'));
console.log(f('3132124215'));
console.log(f('4142124136'));
console.log(f('46'));
console.log(f('4264626313135414154'));
console.log(f('6'));
console.log(f('2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323'));
console.log(f('5414142'));

console.log('Testing falsy cases ...');
console.log(f('11'));
console.log(f('3132124225'));
console.log(f('6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245'));
console.log(f('553141454631'));
console.log(f('14265411'));
console.log(f('16'));
console.log(f('42123523545426464236231321'));
console.log(f('61362462636351'));
console.log(f('62362462636361'));
```

# Answer
> 4 votes
# Perl 6, 22 bytes

Using a regex:

```
{!/(.)<{"$0|"~7-$0}>/}

```

Takes the input as a string. Inspired by G B's Ruby answer.
How it works:

* `/ /`: A regex.
* `(.)`: Match any character, and capture it as `$0`.
* `<{ }>`: Dynamically generate a sub-regex to be matched at that position.
* `"$0|" ~ (7 - $0)`: The sub-regex we generate is one that matches only the previous digit, or 7 minus the previous digit (e.g. `5|2`).
Thus the overall regex will match iff it finds an invalid consecutive pair of digits anywhere.
* `{! }`: Coerce to a boolean (causing the regex to be matched against `$_`), negate it, and turn the whole thing into a lambda (with implicit parameter `$_`).

# Perl 6, 38 bytes

Using list processing:

```
{all ([!=] 7-.[1],|$_ for .[1..*]Z$_)}

```

Takes the input as an array of integers.
How it works:

* `.[1..*] Z $_`: Zip the input list with an offset-by-one version of itself, to generate a list of 2-tuples of consecutive digits.
* `[!=] 7 - .[1], |$_`: For each of those, check if `(7 - b) != a != b`.
* `all ( )`: Return a truthy or falsy value depending on whether all loop iterations returned True.

# Answer
> 4 votes
# JavaScript ~~61~~ 43 bytes

Comments have mentioned I can't use C# linq functions without including the using statement, so here's the exact same in less bytes using standard JS...

```
f=a=>a.reduce((i,j)=>i>6|i==j|i+j==7?9:j)<7

```

# C#, ~~99~~ ~~67~~ 65 bytes

Takes input as an int array `a`

```
// new solution using linq
bool A(int[]a){return a.Aggregate((i,j)=>i>6|i==j|i+j==7?9:j)<7;}

```

```
// old solution using for loop
bool A(int[]a){for(int i=1;i<a.Length;)if(a[i]==a[i-1]|a[i-1]+a[i++]==7)return false;return true;}

```

Explanation:

```
// method that returns a boolean taking an integer array as a parameter
bool A(int[] a)
{
    // aggregate loops over a collection,
    // returning the output of the lambda
    // as the first argument of the next iteration
    return a.Aggregate((i, j) => i > 6 // if the first arg (i) > than 6
    | i == j      // or i and j match
    | i + j == 7  // or i + j = 7
    ? 9   // return 9 as the output (and therefore the next i value)
    : j   // otherwise return j as the output (and therefore the next i value)
    )
    // if the output is ever set to 9 then it will be carried through to the end
    < 7; // return the output is less than 7 (not 9)
}

```

# Answer
> 4 votes
## Python, 38 bytes

```
f=lambda h,*t:t==()or 7>h^t[0]>0<f(*t)

```

A recursive function that takes arguments like `f(1,2,3)`.

This makes use of argument unpacking to extract the first number into `h` and the rest into the tuple `t`. If `t` is empty, output True. Otherwise, use Zgarb's bit trick to check that the first two die rolls are not incompatible. Then, check that the result also holds on the recursive call on the tail.

# Answer
> 3 votes
# Processing, ~~93~~ ~~92~~ 90 bytes

*Changed* `||` *to* `|` *: 1 byte saved thanks to @ClaytonRamsey*

*Started counting backwards: 2 bytes saved thanks to @IsmaelMiguel*

```
int b(int[]s){for(int i=s.length;--i>0;)if(s[i-1]==s[i]|s[i-1]==7-s[i])return 0;return 1;}

```

Takes input as an array of ints, output `1` for true or `0` for false.

### Ungolfed

```
int Q104044(int[]s){
  for(int i=s.length;--i>0;)
    if(s[i-1]==s[i]|s[i-1]==7-s[i])
      return 0;
  return 1;
}

```

# Answer
> 3 votes
# \>\<\> (Fish) 47 bytes

```
0:i:1+?!v\!
   0n;n1< >
!?-{:-"0"/^
!? -{-$7:/^

```

Pretty simple;

Line 1: check to see if inputted a number, if no number (EOF) then we have a truthy to print else checks.

Line 2: print outcome.

Line 3: turn input into number (ASCII 0 - from input), then check if it's equal to previous input.

Line 4: check if input is opposite side of die.

# Answer
> 3 votes
# PowerShell, ~~57~~ ~~44~~ 41 bytes

*(Crossed out 44 is still regular 44)*

```
0-notin($args|%{7-$_-$l-and$l-ne($l=$_)})

```

Try it online!

*(OP has clarified that taking input as separate arguments is OK - saved 13 bytes ... saved another 3 bytes by eliminating `$b`)*

We're looping through the input `$args` a digit at a time. Each digit, we verify that the `$l`ast digit is `-n`ot`e`qual to the current digit `$_`, and that `7-$_-$l` is some number other than zero (which is truthy). Those Boolean results are encapsulated in parens and fed into the right-hand operand of the `-notin` operator, checking against `0`. In other words, if there is any `False` value anywhere in the loop, the `-notin` will also be `False`. That Boolean is left on the pipeline, and output is implicit.

Lengthy because of the `$` requirement for variable names, and that Boolean commands `-ne` `-and` are verbose in PowerShell. Oh well.

# Answer
> 3 votes
# Brain-Flak 128 Bytes

```
(()){{}(({}<>)<>[({})])}{}([]){{{}}<>}{}([]){{}({}({})<>)<>([][()])}{}(<{}>)<>(([])){{}{}({}[(()()()){}()]){<>}<>([][()])}({}{})

```

Outputs 0 for falsey, or -7 for truthy.

Try it Online! (Truthy)
Try it Online! (Flasey)

**Explanation (t stands for top and s stands for second from the top):**

```
(())                # push a 1 to get this loop started
{{}                 # loop through all pairs, or until 2 are equal
(({}<>)<>[({})])    # pop t, push t on the other stack, and t - s on this one
}{}                 # end loop and pop one more time
([])                # push the height of the stack
{                   # if the height isn't 0 (there were equal numbers)...
{{}}<>              # pop everything from this stack and switch
}                   # end if
{{}                 # for every pair on the stack: pop the height and...
({}({})<>)<>        # push t + s on the other stack leaving s on this one
([][()])            # push the height - 1
}                   # end loop when there is only 1 number left
{}(<{}>)<>          # pop t, pop s, push 0 and switch stacks
(([]))              # push the height twice
{                   # loop through every pair
{}{}                # pop the height and what was t - 7
({}[(()()()){}()])  # push t - 7
{<>}<>              # if t is not 0 switch stacks and come come back
                    # if t is 0 (ie, there was a pair that added to 7) just switch once
([][()])            # push height - 1
}                   # end loop
({}{})              # push t + s (either 0 + 0 or 0 + -7)

```

# Answer
> 3 votes
# MATLAB, 30 bytes

```
@(a)all(diff(a)&movsum(a,2)-7)

```

# Answer
> 3 votes
# PHP, 63 bytes

```
for($d=$argv[$i=1];$c=$argv[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);

```

takes input as list of command arguments; exits with `1` (error) if input is invalid, `0` (ok) if valid.

Run with `-nr`.

**input as string argument, 65 bytes**

```
for($d=($s=$argv[1])[0];$c=$s[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);

```

# Answer
> 3 votes
**C ~~47~~ 44 bytes**

```
F(char*s){return!s[1]||(*s^s[1])%7&&F(s+1);}

```

takes a string of digits (or a zero terminated array of bytes)

Explanation

`F(char*s){`

according to the standard `int` return type is implied. (saving 4 bytes)

`return` unconditional return because this is a recursive function

using shortcut evaluation:

`!s[1]||` if the second character is *nul* return true

`((*s^s[1])%7&&` if the first two charcters aren't legal false

`F(s+1))` check the rest of the string in the same way

that confusing expression

`*s` is the first character `s[1]` is the second

`*s^s[1]` exclusive-ors them together if they are the same the result is 0 if they add to 7 the result is 7 , (if they differ and don't add to 7 the result is between 1 and 6 inclusive)

so `(*s^s[1])%7` is zero for bad input and non-zero otherwise, thus false if these 2 characters are bad, and true otherwise

**comment:** as this function call uses only end-recursion (only the last statement is a recursive call) an optimiser could translate the recursion into a loop, this is a happy conicidence and is obviously not worth any golf score, but in the real word makes it possible to process strings of any length without running out of stack.

# Answer
> 2 votes
# Python, 71 bytes

```
f=lambda s:len(s)<2or(s[0]!=s[1]and int(s[0])!=7-int(s[1]))and f(s[1:])

```

Uses a recursive approach.

Explanation:

```
f=lambda s:                                                              # Define a function which takes an argument, s
           len(s)<2 or                                                   # Return True if s is just one character
                      (s[0]!=s[1]                                        # If the first two characters matches or...
                                 and int(s[0])!=7-int(s[1])              # the first character is 7 - the next character, then return False
                                                           )and f(s[1:]) # Else, recurse with s without the first character

```

# Answer
> 2 votes
## Retina, 28 bytes

```
M`(.)\1|16|25|34|43|52|61
^0

```

Try it online!

Alternatively:

```
M`[16]{2}|[25]{2}|[34]{2}
^0

```

Try it online!

# Answer
> 2 votes
# MATL, 9 bytes

```
dG2YCs7-h

```

The input is an array of numbers representing the digits.

The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy otherwise (read more about MATL's criterion for truthy and falsy here).

Try it online! Or verify all test cases.

### Explanation

```
d     % Take input implicitly. Consecutive differences
G     % Push input again
2YC   % Overlapping blocks of length 2, arranged as columns of a matrix
s     % Sum of each column
7-    % Subtract 7, element-wise
h     % Concatenate horizontally. Implicitly display

```

# Answer
> 2 votes
# C# (with Linq) ~~90~~ ~~81~~ ~~73~~ ~~71~~ ~~69~~ 68 Bytes

```
using System.Linq;n=>n.Aggregate((p,c)=>p<9|c==p|c==103-p?'\b':c)>9;

```

## Explanation:

```
using System.Linq;           //Obligatory import
n=>n.Aggregate((p,c)=>       //p serves as both previous character in chain and error flag
    p<9                      //8 is the error flag, if true input is already invalid
        |c==p
            |c==103-p        //103 comes from 55(7) + 48(0)
                ?'\b'       //'\b' because it has a single digit code (8)
                    :c)      //valid so set previous character, this catches the first digit case as well
                        >8;  //as long as the output char is not a backspace input is valid

```

# Answer
> 2 votes
**C, 81 bytes, was 85 bytes**

```
int F(int *A,int L){int s=1;while(--L)s&=A[L]!=A[L-1]&A[L]!=(7-A[L-1]);return s;}

```

Input is an array of integers A with length L. Returns 1 for true and 0 for false. The input is checked from the end to the start using the input length L as the array index.

# Answer
> 2 votes
## Haskell, 37 bytes

```
f(a:b:c)=a+b/=7&&a/=b&&f(b:c)
f _=1<2

```

Usage example: `f [1,5,2]` -\> `False`.

Simple recursion. Base case: single element list, which returns `True`. Recursive case: let `a` and `b` be the first two elements of the input list and `c` the rest. All of the following conditions must hold: `a+b/=7`, `a/=b` and the recursive call with `a` dropped.

# Answer
> 2 votes
## JavaScript, 40 bytes

```
f=i=>i.reduce((a,b)=>a&&a-b&&a+b-7&&b,9)

```

Takes advantage of the JavaScript feature that `&&` will return the last value that is parsed (either the falsy term or the last term). `0` is passed along if it doesn't meet the conditions, and the previous term is passed along otherwise. The 9 makes sure that it starts with a truthy value.

# Answer
> 1 votes
# Groovy, 61 bytes

```
{i=0;!(true in it.tail().collect{x->x in [7-it[i],it[i++]]})}

```

# Answer
> 1 votes
# Python 2, 58 Bytes

```
lambda x:all(x[i]!=x[i+1]!=7-x[i]for i in range(len(x)-1))

```

# Answer
> 1 votes
# \>\<\>, 39 bytes

```
0>i'0'-::&0)?v1n;>&!
?=0+=7+@=}:{:<;n0^

```

Try it online!

# Answer
> 1 votes
## Batch, 102 bytes

```
@set s=%1
@set/an=0%s:~0,2%,r=n%%9*(n%%7)
@if %r%==0 exit/b
@if %n% gtr 6 %0 %s:~1%
@echo 1

```

Ungolfed:

```
@echo off
rem grab the input string
set s=%1
:loop
rem convert the first two digits as octal
set /a n = 0%s:~0,2%
rem check for divisibility by 9 (011...066)
set /a r = n %% 9
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem check for divisibility by 7 (016...061)
set /a r = n %% 7
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem remove first digit
set s=%s:~1%
rem loop back if there were at least two digits
if %n% gtr 6 goto loop
rem truthy output
echo 1

```

# Answer
> 1 votes
**Clojure, ~~55~~ ~~49~~ 46 bytes**

*edit 1*: using `(mapcat ...)` instead of `(flatten(map ...))`

*edit 2*: using `(juxt - +)` instead of `(juxt = +)`, checking for values `0` or `7`

```
#(not(some #{0 7}(mapcat(juxt - +)(rest %)%)))

```

Consecutive values are not allowed to be equal (difference = `0`) or sum up to `7`. Got to use `juxt` again :)

# Answer
> 1 votes
# JavaScript (ES6), 46 Bytes

```
a=>r=1&&a.reduce((c,p)=>r=c==p||c==7-p?0:1)&&r

```

```
f=a=>r=1&&a.reduce((c,p)=>r=c==p||c==7-p?0:1)&&r;

console.log(f([4,6]));
console.log(f([1,6]));
```

# Answer
> 1 votes
# Bash, 60 bytes

```
f(){
while [ $2 ]
do
(( ($1^$2)%7 ))||return 1
shift
done
}

```

Takes separate arguments as input.

## Explanation

`while`-`do`-`shift`-`done` loops though the arguments giving each pair a turn as (`$1`,`$2`) if the loop completes truth is returned.

The complicated expression `(( ($1^$2)%7 ))` exclusive-ors the the arguments being tested together and `mod(7)`s them.

Valid pairs will result in non-zero, invalid ones in zero.

`((`...`))` yields true when the arithmetic returns non-zero.

`||` runs the next command if the previous was false (in this context that means if the arithmetic above returned 0).

Unix shell treats zero as true (except as above) so `return 1` yields a false result from this function when an invalid pair is found.

# Answer
> 1 votes
# Prolog (SWI), 45 bytes

```
p([A,B|T]):-A+B=\=7,A\=B,p([B|T]).
p([_|[]]).

```

Online interpreter

# Answer
> 1 votes
# Math++, 111 bytes

```
?>b
0>n
n+1>n
b%10>{n}
_(b/1)>b
3+4*!b>$
0>n
n+1>n
10+4*!({n}-{n+1})>$
11+3*!(7-{n}-{n+1})>$
8+4*!{n}>$
1
0>$
0

```

# Answer
> 1 votes
# Mathematica, 32 bytes

```
FreeQ[Most@#~BitXor~Rest@#,0|7]&

```

Unnamed function taking a list of integers as input and outputting `True` or `False`. Like many existing answers, it computes the bitwise XOR of consecutive elements of the input, and checks that the answer is never 0 nor 7.

# Answer
> 1 votes
# PHP, 41 bytes

```
<?=!similar_text(aa^af,$s^s.$s=$argv[1]);

```

Takes input as a string. Prints `1` if the input is valid, an empty string otherwise.

Calculates XOR by pairs of adjacent characters, using shifted version of the input. Then searches for `0x00` or `0x07` characters in it.

# Answer
> 1 votes
# SmileBASIC, 65 bytes

```
DEF T A
WHILE LEN(A)V=POP(A)IF!(O-V&&7-O-V)THEN?0A
O=V
WEND?1
END

```

This can definitely be made a little smaller

---
Tags: code-golf, sequence, decision-problem
---