title: Code Golf: Word Unscrambler

text:
# Question
Title: Code Golf: Word Unscrambler
Write a program that either accepts input via stdin or from the command line. It will then unscramble the words, printing out the unscrambled version of each word.You get a text file containing every word (most of them) in the English dictionary to use. (Here is the file: Word List, and you can either use it from the web or save it as a text file and use it from there.)

## Inputs to measure the score:

> bbuleb lwrfoe kaec rtawe cokr kmli pcaee

## Correct Outputs:

> bubble flower cake water rock milk peace
>
> bubble fowler cake water cork milk peace

(Word case doesn't matter, and please post your score and outputs along with your code!)

## Scoring:

Score = (Amount of correct outputs) x (100 / (Code Length))

The code with the highest score wins!

**Edit:** This is my first post, please be kind!

# Answer
> 3 votes
## GolfScript, 27 chars, 7 correct outputs ⇒ score ≈ 25.926

```
n%(\:w;' '%{$:c;w{$c=}?}%n*

```

GolfScript doesn't have a file I/O operator, so I had to get a bit clever with the input. Specifically,

* the scrambled words should be given on the first input line, separated by spaces, and
* the wordlist should be given on the subsequent input lines, one word per line.

The scrambled words and the wordlist need to have the same letter case.

Here's an example invocation from a Unix shell command line, assuming that the code above has been saved as `unscramble.gs`, the GolfScript interpreter as `golfscript.rb` and the wordlist as `wordlist.txt`:

```
(echo BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE; cat wordlist.txt) \
  | ruby golfscript.rb unscramble.gs

```

This will produce the following output:

```
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE

```

The way it works is simply by sorting the letters in each input word and selecting the first word in the wordlist that produces the same string when its letters are sorted. Nearly half of the code is actually just for input parsing (and output formatting): all the real work is done in the `{$:c;w{$c=}?}%` loop.

Here's a de-golfed version with comments showing how it works:

```
n %                 # split the input on newlines
( \ :w ;            # pop the first line off the list of lines and assign the rest to w
' ' %               # split the first line on spaces

# apply the following map to each scrambled word:
{
    $ :c ;          # sort the letters in the word and assign the sorted word to c
    w { $ c = } ?   # find the first word in w that, sorted, equals c
} %

n *                 # join the results with newlines for output

```

# Answer
> 5 votes
## Python 3 / 84 chars / 7 correct outputs / score 8.3333

**edit** As per clarifications, removed `.upper()` and considering all 7 ouputs correct.

```
a=sorted
for b in input().split():print([c for c in open('x')if a(b)==a(c[:-1])][0])

```

Output:

```
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE

```

# Answer
> 3 votes
## Python, ~~189~~ ~~171~~ 156 chars / ~~6~~ 7 correct outputs / "spirit of the law"

```
from urllib import*
z=sorted
x=dict((`z(m)`,m)for m in urlopen("http://bit.ly/wZYCmE").read().split())
for n in raw_input().split():print x[`z(n.upper())`]

```

(It gets "fowler" instead of "flower", both are on the input list and have the same letters.)

Edit: Steven Rumbalski's suggestions

## Python, 144 chars / 7 correct outputs / "letter of the law"

```
for x in raw_input().split():print{620:'bubble',655:'flower',404:'cake',547:'water',431:'rock',429:'milk',510:'peace'}[sum(map(ord,x.lower()))]

```

# Answer
> 2 votes
### bash, grep, sed, sort: 144 chars, 144/7=20.57 (all correct)

```
s(){
echo $1|sed 's/./\n&/g'|sort
}
for w in $*
do
for m in $(egrep "^["$w"]{"${#w}"}$" d)
do
[[ `s $w` = `s $m` ]] &&(echo $m;break)
done
done

```

d is the filename of the dict; for testing on Linux replace it with `$d` as `d=/usr/share/dict/words` and subtract 1 from the filesize, to avoid a local copy.

usage:

```
./unscramble.sh bbuleb lwrfoe kaec rtawe cokr kmli pcaee
bubble
flower
cake
water
cork
rock
milk
peace

```

works well with dict/words, so I didn't download anything, lazy me! :)

# Answer
> 1 votes
## Perl, 173 characters / 6 correct outputs

```
use LWP::Simple;
sub e{my$m;$m.=$_ for sort split//,uc$_[0];$m}$_=get"http://bit.ly/wZYCmE";
@x=split/\n/;$_=<>;for(split){$l=$_;for(@x){print"$_ ",$l=''if(e$_)eq e$l}}

```

# Answer
> 1 votes
## JavaScript, ~~357~~ 330 chars \[node.js\] / 7 correct outputs

```
function g(w,s){return s===+s?g[a=w.toUpperCase().split("").sort().join("")]=g[a]||w:w.split("\n").map(g)&&s.split(" ").map(g).join(" ")}require('http').get({host:'web.mit.edu',path:'/kilroi/Public/bot/wordlist'},function(r){b=[];function f(c){c?b.push(c):console.log(g(b.join(""),process.argv[2]))}r.on('data',f),r.on('end',f)})

```

Eugh... slightly prettier version below. Doesn't read from stdin (string to check is first command-line argument), but it *does* fetch the dictionary from the net. The `g` function receives a string with the dictionary content (`w`) and a string to check (`s`); this is the most interesting part I suppose.

(It should theoretically work on any input string, as long as there's a permutation of each word in the dictionary. Oh, and the output is currently upper-case \[as it is in the dictionary\])

```
function g(w,s) {
  return s===+s
       ? g[a=w.toUpperCase().split("").sort().join("")] = g[a] || w
       : w.split("\n").map(g) && s.split(" ").map(g).join(" ")
}

require('http').get({host:'web.mit.edu',path:'/kilroi/Public/bot/wordlist'}, function(r) {
  b=[]
  function f(c) {
    c ? b.push(c)
      : console.log(g(b.join(""), process.argv[2]))
  }
  r.on('data',f)
  r.on('end',f)
})

```

# Answer
> 1 votes
# Q,38 chars, 7 correct, 18.42105 points

```
{1#d(&)1=asc[x]~/:(asc')d:(_)read0`:d}

```

d is the dictionary file, stored locally in the same working directory.

usage:

```
{1#d(&)1=asc[x]~/:(asc')d:(_)read0`:d} each ("bbuleb";"lwrfoe";"kaec";"rtawe";"cokr";"kmli";"pcaee")
"bubble"
"flower"
"cake"
"water"
"cork"
"milk"
"peace"

```

# Answer
> 1 votes
## PHP 270bytes Source. SCORE- ?

I'm not sure if if this type of output is accepted, please inform if its wrong.

```
<?$s=explode(PHP_EOL,file_get_contents('http://bit.ly/wZYCmE'));$n=explode(' ',$argv[1]);for($i=0;$i<count($n);$i++){$f=0;for($j=0;$j<count($s);$j++){$t1=str_split(trim($n[$i]));sort($t1);$t2=str_split($s[$j]);sort($t2);if($t1==$t2){$f++?echo'/':0;echo$s[$j];}}echo' ';}

```

Run:

```
php unscramble.php "BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE"

```

Output:

```
BUBBLE FLOWER/FOWLER CAKE WATER CORK/KROC/ROCK MILK PEACE

```

# Answer
> 0 votes
# Jelly, 14 bytes, 7 correct outputs ⇒ score = 50 (Feedback appreciated!)

```
ɠḲ©µ³ḲŒ!f®ḢƊ€K

```

Try it online! (Long URL)

Feed space-separated dictionary on `stdin` and space-separated scrambled words as the first argument, e.g. `curl http://web.mit.edu/kilroi/Public/bot/wordlist | tr '\n' ' ' | jelly fun unscrambler.j "BBULEB LWRFOE KAEC RTAWE COKR KMLI PCAEE"`

```
ɠḲ©µ³ḲŒ!f®ḢƊ€K
ɠḲ©µ               read the dictionary from stdin splitting on spaces, and save it to the register
    ³Ḳ             split the scrambled word list argument on spaces
            Ɗ      define a function of the previous three links taking an input W:
       Œ!f®        get all permutations of W, and filter it with the dictionary
                   (aka, remove all words in the dictionary that are not permutations of W)
           Ḣ       take the head, so we return just one unscrambled word per scrambled word
              €K    run that Ɗ function on each of the unscrambled words, and split the results with spaces

```

# Answer
> 0 votes
# Zsh, 129 chars / 7 correct outputs ⇒ score ≈ 5.426

```
for i in $@
do
while read w
do
[[ ${#w} == ${#i} ]]&&[[ ${${(Lo)${(s::)w}}} == ${${(Lo)${(s::)i}}} ]]&&echo $w&&break
done<d
done

```

Usage:

Save the word list as `d` in the same directory as the script, and from that directory run

```
% zsh ./unscramble.zsh bbuleb lwrfoe kaec rtawe cokr kmli pcaee
BUBBLE
FLOWER
CAKE
WATER
CORK
MILK
PEACE

```

How it works:

`(s::)` splits into single-character words

`(L)` lowercases

`(o)` sorts ascending

Was inspired to try after reading this blog post. Not golf, but a fun survey. (Disclaimer: the article's from one of the other teams at my workplace.)

---
Tags: code-golf, word
---


title: Identical grids

text:
# Question
Title: Identical grids
You’re given two \\$r×c\\$ grids. Each cell contains either 0 or 1. What are the minimum number of swaps (between horizontally and vertically adjacent cell elements, no wrapping i.e no swapping between last and first element of a row) are required in the first grid for it to match the second. If the matched arrangement can never be achieved, output -1.

**Constraints**

\\$1 \leq r \leq 100\\$
\\$1 \leq c \leq 100 \\$

**Examples**

```
input:
00
11

01
10
output:
1

input:
00
11

01
00
output:
-1

input:
0011011

0101101
output:
2

```

# Answer
# Python 3, 383 334 bytes

*-6 bytes thanks to @Kevin Cruijssen*

*-43 bytes thanks to @Jitse*

```
import numpy
z=len
d=lambda a,b,c,d:abs(a-c)+abs(b-d)
def g(l,m):
 if z(l)==1:yield d(*l[0],*m[0])
 for i in range(z(l)):
  for s in g(l[1:],m[:i]+m[i+1:]):yield d(*l[0],*m[i])+s
def c(a,b):
 e=a-b;k=z(a);f,*h=[],
 for x in range(k*z(a[0])):w=[(x%k,x//k)];v=e[x%k][x//k];f+=w*(v>0);h+=w*(v<0)
 return-1 if numpy.sum(e)else min(g(f,h))

```

Try it online!

Takes input as two numpy arrays.

### Explanation:

First, `e=a-b` determines which positions change from one grid to the other. The next line finds all of the differences and sorts them into the lists `f` and `h`. If the sum of differences is not zero, meaning there are more 1s in one grid than the other, this returns `-1`, or the minimum of all possible paths found by `g`.

This is the fun part. Essentially, in order to make this work, a 1 must move from one position to another by swapping. Therefore, the minimum number of swaps for each pair is the manhattan distance between them, found in `d`. `g` finds every possible pairing between start and end points and returns a list of the total distances between them. If there is only one start point, it returns the distance between that and the end point. Beyond that, it pairs the first start point with each end point iteratively and adds their distance to the total distance of the rest of the points, calculated recursively.
> 5 votes

# Answer
# APL (Dyalog Extended), 35 bytes

```
{⍺≠⍥≢⍵:¯1⋄⌊/⍺[⌂pmat≢⍺]+.(1⊥∘|-)⍵}⍥⍸

```

Try it online!

A function that takes two Boolean matrices as left and right arguments.

Uses Hiatsu's algorithm. One additional thing to point out is that, while moving a 1 from some position to another, it may freely step over some ones and still take the same steps. Therefore, the pairwise Manhattan distances can be summed without interfering each other. (This doesn't invalidate the previous answers; rather, it covers a hole in the proof that the algorithm is indeed correct.)

```
Moving the one at the start to the end:
1 0 0 0 0 1 1 1 0 0 0
^------->              Move the 1 four steps forward
0 0 0 0 1 1 1 1 0 0 0
        <-------^      Move the 0 four steps backwards
0 0 0 0 0 1 1 1 1 0 0  (See that the target 1 has moved 4 steps forward as net effect)
                ^--->  Finally move the 1 to the destination
0 0 0 0 0 1 1 1 0 0 1
So the 1 has travelled the distance of 10 in 10 steps, stepping over ones

```

### How it works: the code

```
{⍺≠⍥≢⍵:¯1⋄⌊/⍺[⌂pmat≢⍺]+.(1⊥∘|-)⍵}⍥⍸  ⍝ Main function
{                               }⍥⍸  ⍝ Extract coordinates of ones from both args
 ⍺≠⍥≢⍵:     ⍝ If the lengths (count of ones) do not match,
       ¯1   ⍝ Return minus 1
         ⋄  ⍝ Otherwise,
            ⍺[⌂pmat≢⍺]            ⍝ All permutations of coordinates of left arg
                      +.(1⊥∘|-)⍵  ⍝ Inner product with ⍵ to get Manhattan distance sum:
                        (1⊥∘|-)   ⍝ sum the absolute differences of coords point-wise
                      +.          ⍝ and sum all the distances
          ⌊/                      ⍝ Pick the minimum value

```
> 4 votes

# Answer
> Based on @Hiatsu's answer.

# Python 3, 262 bytes

```
e=enumerate
def f(r,s):
 if not r:yield 0
 for i,t in e(r):yield abs(t[0]-s[0][0])+abs(t[1]-s[0][1])+min(f(r[:i]+r[i+1:],s[1:]))
def g(x,y):
 z=x-y;n=len(x.T);v,*w=[],
 for i,p in e(z.flat):t=[(i%n,i//n)];v+=t*(p>0);w+=t*(p<0)
 return-1if z.sum()else min(f(v,w))

```

Try it online!
> 1 votes

---
Tags: code-golf, grid, binary-matrix
---


title: Smaller Strings in Printable ASCII base

text:
# Question
Title: Smaller Strings in Printable ASCII base
# Task

Given a input string `s` which contains only printable ascii characters output all strings which contain only printable ascii characters and are strictly smaller than `s` in any order

String `a` is strictly smaller than a string `b` if either of the following is true:

* `len(a) < len(b)`
* `len(a) == len(b)` and string `a` is lexicographically smaller than string `b`

**Note:** here printable ascii characters refer to the characters which have a ascii value strictly greater than `0x1f` and strictly less than `0x7f`

Reference Python Implementation

# Scoring

This is so shortest bytes wins

# Testcases

```
'' -> []
'%' -> ['$', '', '#', '"', ' ', '!']
' #' -> ['', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '  ', ' !', ' "']
'! ' -> ['', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '  ', ' !', ' "', ' #', ' $', ' %', ' &', " '", ' (', ' )', ' *', ' +', ' ,', ' -', ' .', ' /', ' 0', ' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' :', ' ;', ' <', ' =', ' >', ' ?', ' @', ' A', ' B', ' C', ' D', ' E', ' F', ' G', ' H', ' I', ' J', ' K', ' L', ' M', ' N', ' O', ' P', ' Q', ' R', ' S', ' T', ' U', ' V', ' W', ' X', ' Y', ' Z', ' [', ' \\', ' ]', ' ^', ' _', ' `', ' a', ' b', ' c', ' d', ' e', ' f', ' g', ' h', ' i', ' j', ' k', ' l', ' m', ' n', ' o', ' p', ' q', ' r', ' s', ' t', ' u', ' v', ' w', ' x', ' y', ' z', ' {', ' |', ' }', ' ~']

```

# Answer
# 05AB1E, 11 bytes

*-1 byte thanks to @KevinCruijssen*

```
gžQ×æêéI¡н

```

Try it online!

TIO link is for "abcd" instead of printable ascii since powerset of len(input) printable ascii takes a while to compute...

---

### Explanation

```
gžQ×                 - repeat printable ascii length of the input times
    æ                - get the powerset of this string
     êé              - sort and uniquify lexicographically then sort by length
       I¡            - split on the input
         н           - and take the elements that are before it
                     - output these implicitly

```
> 4 votes

# Answer
# Haskell, ~~64~~ 62 bytes

```
f s|h:t<-mapM(\_->[' '..'~'])<$>scanr(:)""s=id=<<filter(<s)h:t

```

Try it online!

---

Previous 64 byte version with explanation:

```
f s=[x|x<-mapM(\_->[' '..'~'])=<<scanr(:)""s,(0<$x)<(0<$s)||x<s]

```

Try it online!

Given an input string `s`, e.g. `s="abc"`, `scanr(:)""s` yields all suffixes of `s`: `["abc","bc","c",""]`. `mapM(\_->[' '..'~'])` takes a string and computes all possible combinations of the printable ASCII characters of the same length as this string. We apply this function to all the suffixes and thus get all possible strings of length 3, 2, 1 and zero. `x` iterates over all those strings and we keep only those that are smaller in length (`(0<$x)<(0<$s)` using this Tip) or lexicographically smaller (`x<s`) than the input `s`.
> 3 votes

# Answer
# Jelly,  ~~11~~  10 bytes

-1 thanks to Nick Kennedy!

```
LŻØṖṗẎṣ⁸Ṗj

```

A monadic Link accepting a list of characters which returns a list of lists of characters.

**Try it online!** (footer prints each on it's own line, since a full program would implicitly smash and print)

### How?

```
LŻØṖṗẎṣ⁸Ṗj - Link: list of characters (i.e. a string), S
L          - length (S)
 Ż         - zero-range -> [0,1,2,...,length(S)]
  ØṖ       - list of printable ASCII characters
    ṗ      - Cartesian power (vectorises) - i.e. all length n strings for n in [0..len(S)]
     Ẏ     - tighten (join all these lists of strings to one list of strings)
       ⁸   - chain's left argument, S
      ṣ    - split (the list of strings) at occurrences of (S)
        Ṗ  - throw away the rightmost list of strings (those lexicographically greater than S)
         j - join (the resulting list of lists of strings) with (S) (to get a list of strings)

```
> 3 votes

# Answer
# Python 3, ~~146~~ ~~139~~ ~~138~~ 136 bytes

```
lambda s:[v for n in range(len(s)+1)for v in g(n)if n<len(s)or v<s]
g=lambda n:n and[s+chr(c+32)for c in range(95)for s in g(n-1)]or[""]

```

Try it online!

**How:**

The function `g` recursively generates all strings of length `n`. Our main function `f` only has to generate all the shorter strings and then, for the strings with the same length as the input, only keep the ones that have smaller dictionary order.

Thanks to @SurculoseSputum for fixing a mistake *and* saving 2 bytes at the same time, plus saving 2 bytes on a different golfing effort.
> 2 votes

# Answer
# JavaScript (Node.js), 110 bytes

Prints the strings.

```
s=>(g=o=>o[k=s.length]||o[g([...o,32]),(n=o.length)<k|(S=Buffer(o)+'')<s&&console_log(S),n-1]++<126&&g(o))([])

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~142~~ ~~141~~ ~~135~~ 129 bytes

```
lambda s:["%c"*n%p for n in range(len(s)+1)for p in product(*tee(range(32,127),n))if n<len(s)or"%c"*n%p<s]
from itertools import*

```

Try it online!

Takes input as a string `s`, and outputs a list of strings.

## Explanation

The function generates all printable strings of length at most `len(s)`, then keeps the ones that are smaller than `s`.

```
lambda s:[
  "%c"*n%p                    # forms string from p - a tuple of n ints (representing ASCII code points)
  for n in range(len(s)+1)    # for each length n from 0 to len(s), inclusive
  for p in product(*tee(range(32,127),n))
                              # for each possible tuple of n ASCII codepoints
  if n<len(s)or"%c"*n%p<s     # keep only the strings that are smaller than s
]

```

To generate all printable strings of length `r`:

* `tee(range(32,127),n)` creates `n` iterators from 32 to 126 inclusive
* `product(*tee(...))` finds the Cartesian product of those `n` iterators
* `p in product(...)`: `p` will be a tuple of `n` integers, each between 32 and 126 inclusive
* `"%c"*r%p` creates a string of `n` characters from `p`.
> 2 votes

# Answer
# \[Ruby\], ~~111~~ 108 bytes

```
->s,w=[*32..126]{!s[0]? []:w.product(*([w]*(s.size-1))).map{|a|a.map{|n|n<32 ?"": n.chr}*''}.select{|t|t<s}}

```

Try it online!

This perplexed me for far too long until I realised that I had the test cases mixed up (D'oh!).

It also creates a Cartesian product of the ASCII characters, and filters those "less than" the input string.

### Explanation

`w.product(*([w]*(s.size-1)))` to get the Cartesian product of the ASCII characters, where `w=[*32..126]`. Found here

`a.map{|n|n<32 ?"": n.chr}*''` to then take those arrays of code points and convert them to characters and join them into strings

`.select{|t|t<s}}` to filter down to those strings less than the input string.

**Edit**: Swap out `s.empty?` for `!s[0]`. Everything except `nil` and `false` are truthy in Ruby, and indexing an array out of bounds returns `nil`. So if there is a first element, then the array is not empty.
> 2 votes

# Answer
# Pyth, 10 bytes

```
f!-Trd\rk

```

Try it online!

Contains an unprintable after the `\` so here's a hex dump:

```
00000000: 66 21 2d 54 72 64 5c 7f 72 6b        f!-Trd\.rk

```

**Explanation**

* `rk(Q)` Generate a string range from the empty string to the input string. This is a list of all strings strictly smaller than the input, but it also contains characters outside the printable ASCII range.
* `rd\.` Generate a string range from the space character (ascii 32) to the DEL character (ascii 127). This is the range of printable ASCII.
* `f!-T ...` Filter for elements of the first range that contain only elements of the second range.
> 2 votes

# Answer
# PHP, 138 bytes

```
$c=unpack('C*',$argn);for(;$i=count($c);){for(;$i;)if(--$c[$i]<32)$c[$i--]=126;else break;if(!$i)array_pop($c);echo pack('C*',...$c),',';}

```

Try it online!

The idea is to create an array of ASCII code points and iterate over those.
> 1 votes

# Answer
# Charcoal, 21 bytes

```
ＵＴＥΦＥ⍘⁺!θＳ⍘ιγ⁼§ι⁰!✂ι¹

```

Try it online! Link is to verbose version of code. I don't know whether I should include the `ＵＴ` in the byte count but Charcoal's default of padding all lines to the same length does make distinguishing between strings that might end in spaces very tricky. Explanation:

```
ＵＴ

```

Turn off padding.

```
     !              Literal `!`
    ⁺               Concatenated with
      Ｓ             Input string
   ⍘   γ            Base conversion using printable ASCII as base 95
  Ｅ                 Map over implicit range
        ⍘ιγ         Convert current value to base 95 as printable ASCII
 Φ                   Filter where
            §ι⁰      First character
           ⁼   !     Equals literal `!`
Ｅ                   Map over results
                ✂ι¹ Slice off first character
                    Implicitly print

```

If Charcoal had a bijective base conversion function, this could be written `Print(Map(BijectiveBaseString(InputString(), g), BijectiveBaseString(i, g)));` probably for 9 bytes, but unfortunately it doesn't, so the easiest way to fake it is to prefix all values with the same ASCII character and filter out entries that don't begin with that character.
> 1 votes

# Answer
# JavaScript (Node.js), 90 bytes

```
s=>(g=(x='',j=32,b=Buffer)=>(s[x.length]?b(95).map(_=>g(x+b([j++]))):x<s)&&console_log(x))

```

Try it online!
> 1 votes

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


title: Stepping Through Time

text:
# Question
Title: Stepping Through Time
**Given a 24 hour time, e.g. 20:48, output the nearest time where each adjacent pair of digits has an absolute difference of 1, e.g. 21:01.**

That is, each number in the output must differ from the numbers next to it by 1, and the output must be the closest time, forwards or backwards, for which this is true. Time can be considered to wrap around. For example, 23:55 and 00:05 are only 10 minutes apart.

### Input

* Input can be in any reasonable form which represents all four digits of a 24 hour time. E.x. a string, "20:48" (colon optional), a list of integers, \[2, 0, 4, 8\], or a single integer 2048.
* Leading zeros are optional for input. Use whatever is most convenient.
* You can assume the input will always represent a valid 24 hour time.

### Output

* You must output four integers which represent a valid 24 hour time. The individual integers can be represented in whatever form is most convenient. E.x. \[2, 1, 0, 1\] or "2101".
* Leading zeros are *not* optional for output. E.x. you can't output 1:23 instead of 01:23.
* You may optionally output a separator between the hours and minutes. This can be a colon, period, space, newline, or some other junk that saves you a byte. Whatever separator you choose, it must be consistent from one output to another.
* If there are two equally close times to the input which satisfy the requirements, you may output either.
* Note there are only 16 possible outputs: 01:01, 01:21, 01:23, 10:10, 10:12, 12:10, 12:12, 12:32, 12:34, 21:01, 21:21, 21:23, 23:21, 23:23, 23:43, and 23:45.

### Test cases

* 00:10 -\> 23:45
* 01:23 -\> 01:23
* 05:46 -\> 01:23
* 05:47 -\> 10:10
* 12:00 -\> 12:10
* 16:47 -\> 12:34
* 16:48 -\> 21:01
* 20:48 -\> 21:01
* 21:22 -\> 21:23 *or* 21:21

Python 3 reference implementation.

### Score

This is code golf, so the shortest program in bytes wins. The standard loopholes are forbidden.

# Answer
> 2 votes
# Jelly, 29 bytes

```
⁽¬ẊDŻ€Œpḣ⁽¢ẒðIAP€ẹ1ạÞiḢị⁸

```

A monadic Link accepting a list of four integers which yields a list of four integers.

**Try it online!** Or see the test-suite.

# Answer
> 10 votes
# JavaScript (ES7),  ~~136~~  132 bytes

Takes a single integer as input and returns a string.

```
s=>(V=g=(d,t=s,k=0)=>k>V?R:[...S=([1e3]+t).slice(-4)].some(p=c=>(p-(p=c))**2-1)?g(d,t=(t-~d)%2400,k+=t%100<60):(V=k,R=S))()&&g(2398)

```

Try it online!

### How?

The only valid hour prefixes are `01`, `10`, `12`, `21` and `23`. It means that any invalid minute count starting with a digit greater than 5 will be rejected by the test on the absolute difference between two consecutive digits.

So there's no need to explicitly handle the wrapping of minutes modulo 60. Instead, we can just make sure that the distance `k` is not incremented on invalid minutes:

```
k += t % 100 < 60

```

---

# JavaScript (Node.js),  ~~148~~  146 bytes

Takes a single integer as input and returns a string.

This version picks the answer from a hardcoded table.

```
t=>0x60553BCD48A3CE4F56D818FDC473FC726398E907D3A9n.toString(6).substr([22,85,9,423,462,x=98,x,9,9,413,461,9,x,x,9,9].findIndex(d=>(t-=d+2)<0)*4,4)

```

Try it online!

### How?

Once converted to base-6, the integer `0x60553BCD48A3CE4F56D818FDC473FC726398E907D3A9n` is turned into the following string, which holds all possible valid answers:

```
"23450101012101231010101212101212123212342101212121232321232323432345"

```

The correct answer is selected according to the interval in which the input time falls:

```
 answer | input interval
--------+----------------
 "2345" | 00:00 - 00:23
 "0101" | 00:24 - 01:10
 "0121" | 01:11 - 01:21
 "0123" | 01:22 - 05:46
 "1010" | 05:47 - 10:10
 "1012" | 10:11 - 11:10
 "1210" | 11:11 - 12:10
 "1212" | 12:11 - 12:21
 "1232" | 12:22 - 12:32
 "1234" | 12:33 - 16:47
 "2101" | 16:48 - 21:10
 "2121" | 21:11 - 21:21
 "2123" | 21:22 - 22:21
 "2321" | 22:22 - 23:21
 "2323" | 23:22 - 23:32
 "2343" | 23:33 - 23:43
 "2345" | 23:44 - 23:59

```

The lengths of the intervals in minutes (minus 2) are stored in an array.

# Answer
> 5 votes
# Python 2, ~~136~~ ~~138~~ ~~133~~ ~~126~~ ~~125~~ ~~122~~ ~~151~~ ~~124~~ ~~108~~ ~~106~~ ~~103~~ 101 bytes

```
f=lambda h,m,i=0:(h,m)*all(j%11%9==1for j in(h,m/10-h%10,m))or f((h+(m+i)/60)%24,(m+i)%60,~i+2*(i<1))

```

Try it online!

Input is hour,minute parameters result is (hour,minute) tuple

Using recursion

i moves through \[0,-1,+2,-3,+4,...\] the sum of the initial terms therefore moves through \[0,-1,1,-2,2,...\]

(h,m) are offset by i minutes moving alternately through nearest above and below time not yet checked.

Check for result by considering h, m and h%10\*10+m/10, which is low hour digit and top minute digit.

To check two digit number n in form d (d+1) or (d+1) d, observe n%11 is either 1 or 10 in exactly these cases, and checking for 1 or 10 using %9==1. i.e. n%11%9==1

As this two digit test reduces modulo 11, h%10\*10+m/10 is equivalently m/10-h%10.

**Previous approach**:

```
def f(h,m,i=0):t=m+i;s='%02d'*2%((h+t/60)%24,t%60);return s*all(a+b in'4321012345'for a,b in zip(s,s[1:]))or f(h,m,-i+(i<1))

```

Try it online!

Input in integer output is 4 character string.

Formats number as string, taking pairs checks against string table, otherwise recurse with alternating offsets (i=0,1,-1,2,-2,...)

Originally:

Offsets n by \[0,1,-1,2,-2,...\], formats as four digit string, then taking pairs of characters checks they differ by one by looking up as substring in compressed string table.

+2 bytes Fixed by adding '43' to table.

-5 bytes Removed unnecessary +2400, which was to avoid mod of negative number -- Python's % works properly in that case.

-7 bytes string table improved, and by using / instead of // due to Surculose Sputum.

-1 byte reduce range of search.

-3 bytes Surculose Sputum: remove unecessary \[\] in all() and compress expression i%2\*2-1 to i%-2|1.

+29 bytes code was broken, added correction term for wrapping minutes (n%100+i)/60\*40

-27 bytes Surculose Sputum: rewritten using recursion

-16 bytes reworked using new approach

-2 bytes remove introduced variable which was false saving.

-3 bytes simplification for middle digits test.

-2 bytes Surculose Sputum: using lambda instead of def

# Answer
> 4 votes
# Python 2, 142 bytes

```
lambda*t:'%02d'*2%max(g(-720,*t))[1:]
g=lambda w,h,m,t=10:w/720*[0]or[(w*w,h,m)]*({h/t-h%t,h%t-m/t,m/t-m%t}<={1,-1})+g(w+1,(h+m/59)%24,-~m%60)

```

Try it online!

without the strict output:

# Python 2, ~~160~~ ~~148~~ ~~144~~ ~~138~~ 133 bytes

-~~6~~ 11 bytes thanks to Surculose Sputum!

Input and output is `hours, minutes`.

```
lambda*t:max(g(-720,*t))[1:]
g=lambda w,h,m,t=10:w/720*[0]or[(w*w,h,m)]*({h/t-h%t,h%t-m/t,m/t-m%t}<={1,-1})+g(w+1,(h+m/59)%24,-~m%60)

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~159~~ 155 bytes

Heavily inspired by @Arnauld's JavaScript solution. Instead of converting the answer string from hex to base 6, I needed to convert it from ~~hex~~ *base 36* to base 10, since Python does not have built-in conversion to an arbitrary base.

*-4 bytes thanks to @ovs for the suggestion to convert from base 36*

```
x=input()
j=0
while x>23:x-=[80,4,418,457,93,93,4,4,408,456,4,93,93,4,4,9][j/4]+7;j+=4
print`int("2T9DHQE9BIABWTC7VO76PFJ2QND3LLSQY0ISQTMZCHP5",36)`[j:j+4]

```

Try it online!

Takes input as an integer representing the time (eg. `2101` for 21:01, or `123` for 01:23). Output is a string in the form `hhmm` with no delimiter.

# Answer
> 3 votes
# JavaScript (Node.js), 108 bytes

```
t=>(g=i=>(k=0,s=(new Date(t-i*6e4)+0).slice(16,21),h(1)+h(3)+h(4)-3?g(~i+(i<0)):s))(0,h=l=>(s[k]-s[k=l])**2)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 59 bytes

```
≔⪪”)⊟ς∧Ｑ@ςE⁶¿ê40ofυ_Y±F⌊M↨ ”⁴υ≔↔⁻↨⁶⁰Ｉ⪪Ｓ²Ｅυ↨⁶⁰Ｉ⪪ι²θ∧⊟υ§υ⌕θ⌊θ

```

Try it online! Link is to verbose version of code. I/O is as a 4-digit string without colon. Explanation:

```
≔⪪”)⊟ς∧Ｑ@ςE⁶¿ê40ofυ_Y±F⌊M↨ ”⁴υ

```

Split a compressed string of all the possible times into substrings of 4 digits. (I tried computing the string but unfortunately that cost at least 6 more bytes.) Additionally include the value `2401` which will map to `0101` for the next day.

```
≔↔⁻↨⁶⁰Ｉ⪪Ｓ²Ｅυ↨⁶⁰Ｉ⪪ι²θ

```

Convert the input and the substrings into seconds since midnight and take the absolute difference.

```
∧⊟υ§υ⌕θ⌊θ

```

Print the substring with the least absolute difference, but remove the `2401` entry first, which causes the indexing to wrap around to `0101`.

# Answer
> 1 votes
# JavaScript (V8), 155 bytes

```
(s,o=Math.abs,m=k=>Math.min(o(s-k),o(s+2400-k)))=>[101,121,123,1010,1012,1210,1212,1232,1234,2101,2121,2123,2321,2323,2343,2345].sort((a,b)=>m(a)-m(b))[0]

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 106 bytes

Prompts for time as a vector of integers hh mm:

```
¯2↑¨'0',¨⍕¨,60 60⊤((|m)=⌊/|m←(¯15,1↓n)-60 60⊥⎕)/n←60 60⊥⍉17 2⍴¯33+⎕av⍳'7M!!!7!5***,,*,,,@,B5!555775777B7M'

```

Stores 16 possible times as characters in APL+WIN character set (extended ASCII) adjusted by 33 to make printable. Could be removed to save 4 bytes. Converts to seconds, gets closest match and outputs nested character vector of time. Unfortunately I cannot put this up on TIO because my usual route via Dyalog Classic does not work as Dyalog character set appears to be in a different order to APL+WIN. Anyone care to translate?

# Answer
> 1 votes
# 05AB1E, 35 bytes

```
60©Ž5—Ÿ®δвT‰JʒS¥ÄP}D®δβD14(ªI®β.xkè

```

Both input and output is a pair of `[hours, minutes]`.

Try it online or verify all test cases.

**Explanation:**

```
60                 # Push 60
  ©                # Store it in variable `®` (without popping)
   Ž5—             # Push compressed integer 1425
      Ÿ            # Pop both, and push a list in the range [60,1425]
       ®δв         # Convert each integer to a base-60 list/pair
          T‰       # Add leading 0s by taking the divmod-10 on each inner integer,
            J      # and then joining the inner pairs together
ʒ                  # Filter this list by:
 S                 #  Convert it to a flattened list of digits
  ¥Ä               #  Get the absolute difference of each pair of digits
    P              #  And check if all of them are exactly 1
}D                 # After the filter: duplicate the list of remaining pairs
  ®δβ              # Convert each pair from a base-60 pair back to a base-10 integer
     D             # Duplicate that list of integers
      14(ª         # Append a trailing -14
          I        # Push the input-pair
           ®β      # Convert it from a base-60 pair also to a base-10 integer
             .x    # Get the integer in the list closest to this value
               k   # Get the index of this value in the duplicated list
                   # (which will result in -1 for the trailing -14)
                è  # And use that to index into the duplicated list of pairs
                   # (where the -1 will index into the last pair, which is the [23,45])
                   # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integer*) to understand why `Ž5—` is `1425`.

---
Tags: code-golf, clock
---


# Question
Title: Determine if a move exists in a Bejeweled/match 3 game
# Background

In Bejeweled and similar games, the player must swap any two adjacent gems (no diagonals) in an 8x8 grid of gems in order to match three of the same color in a row. The gems can be matched horizontally or vertically. Gameplay continues until there no move exists that can be made resulting in three in a row, at which point the game is over.

# Task

The goal is to write a program that determines whether a game of Bejeweled is not over yet. In other words, it must check to see if there is a possible move that makes at least three in a row. There can be more than three gems in a row and it is still a valid move.

# Input

Your program must accept via standard input an 8x8 representation of a Bejeweled grid. Each of the seven gem colors will be represented by a digit from 1 to 7. Each line will contain one row, and 8 lines, each consisting of 8 digits, will be input. See the examples. You can assume that the input will always follow this format, and will never already contain three in a row.

# Output

The program must then output (to standard output) `yes` or `no` depending on whether or not at least one valid move exists that would result in three or more gems in a row. Your program must not output anything other than a single instance of either `yes` or `no`.

# Rules

Your program must not use any external files or resources, command-line arguments, or require a certain file name. The program with the least number of bytes in its source code wins.

# Examples

**Input:**

```
12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656

```

**Output:** `yes`

**Input:**

```
35261546
76421754
15743271
62135642
35617653
64565476
54427254
15635465

```

**Output:** `no`

See MT0's answer below for additional test cases.

# Answer
# Original Solution: JavaScript - ~~261~~ ~~255~~ ~~228~~ ~~227~~ ~~179~~ 153 Characters

```
/(\d)(\1(\d|.{6}|.{9})|(\d|.{6}|.{9})\1|.{7}\1(.|.{9})|(.|.{9})\1.{7}|(.{7,9}|.{17})\1.{8}|.{8}\1(.{7,9}|.{17}))\1/.test(s.replace(/\n/g,'A'))?'yes':'no'

```

Assuming that the string to test is in the variable `s` (to make it a function `f` then add `f=s=>` to the beginning of the code or, otherwise, to take input from a prompt then replace `s` with `prompt()`).

Outputs is to the console.

# 3rd Solution: JavaScript (ECMAScript 6) - 178 Characters

```
p=x=>parseInt(x,36);for(t="2313ab1b8a2a78188h9haj9j8iaiir9r",i=v=0;s[i];i++)for(j=0;t[j];v|=s[i]==s[i+a]&s[i]==s[i+b]&i%9<8&(b>3|(i+b-a)%9<8))a=p(t[j++]),b=p(t[j++]);v?'yes':'no'

```

I took the 2nd solution, below, (which uses regular expressions to check for characters in certain configurations) and reworked it to just check the string for identical characters in the same configurations without using regular expressions.

The Base-36 string `"2313ab1b8a2a78188h9haj9j8iaiir9r"` gives pairs of offsets to check - i.e. the pair `23` results in the check if ith character is identical to the (i+2)th character and the (i+3)th character (the equivalent of the regular expression `(.).\1\1` \- with some additional checks to ensure that the non-identical character is not a newline).

# 2nd Solution: JavaScript (ECMAScript 6) - 204 Characters

```
p=x=>parseInt(x,18);g=a=>a?a>1?"(.|\\n){"+a+"}":".":"";f=(x,a,b)=>RegExp("(.)"+g(a)+"\\1"+g(b)+"\\1").test(x);for(t="10907160789879h8",i=v=0;t[i];v|=f(s,x,y)||f(s,y,x))x=p(t[i++]),y=p(t[i++]);v?'yes':'no'

```

Builds multiple regular expressions (see below for more details) using pairs of values taken from the Base-18 string `10907160789879h8` and takes the `OR` of all the tests. To reduce it further you can note that the regular expressions come in pairs where one is the "reverse" of the other (ignoring the Regular Expressions for 3-in-a-row horizontally and vertically as the OP states they will never be present - if you want to add those tests back in the append `0088` to the Base-18 string).

**Explanation**

Start with 16 regular expressions covering all the possible configurations of valid moves:

```
REs=[
    /(\d)\1\1/,                 // 3-in-a-row horizontally
    /(\d).\1\1/,                // 3-in-a-row horizontally after left-most shifts right
    /(\d)\1.\1/,                // 3-in-a-row horizontally after right-most shifts left
    /(\d)(?:.|\n){9}\1\1/,  // 3-in-a-row horizontally after left-most shifts down
    /(\d)(?:.|\n){7}\1.\1/, // 3-in-a-row horizontally after middle shifts down
    /(\d)(?:.|\n){6}\1\1/,  // 3-in-a-row horizontally after right-most shifts down
    /(\d)\1(?:.|\n){6}\1/,  // 3-in-a-row horizontally after left-most shifts up
    /(\d).\1(?:.|\n){7}\1/, // 3-in-a-row horizontally after middle shifts up
    /(\d)\1(?:.|\n){9}\1/,  // 3-in-a-row horizontally after right-most shifts up
    /(\d)(?:.|\n){7,9}\1(?:.|\n){8}\1/, // 3-in-a-row vertically (with optional top shifting left or right)
    /(\d)(?:.|\n){7}\1(?:.|\n){9}\1/,   // 3-in-a-row vertically after middle shifts right
    /(\d)(?:.|\n){9}\1(?:.|\n){7}\1/,   // 3-in-a-row vertically after middle shifts left
    /(\d)(?:.|\n){8}\1(?:.|\n){7}\1/,   // 3-in-a-row vertically after bottom shifts right
    /(\d)(?:.|\n){8}\1(?:.|\n){9}\1/,   // 3-in-a-row vertically after bottom shifts left
    /(\d)(?:.|\n){17}\1(?:.|\n){8}\1/,  // 3-in-a-row vertically after top shifts down
    /(\d)(?:.|\n){8}\1(?:.|\n){17}\1/,  // 3-in-a-row vertically after bottom shifts up
];

```

(*Note: the regexs for 3-in-a-row horizontally (0th) and vertically (part of the 9th) are irrelevant as the OP states that inputs matching these will never be present.*)

Testing each of those against the input will determine if a valid move of that configuration can be found.

However, the regular expressions can be combined to give these 6:

```
/(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1/            // Tests 0,1,3,5
/(\d)\1(?:.|(?:.|\n){9}|(?:.|\n){6})?\1/            // Tests 0,2,6,8
/(\d)(?:.|\n){7}\1(?:.|(?:.|\n){9})\1/              // Tests 4,10
/(\d)(?:.|(?:.|\n){9})\1(?:.|\n){7}\1/              // Tests 7,11
/(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\1(?:.|\n){8}\1/ // Tests 9,14
/(\d)(?:.|\n){8}\1(?:(?:.|\n){7,9}|(?:.|\n){17})\1/ // Tests 9a,12,13,15

```

These can then be combined into a single regular expression:

```
/(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1|(\d)\2(?:.|(?:.|\n){9}|(?:.|\n){6})?\2|(\d)(?:.|\n){7}\3(?:.|(?:.|\n){9})\3|(\d)(?:.|(?:.|\n){9})\4(?:.|\n){7}\4|(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\5(?:.|\n){8}\5|(\d)(?:.|\n){8}\6(?:(?:.|\n){7,9}|(?:.|\n){17})\6/

```

Which just needs to be tested against the input.

**Test Cases**

Some test cases which other people might find useful (doesn't comply with the input format of using only digits 1-7 but that's easily corrected and is only an 8x4 grid - since that is the minimum required for a test of all the valid inputs).

In the format of a map from input string to which of the 16 regular expressions above it matches.

```
Tests={
    "12345678\n34567812\n56781234\n78123456": -1, // No Match
    "12345678\n34969912\n56781234\n78123456": 1,    // 3-in-a-row horizontally after left-most shifts right
    "12345678\n34567812\n59989234\n78123456": 2,    // 3-in-a-row horizontally after right-most shifts left
    "12345978\n34567899\n56781234\n78123456": 3,    // 3-in-a-row horizontally after left-most shifts down
    "12345978\n34569892\n56781234\n78123456": 4,    // 3-in-a-row horizontally after middle shifts down
    "12345678\n34967812\n99781234\n78123456": 5,    // 3-in-a-row horizontally after right-most shifts down
    "12399678\n34967812\n56781234\n78123456": 6,    // 3-in-a-row horizontally after left-most shifts up
    "12345678\n34597912\n56789234\n78123456": 7,    // 3-in-a-row horizontally after middle shifts up
    "12345998\n34567819\n56781234\n78123456": 8,    // 3-in-a-row horizontally after right-most shifts up
    "12945678\n34597812\n56791234\n78123456": 9,    // 3-in-a-row vertically after top shifts right
    "12349678\n34597812\n56791234\n78123456": 9,    // 3-in-a-row vertically after top shifts left
    "12345978\n34569812\n56781934\n78123456": 10,   // 3-in-a-row vertically after middle shifts right
    "92345678\n39567812\n96781234\n78123456": 11,   // 3-in-a-row vertically after middle shifts left
    "12945678\n34967812\n59781234\n78123456": 12,   // 3-in-a-row vertically after bottom shifts right
    "12349678\n34569812\n56781934\n78123456": 13,   // 3-in-a-row vertically after bottom shifts left
    "12395678\n34567812\n56791234\n78193456": 14,   // 3-in-a-row vertically after top shifts down
    "12345698\n34567892\n56781234\n78123496": 15,   // 3-in-a-row vertically after bottom shifts up
    "12345678\n34567899\n96781234\n78123456": -1,   // No match - Matches (.)\1.\1 but not 3 in a row
    "12345679\n99567812\n56781234\n78123456": -1,   // No match - Matches (.).\1\1 but not 3 in a row
};

```

**Edit 1**

Replace `\d`s with `.` \- saves 6 characters.

**Edit 2**

Replace `(?:.|\n)` with `[\s\S]` and removed extra non-capturing groups and updated back references (as suggested by m-buettner) and added in yes/no output.

**Edit 3**

* Added ECMAScript 6 solution to build the individual Regular Expressions from a Base-18 string.
* Removed the tests for 3-in-a-row horizontally (as suggested by m-buettner).

**Edit 4**

Added another (shorter) solution and two more non-matching tests cases.

**Edit 5**

* Shortened original solution by replacing newlines with a non-numeric character (as suggested by VadimR).

**Edit 6**

* Shortened original solution by combining bits of the regular expression (as suggested by VadimR).
> 13 votes

# Answer
# Python 383

Just a single\* line of Python!

```
a=[list(l)for l in raw_input().split('\n')];z=any;e=enumerate;c=lambda b:z(all(p==b[y+v][x+u]for(u,v)in o)for y,r in e(b[:-2])for x,p in e(r[:-2])for o in [[(0,1),(0,2)],[(1,0),(2,0)]]);print z(c([[q if(i,j)==(m,n)else a[m][n]if(i,j)==(y+1,x+1)else p for j,p in e(r)]for i,r in e(a)])for y,t in e(a[1:-1])for x,q in e(t[1:-1])for n,m in((x+u,y+v)for u,v in[(1,0),(1,2),(0,1),(2,1)]))

```

\*Well, with semicolons, but that's still non-trivial in python (python one-liners are fun!)
> 4 votes

# Answer
# APL (Dyalog Unicode), 71 bytes

```
'no' 'yes'⊃⍨{∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)}↑{⍞}¨⍳8

```

Try it online!

Nice challenge to show off some extreme array-processing capabilities of APL.

Without the I/O restriction, it is **~~55~~ 52 bytes** as a function taking a 8-by-8 matrix of chars and returning a boolean (therefore without 7-bytes pre-processing `↑{⍞}¨⍳8` and 12-bytes post-processing `'no' 'yes'⊃⍨`):

```
{∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)}

```

Try it online!

The basic idea is that we can test for 1x4 and 2x3 sub-boxes if each sub-box has a valid Bejeweled move:

```
(1x4 box)
OxOO    OOxO

(2x3 box)
OOx     OxO     xOO
xxO     xOx     Oxx

Oxx     xOx     xxO
xOO     OxO     OOx

```

For 1x4 boxes, we can check if the first item appears at least 3 times. For 2x3 boxes, we can check if at least one item in the first column appears in every column. For 4x1 and 3x2 boxes, we can check for 1x4 and 2x3 on the board transposed.

### How it works: the code

```
'no' 'yes'⊃⍨{∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)}↑{⍞}¨⍳8

↑{⍞}¨⍳8  ⍝ Take 8 lines of input and form a 8x8 matrix
     ⍳8  ⍝ A dummy length-8 vector
 {⍞}¨    ⍝ Map "take a line of input" over the dummy vector
↑        ⍝ Promote a vector of vectors to a matrix (M)

{∨/∊{...}¨⍵(⍉⍵)}  ⍝ Pass the matrix onto the inline function
          ⍵(⍉⍵)   ⍝ M and transpose of M
    {...}¨        ⍝ Test over M and transposed M for Bejeweled moves
                  ⍝ (explained below)
 ∨/∊              ⍝ Enlist all booleans and check if any is true

{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}  ⍝ Test over all possible sub-boxes
((3≤1⊥⊃=⊢)¨4,/⍵)  ⍝ Test over 1x4 boxes
           4,/⍵   ⍝ Extract 1x4 boxes
 (    ⊃=⊢)¨       ⍝ For each box, test if each item equals first item
  3≤1⊥            ⍝ Is the count at least 3?
({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)  ⍝ Test over 2x3 boxes
 {             }⌺2 3⊢⍵   ⍝ Ditto
        ⍵∘.=⊣/⍵          ⍝ Compare each item with the first column
  ∨⌿                     ⍝ Does there exist an item from the first column
    ∧⌿                   ⍝ that appears on every column
      ∨⌿                 ⍝ at least once?

'no' 'yes'⊃⍨  ⍝ Map 0/1 to no/yes respectively

```
> 4 votes

# Answer
# Perl, ~~114~~ ~~96~~ ~~95~~ ~~93~~ ~~92~~ ~~87~~ ~~86~~ 85 bytes

Includes + for `-a0p`

Run with the input on STDIN:

```
bejeweled.pl
12314131
13224145
54762673
61716653
61341144
23453774
27645426
75575656
^D

```

`bejeweled.pl`:

```
#!/usr/bin/perl -a0p
$i/s%.%chop$F[$i++&7]%eg>3|/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/||redo;$_=$1?yes:n.o

```

This combines a single direction horizontal regex solution with rotations

## Explanation:

In this solution I will repeatedly rotate and do the following 4 tests:

```
/(.).\1\1/,      // 3-in-a-row horizontally after left-most shifts right
/(.)\C{9}\1\1/,  // 3-in-a-row horizontally after left-most shifts down
/(.)\C{7}\1.\1/, // 3-in-a-row horizontally after middle shifts down
/(.)\C{6}\1\1/,  // 3-in-a-row horizontally after right-most shifts down

```

Where `\C` is "any character" (unlike `.` this includes newline). Except that `\C` is deprecated and leads to warnings, so I use `\H` (non-horizontal space) instead which is good enough to capture all digits and newline.

After 4 rotation this will have done all 16 tests that are needed

```
-p                            Read lines from STDIN, print $_ at the end
-0                            No line ending => slurp ALL of STDIN
-a                            Split $_ into @F. Since there are no spaces
                              on the rows this means each element of @F is
                              1 row

    s%.%chop$F[$i++&7]%eg     Replace each row by the removed last column
                              This is therefore a left rotation. Very short
                              but at the cost of using @F. To make sure that
                              @F gets refilled from $_ each time I won't be
                              able to use while, until, eval or do$0 for the
                              loops but have to use redo. That costs a few
                              bytes but less than having to do my own split
$i/                      >3   The previous regex replacement always
                              returns 64 and each time through the loop $i is
                              increased by 64. So if this division reaches
                              4 all rotations have been done

/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/ This is the 4 regexes mentioned above
  ||redo                      Stop the loop if the regex matches or we
                              rotated 4 times
$_=$1?yes:n.o                If the regex matched $1 will be one of the
                              color digits (which cannot be 0) and this will
                              assign "yes" to $_. If the regex didn't match
                              in 4 times $1 will get its value from the last
                              succesful regex in scope which will be the one
                              from the rotation, but that one doesn't have
                              any () so $1 will be unset. So in case there
                              is no move $_ will be set to "no" (which needs
                              to be constructed because "no" is a keyword)

```
> 3 votes

# Answer
# Node.js - Naive solution - 905 bytes

Well, no answers yet so I'll post a really naive solution in Node.js

It goes through every possible move and then tests the resulting board to see if there's 3 in a row.

Golfed (with google closure compiler) (some hacky stuff in there like !0 and !1; I'm not even sure what it did with my XOR swap)

```
Array.prototype.a=function(){for(var f=[],d=0;d<this.length;d++)f[d]=this[d].a?this[d].a():this[d];return f};for(var a=[],b=0;8>b;b++)a[b]=[];for(b=2;b<process.argv.length;b++)for(var c=process.argv[b].split(""),e=0;e<c.length;e++)a[b-2][e]=parseInt(c[e],10);function h(){for(var d=l,f=0;f<d.length-2;f++)for(var g=0;g<d[f].length-2;g++){var k=d[f][g];if(k==d[f+1][g]&&k==d[f+2][g]||k==d[f][g+1]&&k==d[f][g+2])return!0}return!1}function m(){console.log("yes");process.exit()}for(b=0;b<a.length;b++)for(e=0;e<a[b].length;e++){var l=a.a();0!=b&&(l[b-1][e]^=l[b][e],l[b][e]^=l[b-1][e],l[b-1][e]^=l[b][e],h()&&m(),l=a.a());b!=a.length-1&&(l[b+1][e]^=l[b][e],l[b][e]^=l[b+1][e],l[b+1][e]^=l[b][e],h()&&m(),l=a.a());0!=e&&(l[b][e-1]^=l[b][e],l[b][e]^=l[b][e-1],l[b][e-1]^=l[b][e],h()&&m(),l=a.a());e!=a[b].length-1&&(l[b][e+1]^=l[b][e],l[b][e]^=l[b][e+1],l[b][e+1]^=l[b][e],h()&&m(),l=a.a())}console.log("no");

```

Note that I wrote this *all* on my mobile and don't have time to test it or anything. Comment if you see any bugs, I'll check it myself later.

The pre-golfed human readable version

```
// set it up
Array.prototype.clone = function() {
    var arr = [];
    for( var i = 0; i < this.length; i++ ) {
        if( this[i].clone ) {
             arr[i] = this[i].clone();
        } else {
             arr[i] = this[i];
        }
    }
};
var board=[];
for(var i=0;i<8;i++)board[i]=[];
for(var i=2;i<process.argv.length;i++){
    var row=process.argv[i].split("");
    for(var j=0;j<row.length;j++)board[i-2][j]=parseInt(row[j], 10);
}
// function to test
function testBoard(arr){
    for(var i=0;i<arr.length-2;i++){
        for(var j=0;j<arr[i].length-2;j++){
            var val=arr[i][j];
            if(val==arr[i+1][j] && val==arr[i+2][j])return true;
            if(val==arr[i][j+1] && val==arr[i][j+2])return true;
        }
    }
    return false;
}
// functions to exit
function yay(){console.log("yes");process.exit();}
function nay(){console.log("no");}
// super slow naive solution time
for(var i=0;i<board.length;i++){
    for(var j=0;j<board[i].length;j++){
        var newboard=board.clone();
        if(i!=0){
            newboard[i-1][j]=newboard[i-1][j]^newboard[i][j];// whoa, it's a
            newboard[i][j]=newboard[i-1][j]^newboard[i][j];  // cool algorithm
            newboard[i-1][j]=newboard[i-1][j]^newboard[i][j];// at least this
                                                             // isn't all naive
            if(testBoard(newboard))yay();
            newboard=board.clone();
        }
        if(i!=board.length-1){
            newboard[i+1][j]=newboard[i+1][j]^newboard[i][j];
            newboard[i][j]=newboard[i+1][j]^newboard[i][j];
            newboard[i+1][j]=newboard[i+1][j]^newboard[i][j];
            if(testBoard(newboard))yay();
            newboard=board.clone();
        }
        if(j!=0){
            newboard[i][j-1]=newboard[i][j-1]^newboard[i][j];
            newboard[i][j]=newboard[i][j-1]^newboard[i][j];
            newboard[i][j-1]=newboard[i][j-1]^newboard[i][j];
            if(testBoard(newboard))yay();
            newboard=board.clone();
        }
        if(j!=board[i].length-1){
            newboard[i][j+1]=newboard[i][j+1]^newboard[i][j];
            newboard[i][j]=newboard[i][j+1]^newboard[i][j];
            newboard[i][j+1]=newboard[i][j+1]^newboard[i][j];
            if(testBoard(newboard))yay();
            newboard=board.clone();
        }
    }
}
nay();

```
> 2 votes

# Answer
# 05AB1E, 51 bytes

```
„€¸…Ü#|€S2FÐ€ü3ø€ü2s€ü4«sø}\«€`ʒÐg;iøćδåøPàë¢3å]gĀè

```

Port of the approach used by *@Bubbler* in his APL answer, so make sure to upvote him!!

Try it online.

**Explanation:**

```
„€¸…Ü                 # Push dictionary string "no yes"
     #                # Split it on spaces: ["no","yes"]
|                     # Push all input-lines as list
 €S                   # Convert each line to a list of digits
   2F                 # Loop 2 times:
     Ð                #  Triplicate the matrix
      €               #  For each row:
       ü3             #   Create overlapping triplets
         ø            #  Zip/transpose; swapping rows/columns
          €           #  For each overlapping 3-sized column:
           ü2         #   Create overlapping pairs
     s                #  Swap to get the initial matrix again
      €               #  For each row:
       ü4             #   Create overlapping quadruplets
         «            #  Merge this list of 4x1 blocks to the list of 2x3 blocks
     s                #  Swap again to get the initial matrix
      ø               #  Zip/transpose; swapping rows/columns
    }\                # After the loop: discard the top item
      «               # Merge the two lists together
       €`             # Flatten it one level down
         ʒ            # Filter this list of 4x1 and 2x3 blocks by:
          Ð           #  Triplicate the block
           g          #  Get its length (either 4 or 2)
            ;i        #  If this length is 2:
              ø       #   Zip/transpose; swapping rows/columns,
                      #   to make the 2x3 block a 3x2 block
               ć      #   Extract head; pop and push the remainder 2x2 columns and
                      #   first 2x1 column separated to the stack
                δ     #   Apply double-vectorized:
                 å    #    Check if the value is in the list
                  ø   #   Zip/transpose; swapping rows/columns,
                      #   so the checks per value are in the same inner list
                   P  #   Check for both lists whether all checks were truthy
                    à #   And check if either of the two checks is truthy
             ë        #  Else (the length is 4 instead):
              ¢       #   Count how many times each value occurs in the 4x1 block
               3å     #   And check if the counts contain a 3
         ]            # Close both the if-else statement and filter
          g           # Get the amount of remaining blocks
           Ā          # Check that at least one block is remaining
                      # (1 if truthy; 0 if falsey)
            è         # And use that to index into the ["no","yes"] list
                      # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„€¸…Ü` is `"no yes"`.
> 2 votes

# Answer
# Python3, 314B

```
import itertools as T,copy
r=[]
K=range(8)
J=[list(input())for w in K]
P=T.product
f=lambda A:["yes"for b in[A[m][n:]for m,n in P(K,K[:6])]if b[0]==b[1]==b[2]]
for i,j,x in P(K,K,[0,1]):
 t=j+1-x
 if i+x<8and t<8:B=copy.deepcopy(J);B[i][j],B[i+x][t]=B[i+x][t],B[i][j];r+=f(B)+f(list(zip(*B)))
r+=["no"]
print(r[0])

```

Change the 8, the 5 on line 6, and the 8s on line 9 to handle arbitrarily large input sizes; also doesn't care what each value is, so you can feed it:

```
absdefgh
sdkljahs
lsdfjasd
fjdhsdas
dkjhfasd
sdfhaskd
sdkfhkas
weriuwqe

```

and it will return `yes`.

### Annotations

```
import itertools as T,copy
            # itertools.product is going to save us lots of for loops
r=[]        # result
K=range(8)  # we can use range(8) everywhere, so this saves more than the usual R=range
J=[list(input())for w in K]
            # input handling: keep everything as a length-1 string to avoid map(int,input())
P=T.product
f=lambda A:["yes"for b in[A[m][n:]for m,n in P(K,K[:6])]if b[0]==b[1]==b[2]]
            # check the condition horiontally only. K[:6] is the same as range(5)
            # A[m][n:n+3] would be neater, but not actually needed
for i,j,x in P(K,K,[0,1]):
            # <3 itertools.product! 3 for-loops without it.
            # NB we're only going right and downwards
 t=j+1-x
 if i+x<8and t<8:
            # don't want out-of-bounds errors at the edges
  B=copy.deepcopy(J)
            # preserve the reference array
  B[i][j],B[i+x][t]=B[i+x][t],B[i][j]
            # do the switch
  r+=f(B)+f(list(zip(*B)))
            # do the test. you could end up with lots of 'yes's in r.
            # zip(*B) takes the transpose, so that f checks the columns too
r+=["no"]   # happens to ensure that r is nonempty
print(r[0]) # only prints no if r was empty before the last line

```
> 1 votes

# Answer
# GNU sed 255+2 = 257B

I thought this wasn't going to be as good as python but it is now :-/ I've been without internet access today so I occupied myself with solving this in sed :). Needs to be called with the -r flag, i.e. `sed -rf command.sed < input` so I added 2 to my score.

```
:a
$!N
s/\n/ /g
ta
:b
/^((\w)(\w\2\2|\2\w\2|\w\2\w* \w\2|\2\w* \w\w\2|\w* (\2\w* \w* \2|\w* \2\w* \2|\w\2\2|\w\2\w* \2|\2\w* \w\2|\w\2\w* \w\2))|\w((\w)(\w* \6\w\6|\6\w* \6|\w* (\6\w \w\6|\w\6\w* \6|\6\w* \6))|\w(\w)\w* \9\9))/c\yes
s/\w(\w*)/\1/g
tb
c\no

```

How it works:

1. Read the grid into a single line of space-separated characters
2. Use the motherload regex to find out whether there's a match in the first column\* - if yes, swap the entire line for 'yes' (ending the program)
3. Strip the first character from each column and goto 2 if we did
4. If we didn't (the line is empty) replace the whole line with 'no'
> 1 votes

# Answer
# Ruby, 201 bytes

I was disappointed not to see any solutions to this great challenge that don't use a regex or brute force (although those are great), so I wrote one. It takes input on STDIN.

The core bitwise arithmetic algorithm is derived from this fantastic answer on Game Development Stack Exchange by @leander.

```
s=$<.read
$><<(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}?"yes":"no"

```

## Ruby lambda, 181 bytes

Here it is as a lambda that takes a string and returns `true` or `false`:

```
->s{(?1..?9).any?{|n|a=[0]*19
s.scan(n){i=$`.size
a[i/9+1]+=2**(i%9)
a[i%9+10]+=2**(i/9)}
a.each_cons(3).any?{|x,y,z|q=y&y<<1
l=q<<1
q>>=2
y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}}

```

See it on repl.it: https://repl.it/ColJ/2

## Ungolfed & explanation

```
->s{
  (?1..?9).any? {|n|
    a = [0] * 19

    s.scan(n) {
      i = $`.size
      a[i/9+1] += 2**(i%9)
      a[i%9+10] += 2**(i/9)
    }

    a.each_cons(3).any? {|x,y,z|
      q = y & y << 1
      l = q << 1
      q >>= 2
      y & (l << 1 | q >> 1) |
        (q | l | (y & y << 2) >> 1) &
        (x | z) > 0
    }
  }
}

```

The code iterates over the digits "1" to "9." Each iteration has two discrete steps:

The first step is board transformation, which you can see in the `s.scan(n)` block in the ungolfed code. It transforms the board into an array of 8 integers, one for each row, by treating matching digits as 1s and all others as 0s in a binary string. For example, take the row `12231123`. In the first iteration, this will become the binary string `10001100` (all 1s become—er, stay—1s and all other digits become 0s), which is the decimal number 140. In the second iteration the same row becomes `01100010` (all 2s become 2s and all other digits become 0s), or decimal 98.

It simultaneously performs a second transformation, which is the same as the first but with the board rotated 90 degrees. This lets us use the same logic for making horizontal matches as vertical ones. For simplicity, it concatenates the two boards into a single long one with a zero at the beginning, middle (to separate the two boards), and end for padding.

The second step is searching for possible matches, which you can see in the `each_cons(3).any?` block. The transformed rows (which are now 8-bit integers) are checked in (overlapping) groups of three rows (*x*, *y*, *z*) using bitwise arithmetic. Each group is checked to see if a match can be made in row *y*, either by shifting a piece in row *y* or by shifting a piece into *y* from *x* or *z*. Since there is a zero "row" before and after both the original and rotated boards' rows, we don't have to check if we're on the first or last row of a board.

If no matches were found, it continues to the next iteration.
> 1 votes

---
Tags: code-golf, game, grid
---


title: Country name mashup generator

text:
# Question
Title: Country name mashup generator
Part 1 of the task is here

Flags Mashup Bot is a small Twitter bot that generates a new country name based on two random country names and tweets the result every couple of minutes.

## Task

Your task is to replicate what the bot does by writing a script or a function based on the following criteria:

* The input is two country names in English as shown in this page. Country names contain upper or lowercase letters of the English alphabet, spaces or dashes, and there's a special case of `Côte d'Ivoire`. They are usually capitalised with the exception of prepositions and similar words. Examples: `United States of America`, `Portugal`, `Côte d'Ivoire`, `Guinea-Bissau`.
* The output is a single country name that is a mixture of the two inputs based on the following rules:

+ If both names are single words you have to split each country name after a vowel randomly, then use the first half from the first country and the second half of the second country.
        - Vowels are `a`, `e`, `i`, `o`, `u`, or their uppercase variants
        - After the split both parts should contain at least one letter. The first half will always contain the vowel it was split by. The second half doesn't need to contain vowels however.
        - Example: `Poland` can be split by either `Po/land` or `Pola/nd`
        - Example: `Algeria` can be split by `A/lgeria`, `Alge/ria`, or `Algeri/a`. However `Algeria/` is not valid, as the second half doesn't contain any letters.
        - Example output: Mixing `Poland` and `Algeria` can be either of the following: `Polgeria`, `Poria`, `Poa`, `Polalgeria`, `Polaria` or `Polaa`
    + If one of the country names are multiple words while the other is a single one, then you have to replace either the first word of the multi-word one, or the last word with the other dependent on whether the multi-word country name is the first or second.
        - Example: `United States of America` and `France` is `United States of France`.
        - Example: `France` and `United States of America` is `France States of America`
    + If both names are multi-word ones then you have to split both of them at one of the word boundaries and then join them together afterwards.
        - Example: `United States of America` and `Trinidad and Tobago` can be `United and Tobago`, `United States and Tobago`, `United States of and Tobago`, `United Tobago`, `United States Tobago`, or `United States of Tobago`
    + Special case 1: countries containing dashes counts multi-word ones. If you split the name at the dash you have to use a dash in the output instead of a space
        - Example: `United States of America` and `Guinea-Bissau` can be `United States of-Bissau` among others
        - Example: `Spain` and `Timor-Leste` is `Spain-Leste`
    + Special case 2: If you enter the same country twice, you have to return `<country name> 2`.
        - Example: `United States of America` and `United States of America` will return `United States of America 2`
        - Example: `Hungary` and `Hungary` will return `Hungary 2`

Notes:

* Your submission should work for at least the countries as shown in this list
* It is okay if the result is the same as one of the input countries, e.g. `United States of America` and `United Kingdom` can result in `United Kingdom`
* `Côte d'Ivoire` counts as two words: `Côte` and `d'Ivoire`.
* There are no countries in the list that contain both spaces and dashes
* Vowels are `a`, `e`, `i`, `o`, `u`, `A`, `E`, `I`, `O`, `U`
* Standard loopholes, as usual, are prohibited

Examples with all valid answers for a specific pair:

```
Poland, Algeria
Polgeria, Poria, Poa, Polalgeria, Polaria, Polaa

Algeria, Poland
Aland, And, Algeland, Algend, Algeriland, Algerind

United States of America, France
United States of France

France, United States of America
France States of America

United States of America, Trinidad and Tobago
United and Tobago, United States and Tobago, United States of and Tobago, United Tobago, United States Tobago, United States of Tobago

Trinidad and Tobago, United States of America
Trinidad States of America, Trinidad of America, Trinidad America, Trinidad and States of America, Trinidad and of America, Trinidad and America

Hungary, Hungary
Hungary 2

United States of America, United States of America
United States of America 2

United States of America, Guinea-Bissau
United-Bissau, United States-Bissau, United States of-Bissau

Guinea-Bissau, United States of America
Guinea-States of America, Guinea-of America, Guinea-America

Timor-Leste, Spain
Timor-Spain

Spain, Timor-Leste
Spain-Leste

Côte d'Ivoire, Portugal
Côte Portugal

Portugal, Côte d'Ivoire
Portugal d'Ivoire

Côte d'Ivoire, Timor-Leste
Côte-Leste

Timor-Leste, Côte d'Ivoire
Timor-d`Ivoire

```

, so shortest code by byte count wins and will be accepted. Please include example a set of input & output with your submission

# Answer
# Jelly, ~~74~~ 73 bytes

```
JṖXṬk⁸ḢḢFṪ;ƲƭF)jṪḢƭ€Ṁ$$
ḢṖ;
ṪḢṪ;Ɗṭ
Fe€ØcṖTXṬkḢḢṪƭ)
e€⁾ -k)ẈỊḄ‘ƲĿ
Ḣ,2KƊÇE?

```

Try it online!

A full program that takes a list of two strings as its argument and implicitly outputs the mashed up country name.

The handling of hyphens is relatively costly, particularly since they are included whichever side of the split they fall.

## Explanation

### Helper link 1

Handles case where both countries have multiple words

```
              )         | For each country:
J                       | - Sequence along words
 Ṗ                      | - Remove last
  X                     | - Pick one at random
   Ṭ                    | - Convert to a boolean list with a 1 at that index
    k⁸                  | - Split list of words after that point
            ƭ           | - Alternate between:
      Ḣ                 |   - Head (first set of words for the first country)
           Ʋ            |   - Following as a monad (for the second country)
       Ḣ                |     - Head (first set of words, also removed from the country)
        F               |     - Flatten
         Ṫ              |     - Tail (i.e. last character which will be space or hyphen)
          ;             |     - Concatenate to remaining words for second country
             F          | - Flatten
                      $ | Following as a monad
               j     $  | - Join countries with following as a monad
                ṪḢƭ€    |   - Alternate between tail for first country and head for second
                    Ṁ   |   - Max (will be hyphen if one present, otherwise space)

```

### Helper link 2

Handles case where only first country has multiple words

```
Ḣ   | Head (first country)
 Ṗ  | Remove last word
  ; | Concatenate to second country

```

### Helper link 3

Handles case where only second country has multiple words

```
Ṫ      | Tail (second country)
    Ɗ  | Following as a monad:
 Ḣ     | - Head (first word; note this will also be removed from the first country)
  Ṫ    | - Tail (last character)
   ;   | - Concatenated to remaining words
     ṭ | Tag onto the end of the first country

```

### Helper link 4

Handles case where both countries have single words

```
              ) | For each country
F               | - Flatten (remove the layer of lists generated in helper link 5)
 e€Øc           | - Check whether each character is a vowel
     Ṗ          | - Remove last
      T         | - Comvert to list of indices
       X        | - Pick one at random
        Ṭ       | - Convert to a boolean list with a 1 at that index
         kḢ     | - Split the original country name after that vowel
           ḢṪƭ  | - Alternate between taking the head (for first country) and tail (for second)

```

### Helper link 5

Splits each country into words and dispatched to helper links 1-4 depending on which countries have multiple words

```
      )       | For each country:
e€⁾ -         | - Check whether each character is a space or hyphen
     k        | - Split country after those characters
           ƲĿ | Call the link indicated by the number calculated by the following monad:
       Ẉ      | Lengths of lists (i.e. number of words in each country)
        Ị     | Insignificant (abs(x)<=1)
         Ḅ    | Convert from binary
          ‘   | Increment by one

```

### Main link

Determines if countries are equal, and otherwise calls helper link 5

```
      E? | If both countries equal:
    Ɗ    | Then, as a monad:
Ḣ        | - Head (first country)
 ,2      | - Pair with 2
   K     | - Join with spaces
     Ç   | Else: Call helper link 5

```
> 6 votes

# Answer
# Python 2, ~~395~~ ~~332~~ ~~336~~ ~~318~~ 313 bytes

```
def f(c,d):
 j,k=[' -'['-'in s]for s in c,d];u=c.split(j);v=d.split(k);n,m=len(u),len(v);D=max(j,k);b=D in c+d
 if(n>1)^(m<2):i,j=[choice([i+1for i in range(len(s)-1)if s[i]in['aeiouAEIOU',' -'][b]])for s in c,d];R=c[:i-b]+b*D+d[j:]
 else:R=D.join((u[:-1]or u)+v[m>1:])
 return[R,c+' 2'][c==d]
from random import*

```

Try it online!

17 bytes thx to Value Ink; and a hat tip to SztupY for pointing out a bug.
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 242 bytes

```
a=>b=>a==b?a+" 2":((d=a.LastIndexOfAny(z=((j=new[]{a,b}.Count(x=>"- ".Any(x.Contains)))>0?"- ":"aeiouAEIOU").ToArray()))<0?a:a.Remove(d+1))+b.Remove(0,j+new Random().Next()>0?(d=b.IndexOfAny(z)-j%2+1)<0?0:d:b.LastIndexOfAny(z));dynamic z,d,j;

```

Try it online!
> 3 votes

# Answer
# Lua, ~~614~~ ~~604~~ ~~600~~ 585 bytes

```
g,s,y,e={},{},{}r=math.random for _,v in ipairs({A,B})do c=0 for w in v:gmatch(".?.'?%a+.")do c=c+1(_<2 and g or s)[c]=w end end h=s[1]:find('-')and'-'or' 'u,k=#g,#s if u==1 and k>1then s[1]=g[1]..h e=s elseif u>1 and k==1then g[u]=s[1]e=g elseif u>1 and k>1then c=0 for i=1,r(u-1)do c=c+1y[c]=g[i]end for j=r(2,k),k do y[c]=y[c]:gsub(' ',h)c=c+1y[c]=s[j]end e=y else g,s={},{}for i=1,10 do t=("aeiouAEIOU"):sub(i,i)p=A:sub(1,A:find(t)or 0)g[#g+1]=#p>0 and#p<#A and p or q;p=B:sub(1+(B:find(t)or#B),#B)s[#s+1]=#p>0 and p or q end e={g[r(1,#g)],s[r(#s)]}end return A==B and{A," 2"}or e

```

Try it online!

**All possible combinations (75532)** --\> Click!
> 3 votes

# Answer
# Ruby, ~~230~~ 228 bytes

```
->c,d{g=->s,r{(0..s.size-2).select{|i|s[i]=~r}.sample}
i=g[c,e=/[ -]/];j=g[d,e];c==d ?c+" 2":(c+d)[e]?c[e]&&!d[e]?c[/.*[ -]/]+d:!c[e]&&d[e]?c+d[/[ -].+/]:c[0,i]+[c[i],d[j]].max+d[j+1..-1]:c[0..g[c,r=/[aeiou]/i]]+d[g[d,r]+1..-1]}

```

Try it online!
> 1 votes

# Answer
# Retina, 146 bytes

```
'

^(.+)¶\1$
$1 2
/^\w+¶\w+$/&%@/(?<=[aeiou])\B/i%`$
X
/\W.+¶.+\W/&%@/\W/%`$
X
¶.*?X|X(-?).*
$1
-\W
-
/\W.+¶\w+$/&`\w+¶

/^\w+¶.+\W/&`¶\w+

dI
d'I

```

Try it online!

Test suite

**Explanation**

```
'

- - -
dI
d'I

```

Since `Côte d'Ivoire` is a special case, remove the apostrophe at the start and insert it back in at the end.

```
^(.+)¶\1$
$1 2

```

If a country is repeated, just append the `2`

```
/^\w+¶\w+$/&%@/(?<=[aeiou])\B/i%`$
X

```

*If the counties are both single words*:

Choose a vowel at random (but not at the end) from each country's name and insert an `X` after it.

```
/\W.+¶.+\W/&%@/\W/%`$
X

```

*If the counties are both multiple words*:

Choose a space or `-` at random from each country's name and insert an `X` before it.

```
¶.*?X|X(-?).*
$1
-\W
-

```

Remove everything after the `X` from the first country and everything before the `X` from the second country.

If either country was split at a `-` we need to preserve it, which makes this part a bit longer.

```
/\W.+¶\w+$/&`\w+¶

/^\w+¶.+\W/&`¶\w+

```

If one country has multiple words and the other is a single word, replace the first/last word of the multi-word country with the single word one.
> 1 votes

---
Tags: code-golf, text-processing
---


title: Correct errors using Hamming(7,4)

text:
# Question
Title: Correct errors using Hamming(7,4)
The Hamming(7,4) code goes back to 1950. Back then Richard Hamming worked as a mathematician at Bell Labs. Every Friday Hamming set the calculating machines to perform a series of calculation, and collected the results on the following Monday. Using parity checks, these machines were able to detect errors during the computation. Frustrated, because he received error messages way too often, Hamming decided to improve the error detection and discovered the famous Hamming codes.

## Mechanics of the Hamming(7,4)

The goal of Hamming codes is to create a set of parity bits that overlap such that a single-bit error (one bit is flipped) in a data bit or a parity bit can be detected and corrected. Only if there occur multiple errors, the Hamming code fails of recovering the original data. It may not notice an error at all, or even correct it falsely. Therefore in this challenge we will only deal with single-bit errors.

As an example of the Hamming codes, we will look at the Hamming(7,4) code. Additionally to 4 bits of data `d1, d2, d3, d4` it uses 3 parity bits `p1, p2, p3`, which are calculated using the following equations:

```
p1 = (d1 + d2 + d4) % 2
p2 = (d1 + d3 + d4) % 2
p3 = (d2 + d3 + d4) % 2

```

The resulting codeword (data + parity bits) is of the form `p1 p2 d1 p3 d2 d3 d4`.

Detecting an error works the following way. You recalculate the parity bits, and check if they match the received parity bits. In the following table you can see, that every variety of a single-bit error yields a different matching of the parity bits. Therefore every single-bit error can be localized and corrected.

```
error in bit | p1 | p2 | d1 | p3 | d2 | d3 | d4 | no error
-------------|---------------------------------------------
p1 matches   | no | yes| no | yes| no | yes| no | yes
p2 matches   | yes| no | no | yes| yes| no | no | yes
p3 matches   | yes| yes| yes| no | no | no | no | yes

```

## Example

Let your data be `1011`. The parity bits are `p1 = 1 + 0 + 1 = 0`, `p2 = 1 + 1 + 1 = 1` and `p3 = 0 + 1 + 1 = 0`. Combine the data and the parity bits and you get the codeword `0110011`.

```
data bits   |   1 011
parity bits | 01 0
--------------------
codeword    | 0110011

```

Lets say during a transmission or a computation the 6th bit (= 3rd data bit) flips. You receive the word `0110001`. The alleged received data is `1001`. You calculate the parity bits again `p1 = 1 + 0 + 1 = 0`, `p2 = 1 + 0 + 1 = 0`, `p3 = 0 + 0 + 1 = 1`. Only `p1` matches the parity bits of the codeword `0110001`. Therefore an error occurred. Looking at the table above, tells us that the error occurred in `d3` and you can recover the original data `1011`.

## Challenge:

Write a function or a program, that receives a word (7 bits), one of the bits might be wrong, and recover the original data. The input (via STDIN, command-line argument, prompt or function argument) format may be a string `"0110001"`, a list or an array `[0, 1, 1, 0, 0, 0, 1]` or an integer in MSB `0b0110001 = 49`. As described above, the order of the input is `p1 p2 d1 p3 d2 d3 d4`. The output (via return value or STDOUT) has to be of the same format, but in the order `d1 d2 d3 d4`. Only return/output the 4 data bits.

This is code-golf. Therefore the shortest code wins.

## Test cases:

```
1110000 -> 1000  # no error
1100000 -> 1000  # error at 1st data bit
1111011 -> 1111  # error at 2nd data bit
0110001 -> 1011  # error at 3rd data bit (example)
1011011 -> 1010  # error at 4th data bit
0101001 -> 0001  # error at 1st parity bit
1010000 -> 1000  # error at 2nd parity bit
0100010 -> 0010  # error at 3rd parity bit

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45684;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

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

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

# Answer
# Octave, ~~70~~ ~~66~~ 55 bytes

This function `F` is setting up the decoding matrix `H`, finding the error and correcting the position of the error (if there is one). Then it is returning the right data bits. Input is a standard row vector.

@Jakube suggested I should use Octave instead of Matlab where you *can* use indices on expressions, which makes the whole thing again shorter 11 bytes:

```
F=@(c)xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2)))([3,5:7])

```

Following is the shortest solution in *Matlab*, as you cannot directly use indexing on expressions. (This works in Octave too, of course.) Was able to replace addition/mod2 with `xor`:

```
f=@(c)c([3,5:7]);F=@(c)f(xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2))))

```

Old:

```
f=@(c)c([3,5:7]);F=@(c)f(mod(c+(1:7==bi2de(mod(c*de2bi(1:7,3),2))),2))

```
> 6 votes

# Answer
# Piet 50x11 = 550

codel size is 15. Not too concerned about size, but it passed all the tests.
> 14 votes

# Answer
# Python, 79

```
f=lambda x,n=0,e=3:e&~-e and f(x,n+1,(n&8)*14^(n&4)*19^(n&2)*21^n%2*105^x)or~-n

```

Take input and output as numbers with the least significant bit on the right.

Instead of attempting error recovery, we just try encoding every possible message `n` from 0 to 15 until we get an encoding that's one bit away from what's given. The recursion keeps incrementing `n` until it finds one that works and returns it. Though there's no explicit termination, it must end within 16 loops.

The expression `(n&8)*14^(n&4)*19^(n&2)*21^n%2*105` implements the Hamming matrix bitwise.

To check for a single error, we xor the given message with a computed one to get `e`, and check if it's a power of two (or 0) with the classic bit-trick `e&~-e==0`. But, we can't actually assign to the variable `e` within a lambda, and we refer to it twice in this expression, so we do a hack of passing it as an optional argument to the next recursive step.
> 8 votes

# Answer
# JavaScript (ES6), ~~92~~ ~~87~~ 81

Function getting and returning an integer in MSB.
The implementation is straightforwrd following @randomra comment:

* calc p3wrong|p2wrong|p1wrong (line 2,3,4)
* use it as a bit mask to flip the incorrect bit (line 1),
* then return just the data bits (last line)

```
F=w=>(w^=128>>(
  (w^w*2^w*4^w/2)&4|
  (w/8^w^w*2^w/16)&2|
  (w/16^w/4^w^w/64)&1
))&7|w/2&8

```

**Test** In Frefox/FireBug console

```
;[0b1110000,0b1100000,0b1111011,0b0110001,
0b1011011,0b0101001,0b1010000,0b0100010]
.map(x=>x.toString(2)+'->'+F(x).toString(2))

```

*Output*

```
["1110000->1000", "1100000->1000", "1111011->1111", "110001->1011", "1011011->1010", "101001->1", "1010000->1000", "100010->10"]

```
> 7 votes

# Answer
# Python 2, 71

```
f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0%*3<CLUZfip'else f(i^b/2,b*2)

```

Several characters are unprintable ASCII so here is an escaped version:

```
f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0\x0f\x16\x19%*3<CLUZfip\x7f'else f(i^b/2,b*2)

```

Input and output to the function are done as integers.

I'm taking advantage of the fact that the number of valid messages is only 16, and hard-coding them all. Then I try flipping different bits until I get one of those.
> 4 votes

# Answer
# Haskell, 152 bytes

```
a(p,q,d,r,e,f,g)=b$(d+e)#p+2*(d+f)#q+4*(e+f)#r where b 3=(1-d,e,f,g);b 5=(d,1-e,f,g);b 6=(d,e,1-f,g);b 7=(d,e,f,g-1);b _=(d,e,f,g);x#y=abs$(x+g)`mod`2-y

```

Usage: `a (1,1,1,1,0,1,1)` which outputs `(1,1,1,1)`

Straightforward solution: if `p<x>` does not match, set bit `<x>` in a number. If this number is `3`, `5`, `6` or `7`, flip the corresponding `d<y>`.
> 3 votes

# Answer
# IA-32 machine code, 36 bytes

Hexdump:

```
33 c0 40 91 a8 55 7a 02 d0 e1 a8 66 7a 03 c0 e1
02 a8 78 7a 03 c1 e1 04 d0 e9 32 c1 24 74 04 04
c0 e8 03 c3

```

Equivalent C code:

```
unsigned parity(unsigned x)
{
    if (x == 0)
        return 0;
    else
        return x & 1 ^ parity(x >> 1);
}

unsigned fix(unsigned x)
{
    unsigned e1, e2, e3, err_pos, data;
    e1 = parity(x & 0x55);
    e2 = parity(x & 0x66);
    e3 = parity(x & 0x78);
    err_pos = e1 + e2 * 2 + e3 * 4;
    x ^= 1 << err_pos >> 1;
    data = x;
    data &= 0x74;
    data += 4;
    data >>= 3;
    return data;
}

```

x86 CPU automatically calculates the parity of each intermediate result. It has a dedicated instruction `jp` that jumps or not jumps depending on the parity.

It wasn't specified explicitly in the challenge, but the convenient property of hamming codes is that you can interpret the parity bits as a binary number, and this number indicates which bit was spoiled during transmission. Actually, this number is 1-based, with 0 meaning there were no transmission errors. This is implemented by shifting 1 left by `err_pos` and then right by `1`.

After fixing the transmission error, the code arranges the data bits in the needed order. The code is optimized for size, and it may be unclear at first how it works. To explain it, I denote by `a`, `b`, `c`, `d` the data bits, and by `P`, `Q` and `R` the parity bits. Then:

```
    data = x;     // d  c  b  R  a  Q  P
    data &= 0x74; // d  c  b  0  a  0  0
    data += 4;    // d  c  b  a ~a  0  0
    data >>= 3;   // d  c  b  a

```

Assembly source (`fastcall` convention, with input in `ecx`, and output in `eax`):

```
    xor eax, eax;
    inc eax;
    xchg eax, ecx;

    test al, 0x55;
    jp skip1;
    shl cl, 1;

skip1:
    test al, 0x66;
    jp skip2;
    shl cl, 2;

skip2:
    test al, 0x78;
    jp skip3;
    shl ecx, 4;

skip3:
    shr cl, 1;
    xor al, cl;

    and al, 0x74;
    add al, 4;
    shr al, 3;

    ret;

```
> 3 votes

# Answer
# APL (Dyalog Extended), ~~26~~ 25 bytes

```
(⊤⍳7)(3 5 6 7⊇⊢≠≠.∧∧.=⊣)⊢

```

Try it online!

-1 byte thanks to @Adám.

A bit shortened further using monadic .

---

# APL (Dyalog Unicode), ~~31~~ 30 bytes

```
⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7

```

Try it online!

-1 byte thanks to @Adám.

Full program that takes the boolean vector from stdin. Generalized matrix product `f.g` turns out to be *very* suitable for decoding Hamming code.

### How it works

```
⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7  ⍝ Full program
                       2⊥⍣¯1⍳7  ⍝ m←3×7 matrix of bit patterns of 1..7
                                ⍝ 0 0 0 1 1 1 1
                                ⍝ 0 1 1 0 0 1 1
                                ⍝ 1 0 1 0 1 0 1
⎕                        ⍝ Take the length-7 boolean vector v from stdin
 {                    }  ⍝ Pass to the inline function; ⍺←v ⋄ ⍵←m
                 ⍵≠.∧⍺   ⍝ Calculate parity for each row of m
            ⍵∧.=⍨        ⍝ Compute which column of m matches the error pattern
          ⍺≠  ⍝ Flip that bit from the codeword (or nothing if no error)
  (1<+⌿⍵)/    ⍝ Extract the data bits from the codeword

```
> 3 votes

---
Tags: code-golf, error-correction, coding-theory
---


title: Generate Hamming codes

text:
# Question
Title: Generate Hamming codes
Given a stream of bits, output the shortest possible Hamming code that encodes it.

The steps to generate the Hamming code are as follows, although your submission does not necessarily have to conform to them as long as it produces identical output. The input `110100101` will be used as an example.

1. Pad the input with trailing zeroes until its length is **2m \- m - 1** for some integer m.

```
110100101        becomes
11010010100

```
2. Insert spaces at every position with an index of **2i** (note that all indexing is 1-based for the purposes of this algorithm). This will insert **m** spaces for parity bits, resulting in **2m \- 1** bits total.

```
11010010100      becomes
__1_101_0010100

```
3. Fill in the parity bits. A parity bit at index **i** is calculated by taking the sum modulo 2 of all bits whose index **j** satisfies **i & j ≠ 0** (where **&** is bitwise AND). Note that this never includes other parity bits.

```
__1_101_0010100  becomes
111110100010100

```

Input may be taken as a list (or a string) of any two distinct elements, which do not necessarily have to be `0` and `1`. Output must be in an identical format. (Input or output as an integer with the corresponding binary representation is disallowed, as this format cannot express leading `0`s.)

The input will always have a length of at least 1.

Test cases (of the form `input output`):

```
0 000
1 111
01 1001100
1011 0110011
10101 001101011000000
110100101 111110100010100
00101111011 110001001111011
10100001001010001101 0011010100010010010001101000000

```

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

```
f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):[...Array(p)].map(_=>i&++i?~~a[i-1]:a.reduce((p,e,j)=>p^=++j&i&&e,0))

```

If the padding is unnecessary, then for 97 bytes:

```
f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):a.map(e=>i&++i?e:a.reduce((p,e,j)=>p^=++j&i&&e,0))

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 64 bytes

```
{u∨(~k)\⌽m≠.∧u←(⍵↑⍨g l)\⍨k←1<1⊥m←2⊥⍣¯1⍳¯1+2*l←⌈(g←2∘*-+∘1)⍣¯1≢⍵}

```

Try it online!

A dfn that takes a boolean vector as its right argument.

### Ungolfed with comments

```
f←{
  g←2∘*-+∘1  ⍝ A function that gives the data size from parity size; 2^x - (x+1)
  l←⌈g⍣¯1≢⍵  ⍝ Parity size from input length by inverting(⍣¯1) g
  m←2⊥⍣¯1⍳¯1+2*l  ⍝ Column matrix of bit patterns of 1..2^l-1
  k←1<1⊥m  ⍝ A boolean mask indicating where the data bits should go
  u←(⍵↑⍨g l)\⍨k  ⍝ Data pattern moved into appropriate positions:
     ⍵↑⍨g l      ⍝ Overtake ⍵ by length (g l)
            \⍨k  ⍝ Move the bits to the positions of 1 bits of k
  u∨(~k)\⌽m≠.∧u  ⍝ Complete the codeword:
          m≠.∧u  ⍝ Compute the parity (data AND each row of m, then reduce by XOR)
         ⌽       ⍝ Reverse so that LSB goes first
    (~k)\        ⍝ Fill in the parity positions with parity bits
  u∨             ⍝ Combine with data bits
}

```

# Answer
> 0 votes
# Mathematica, 332 bytes

```
R[n_,m_]:=Module[{a,l,i},i=n;If[i==0,a={0},a={};While[i>0,If[IntegerQ[i/2],PrependTo[a,0];i/=2,PrependTo[a,1];i=(i-1)/2]]];l=Length[a];Do[PrependTo[a,0],{i,m-l}];a];F[m_]:=Transpose@Table[R[i,m],{i,2^m-1}];F[m_,K_]:=Module[{Z,i,N,Y},Z=F[m];N=NullSpace[Z,Modulus->2];Y=Mod[Reverse@K.N,2]];Row@F[#,PadRight[IntegerDigits@#2,2^#-1-#]]&

```

Try it online : copy and paste code using ctrl+v, place input at the end of the code and hit shift+enter to run
(Wolfram-cloud will print "x" between digits but this doesn't happen in mathimatica)

**Input**

> \[4,10101\]

**Output**

> 001101011000000

**Input**

> \[5,10100001001010001101\]

**Output**

> 0011010100010010010001101000000

---
Tags: code-golf, binary, error-correction, coding-theory
---


title: Golf Me A Text-Editor

text:
# Question
Title: Golf Me A Text-Editor
# Golf Me a Text Editor

(similar challenges: Create a simple line editor and Line editor (more text here))

I seem to have forgotten which program to use to open, read, and write text files. Something like Noteleaf or VSBro or ... You see my conundrum. But never fear! I know some people who can write one. But I'm a bit limited on space, so shorter programs would be *much* appreciated.

## The Challenge

Create a program, in your language of choice, that can open, read, and write plaintext files. The program should take input from your language's equivalent of STDIN and write the contents of the file to STDOUT (or equivalent). The program should close the file after the user is done with it (when they type 'q'). If the file does not exist, then the program should create a new one with the given filename. Editing is done line-by-line. The user gives the line number they wish to edit, and then give the new content of that line. If there is no content given, the line should be removed. Additional specifications are listed below.

## Commands

`filename?>` \- opens the specified file. If a file with the given name can not be found, create a new file. If the user types `DELETE`, then the program should prompt with `delete?>`.
`delete?>` \- "deletes" the file. This is done by blanking it (i.e. replacing its contents with `""`), which will suffice for this challenge. If the file can not be found, then print `FILE NOT FOUND`.
`line?>` \- the given line number is where the text will be changed when `content?>` is given. If `q` is entered, then close the file and exit. If `a` is entered, then append a new empty line to the end of the file. If the index is out of bounds (i.e. does not exist (the text files can be `1` or `0` based indexed)) then print `Error!`.
`content?>` \- input that is given here will replace that of the previous content of the line given earlier (`line?>`). If empty then delete that line (remove content from the line and shift all lines after it up one).

After each `filename?>` and `content?>` the contents of the file should be printed, as well as `--` followed by the number of lines in the file.

## Examples

A (rather bad) example program in Python3 can be found here.

Example deletions:

```
filename?>DELETE
delete?>passwords.txt

```

```
filename?>DELETE
delete?>evidence.txt
FILE NOT FOUND

```

Example run:

```
filename?>passwords.txt
password
admin
1234
********
p@$$w0rd
c0d3_1$_l!f3
--
6
line?>3
content?>12345678
password
admin
12345678
********
p@$$w0rd
c0d3_1$_l!f3
--
6
line?>4
content?>
password
admin
12345678
p@$$w0rd
c0d3_1$_l!f3
--
6
line?>a
password
admin
12345678
p@$$w0rd
c0d3_1$_l!f3

--
7
line?>9
Error!

line?>1
content?>passcode
passcode
admin
12345678
p@$$w0rd
c0d3_1$_l!f3

--
7
line?>5
content?>
password
admin
12345678
p@$$w0rd

--
6
line?>q

```

Remember, this is , so the shortest answer in bytes wins!

# Answer
# Bash, ~~388~~ 375 characters

Note that I am aware that further clarifications may come which will invalidate my solution.
Feel free to carry out any necessary modification in the requirement.
I posted this because the challenge is complex and may help to see how someone else understood it when editing for clarification.

```
set -f
IFS=
read -pfilename?\> f
[ $f = DELETE ]&&{
read -pdelete?\> f
[ -f $f ]&&>$f||echo FILE NOT FOUND
exit
}
[ -f $f ]&&mapfile t<$f
echo "${t[*]}--"
while read -plineno?\> l;do
[ $l = q ]&&break
[ $l = a ]&&t+=('
')||{ ((l>=${#t[@]}))&&echo Error!&&continue
read -pcontent?\> c
[ $c ]&&t[l]="$c
"||t=(${t[@]::l} ${t[@]:l+1})
}
echo "${t[*]}--"
done
echo -n "${t[*]}">$f

```

Thanks to:

* GammaFunction for suggesting `set -f` to make some quoting unnecessary (13 characters).
> 3 votes

# Answer
# Zsh, 309 bytes

```
p(){print -l - "$t[@]" -- $#t}
read f'?filename?>'
[ $f = DELETE ]&&{
read f'?delete?>'
[ -f $f ]&&:>$f||echo FILE NOT FOUND
exit}
[ -f $f ]&&t=("${(@f)"$(<$f)"}")
p
while read l'?lineno?>'&&[ ${l/q} ];do
[ $l = a ]&&t+=('')||{((l&&l<=$#t))&&read c'?content?>'&&t[l]=($c);}||echo Error!
p
done
<<<${(F)t}>"$f"

```

Compared to Bash, we use `[` instead of `[[`, get rid of unnecessary quotes (although many are still necessary due to `$foo` expanding to no words if `foo` is empty. We take advantage of this with the `array[index]=(a list)` syntax to insert in a new line *unless* `$c` is empty, in which case `t[l]=()` deletes it.
> 1 votes

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