title: A Yoda-speaking challenge, this is

text:
# Question
Title: A Yoda-speaking challenge, this is
## The challenge

Well, I think it is quite clear, isn't it? You have to make a function or a program that takes a string as an argument and outputs the corrispondent Yoda-speaking.

This is , so least number of bytes wins.

## The input

The input could be **any** string without linefeed. You can translate a string if it is composed like this:

*Subject* \+ Verb + Something else.

Where *Subject* is a personal pronoun (I, you, he, she, it, we, they). You don't have to recognize that the second word is a verb.

If the first word isn't a pronoun, the input is valid but the output will be `Too difficult, this sentence is.`

```
You have to win this code challenge -> Translatable
Luke has to win this code challenge -> Untranslatable

```

Input can end with a letter, a . or a !, not with a ?.

Furthermore, strings can contain Non-Ascii, Parenthesis, commas, colons ...

## The output

In case of a translatable sentence, the output is the same sentence, with the subject and the verb at the end of the sentence.

```
You have to win this code challenge -> To win this code challenge, you have.

```

Comma, period and lower-case on the pronoun are mandatory. (Except, of course, if the pronoun is I).

As stated before, if it is untranslatable you have to output the string `Too difficult, this sentence is.`

## Examples

```
You have to win this code challenge -> To win this code challenge, you have.
He won this code challenge -> This code challenge, he won.  (I know this is not yoda-speaking, but I don’t want to overcomplicate this challenge)
I ate an ice cream earlier! -> An ice cream earlier, I ate.
I liked the Star Wars original trilogy more than the prequel’s one. -> The Star Wars original trilogy more than the prequel’s one, I liked.
I find your lack of faith disturbing -> Your lack of faith disturbing, I find.
I think we are done with the examples -> We are done with examples, I think.
He is your son, Vader -> Your son, Vader, he is.
I think they’ll add new features -> They’ll add new features, I think.
I made a fantastic code challenge (I hope) -> A fantastic code challenge (I hope), I made.
I love constants like π -> Constants like π, I love.

I’ll be the next President, I swear! -> Too difficult, this sentence is.
This challenge is great! -> Too difficult, this sentence is.
Is this challenge great? -> Too difficult, this sentence is.
Luke is not ready for this task -> Too difficult, this sentence is.
Somebody loves constants like π -> Too difficult, this sentence is.
[Empty string] -> Too difficult, this sentence is.

```

# Answer
# Retina, ~~162~~ ~~137~~ ~~145~~ ~~134~~ ~~131~~ 129

Multiple punctuation is now handled correctly. Test case: `You will not win this challenge...! -> Not win this challenge..., you will.`

Try it Online!

```
[.!]$

T`A-Z`a-z`^\w\w
G`^(I|we|you|s?he|it|they) \S+ \S
(\S+ \S+) (.*)
$2, $1.
T`a-z`A-Z`^.
^$
Too difficult, this sentence is.

```

Description:

If there is punctuation in the end, delete it.

```
[.!]$

^empty line

```

Transform the pronoun to lower case, except it is I.

```
T`A-Z`a-z`^\w\w

```

Filter out any line that does not match `<Pronoun><space><word><space><word>...`

```
G`^(I|we|you|s?he|it|they) \S+ \S

```

Split into `pronoun + verb`, `remainder`. Then rearrange.

```
(\S+ \S+) (.*)
$2, $1.

```

Transform the first character to upper case.

```
T`a-z`A-Z`^.

```

If the result is empty, it didn't pass the filter above. Print an error message.

```
^$
Too difficult, this sentence is.

```
> 17 votes

# Answer
# ES6, 212

This can probably a bit further golfed down:

```
i=>(r=/(you|s?he|it?|we|they)( \S+) ([^\.!?]+)/i.exec(i))?(c=(a,b)=>a[`to${['Low','Upp'][b]}erCase`]())(r[3].slice(0,1),1)+r[3].slice(1)+", "+c(r[1],+(/i/i.test(r[1])))+r[2]+".":"Too difficult, this sentence is."

```

JSFiddle (requires up-to-date browser like Chrome) or run it via node.js

Ungolfed:

```
i=>{
    r=/(you|s?he|it?|we|they)( \S+) ([^\.!?]+)/i.exec(i); //Main RegExp
    c=(a,b)=>a[`to${['Low','Upp'][b]}erCase`](); //shortcut for toUpperCase/toLowerCase
    if (r)
        return c(r[3].slice(0,1),1)+r[3].slice(1) + ", " //the "something else", properly formated
             + c(r[1], +(/i/i.test(r[1]))) //The subject lowercased except for "i" or "I"
             + r[2] + "."; //The End
    else //no match, no sentence to translate
        return "Too difficult, this sentence is.";
}

```
> 7 votes

# Answer
# JavaScript (ES6), 164 bytes

```
s=>([,p,,i,r]=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)?r[0].toUpperCase()+r.slice(1)+`, ${i?p:p.toLowerCase()}.`:"Too difficult, this sentence is."

```

## Explanation

It's almost painful how many bytes capitalising the first letter of a string takes in JavaScript...

```
s=>

  // Match and get specific parts of the input string
  ([,p,,i,r]=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)?

    r[0].toUpperCase()+r.slice(1)     // capitalise first letter
      +`, ${i?p:p.toLowerCase()}.`    // lower-case the pronoun (unless it is I)
  :"Too difficult, this sentence is."

```

## Test

Test does not use destructuring assignment to make it more cross-browser compatible.

```
var solution = s=>(p=s.match`^(((I)|You|He|She|It|We|They) \\S+) (.*?)[.!]?$`)?p[4][0].toUpperCase()+p[4].slice(1)+`, ${p[3]?p[1]:p[1].toLowerCase()}.`:"Too difficult, this sentence is."
```

```
<input type="text" id="input" value="I love constants like π...!" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 6 votes

# Answer
## Python, 261 bytes

```
import re
def a(b):
 if b[-1:]in".!":
  b=b[:-1]
 if re.match('(I|YOU|S?HE|IT|WE|THEY) \w+ \S+',b.upper()):
  b=(b+',').split()
  if b[0]!="I":
   b[0]=b[0].lower()
  b=" ".join(b[2:]+b[:2])
  return b[0].upper()+b[1:]
 return "Too difficult, this sentence is."

```

Turns out Python doesn't mind things like `b[-1]in".!"` Next I'll play with the match object more, if no-one beats me to it :)
> 3 votes

# Answer
# Python, ~~218~~ ~~217~~ 204 bytes

Not sure if this can be further golfed down.

```
def f(s):t=s.split();u=' '.join(t[2:]).rstrip('!.');return['Too difficult, this sentence is.','%s, %s %s.'%(u[0].upper()+u[1:],['I',t[0].lower()][t[0]!='I'],t[1])][t[0]in'I We You He She It They'.split()]

```

Ungolfed:

```
def f(s):
    t = s.split()
    u = ' '.join(t[2:]).rstrip('!.')
    return [
        'Too difficult, this sentence is.',
        '%s, %s %s.' % (u[0].upper() + u[1:],
                        ['I', t[0].lower()][t[0] != 'I'],
                        t[1])
    ][t[0] in 'I We You He She It They'.split()]

```
> 2 votes

# Answer
# GNU sed, 129 bytes

I'm including +1 byte for the `-r` flag.

```
#!/bin/sed -rf

/^I /b
s/^(You|[HW]e|She|It|They) /\L&/
t
s/.*/Too difficult, this sentence is./p
d
:
s/[.!]$//
s/^([^ ]+ [^ ]+) (.*)/\u\2, \1./

```

### Explanation

If we match a leading `I` we jump to the label:

```
/^I /b

```

If we match one of the other pronouns, we downcase it, then jump to the label:

```
s/^(You|[HW]e|She|It|They) /\L&/
t

```

Otherwise we print the failure message and move to the next input line:

```
s/.*/Too difficult, this sentence is./p
d

```

If we jumped to the label, we remove any final punctuation:

```
:
s/[.!]$//

```

and swap the first two words with the rest of the sentence, capitalising the new first word and adding the required punctuation as we do so:

```
s/^([^ ]+ [^ ]+) (.*)/\u\2, \1./

```
> 1 votes

---
Tags: code-golf, natural-language
---


# Question
Title: Draw a Christmas Star / Stellated Dodecahedron
Paper stars are a big thing in my family at christmas, so I thought a virtual one would be cool.

Below is an image of a **regular dodecahedron** (from https://en.wikipedia.org/wiki/Dodecahedron, attributed to the author mentioned there.)

The process of stellation (wikipedia) when applied to a polyhedron involves extending the faces until they cross other faces. Thus starting with the regular dodecahedron, we obtain the following shapes:

**Small Stellated Dodecahedron, Great Dodecahedron and Great Stellated Dodecahedron**

Image from http://jwilson.coe.uga.edu/emat6680fa07/thrash/asn1/stellations.html

These are the three possible Stellations of the dodecahedron (Wolfram). They form a natural progression from the dodecahedron, to the small stellated dodecahedron, great dodecahedron and great stellated dodecahedron, as we extend the faces further and further out.

**Task**

Your program or function should display or output to an image file one of the following polyhedra: **Regular dodecahedron, Small stellated dodecahedron, Great dodecahedron or Great Stellated Dodecahedron**.

The colour scheme should be as the second image above. Each of the six pairs of opposite faces shall be one of the six colours Red, Yellow, Green, Cyan, Blue, and Magenta. You may use default colours with these names in your language or its documentation, or use the colours FF0000, FFFF00, 00FF00, 00FFFF, 0000FF, and FF00FF (you may tone these down by reducing the intensity to a minimum of 75% if desired, for example by reducing the F's to C's.)

Note that we define a "face" as being all areas in the same plane. Thus in the images above the front face is yellow (and the parallel back face would also be yellow.)

Background should be black, grey, or white. Edges may be omitted, but should be black if drawn.

**Rules**

The displayed polyhedron must be between 500 and 1000 pixels in width (width is defined as the maximum distance between any two displayed vertices.)

The displayed polyhedron must be in perspective projection (viewpoint at least 5 widths away from the polyhedron), or orthographic projection (effectively a perspective projection with the viewpoint at infinity).

The polyhedron must be displayable from any angle. (It is not acceptable to pick the easiest possible angle and making a hardcoded 2D shape.) The angle can be specified by the user in either of the following ways:

1. Input of three angles corresponding to three rotations, from stdin, or as function or commandline parameters. These can be either Euler angles (where the first and last rotations are about the same axis) or Tait-Bryan angles (where there is one rotation each about the x, y and z axis) https://en.wikipedia.org/wiki/Euler\_angles (simply put, anything goes so long as each rotation is about the x, y, or z axis and consecutive rotations are about perpendicular axes.)
2. Facility for the user to rotate the polyhedron in steps of not more than 10 degrees about the x and y axes and refresh the display, any arbitrary number of times (assuming z axis perpendicular to the screen).

The polyhedron must be solid, not wireframe.

No builtins for drawing polyhedra are allowed (I'm looking at you, Mathematica!)

**Scoring**

This is codegolf. Shortest code in bytes wins.

Bonuses

Multiply your score by 0.5 if you do not use builtins for 3D drawing.

Multiply your score by 0.7 if you can display all three of the stellations of the dodecahedron, selectable by the user by an integer 1-3 entered from stdin, or by function or commandline parameter.

If you go for both bonuses your score will be multiplied by 0.5\*0.7=0.35

**Useful info (sources as below)**

https://en.wikipedia.org/wiki/Regular\_dodecahedron

https://en.wikipedia.org/wiki/Regular\_icosahedron

The dodecahedron has 20 vertices. 8 of them form the vertices of a cube with the following cartesian (x,y,z) coordinates:

(±1, ±1, ±1)

The remaining 12 are as follows (phi is the golden ratio)

(0, ± 1 / φ , ±φ)

(± 1 / φ , ±φ, 0)

(±φ, 0, ± 1 / φ )

The convex hull of the small stellated dodecahedron and great dodecahedron is obviously a regular dodecahedron. The outer vertices describe an icosahedron.

According to Wikipedia an icosahedron's 12 vertices can be described in a similar manner as cyclic permutations of (0, ±1, ±φ). The outer vertices of the small stellated dodecaheron and great dodechahedron (on the same scale as the dodecahedron above) form a larger icosahedron, where the coordinates of the vertices are cyclic permutations of (0, ±φ^2, ±φ).

The angles between faces for the dodecahedron and icosahedron are 2 arctan(phi) and arccos(-(√5)/3) respectively.

For tips on rotating, see https://en.wikipedia.org/wiki/Rotation\_matrix

**EDIT: By mistake I have allowed the regular dodecahedron, and can't retract it now. The x0.7 bonus for drawing all three of the stellated polyhedra remains. On New Year's Day I will issue a bounty of 100 for the answer that can display the most of the four polyhedra, with shortest code as the tie break.**

# Answer
> 3 votes
## Mathematica, ~~426~~ 424 bytes

```
Graphics3D[{Red,Yellow,Green,Cyan,Blue,Magenta}~Riffle~(a=Partition)[Polygon/@Uncompress@"1:eJxtkjEKwkAURNeoySYgeAVP4QFsrcTGTiyUBcEith7A2wgKgpVH8/vgs2TYZmAyw9/5k784XDbHVwihnxisU39N9SiEdI8GO/uWHpXBtjFAgJ7HToFl5WabEdJ+anCqDb6dU9RP65NR59EnI0CZDAWYjFmomBmPCn3/hVVwc9s4xYd66wYqFJVvhMz75vWlHIkhG2HBDJ1V3kYps7z7jG6GomIu/QUJKTGkdtlX2pDM8m6pydyzHIOElBhyG6V9cxulzPldaVJ6lpuUkKUTzWcm+0obkrn0f3OT0rMc0jDkD37nlUo="~a~3~a~5,2],Boxed->1<0]

```

Uses the built-in `Graphics3D` to display the shape. Most of the bytes are taken up by the compressed vertex locations, however, which are then `Partition`ed into a form usable by `Polygon`. Finally:

Note that this shape can be rotated by clicking and dragging.

# Answer
> 3 votes
# Python 2.7, 949 bytes

Here is the solution for the regular dodecahedron plotted using matplotlib. The rough outline for the ungolfed code (not shown here) was is outlined below:

* Make vertices Make edges (based on 3 nearest neighbours, module scipy.spatial.KDtree)
* Make faces based on graph cycles with length 5 (module networkx)
* Make facenormals (and select those with outward facing normal, numpy.cross)
* Generate coloring based on face normals
* Plotting using matplotlib

> ```
> import itertools as it
> import numpy as np
> from mpl_toolkits.mplot3d.art3d import Poly3DCollection
> import matplotlib.pyplot as plt
> v=[p for p in it.product((-1,1),(-1,1),(-1,1))]
> g=.5+.5*5**.5
> v.extend([p for p in it.product((0,),(-1/g,1/g),(-g,g))])
> v.extend([p for p in it.product((-1/g,1/g),(-g,g),(0,))])
> v.extend([p for p in it.product((-g,g),(0,),(-1/g,1/g))])
> v=np.array(v)
> g=[[12,14,5,9,1],[12,1,17,16,0],[12,0,8,4,14],[4,18,19,5,14],[4,8,10,6,18],[5,19,7,11,9],[7,15,13,3,11],[7,19,18,6,15],[6,10,2,13,15],[13,2,16,17,3],[3,17,1,9,11],[16,2,10,8,0]]
> a=[2,1,0,3,4,5,0,1,2,3,4,5]
> fig = plt.figure()
> ax = fig.add_subplot((111),aspect='equal',projection='3d')
> ax.set_xlim3d(-2, 2)
> ax.set_ylim3d(-2, 2)
> ax.set_zlim3d(-2, 2)
> for f in range(12):
>  c=Poly3DCollection([[tuple(y) for y in v[g[f],:]]], linewidths=1, alpha=1)
>  c.set_facecolor([(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0)][a[f]])
>  ax.add_collection3d(c)
> ax.auto_scale_xyz
> plt.show()
>
> ```

# Answer
> 3 votes
# Ruby, 784 bytes * 0.5 * 0.7 = 274.4

**My own answer, therefore not eligible for my bounty.**

Eligible for both the non-3D builtin bonus and the drawing all stellations bonus.

```
->t,n{o=[]
g=->a{a.reduce(:+)/5}
f=->u,v,w,m{x=u.dup;y=v.dup;z=w.dup
15.times{|i|k,l=("i".to_c**(n[i/5]/90.0)).rect
j=i%5
x[j],y[j],z[j]=y[j],x[j]*k+z[j]*l,z[j]*k-x[j]*l}
p=g[x];q=g[y];r=g[z]
a=[0,1,-i=0.382,-1][t]*e=r<=>0
b=[j=1+i,0,j,j][t]*e
c=[-i*j,-i,1,i][t]*e
d=[j*j,j,0,0][t]*e
5.times{|i|o<<"<path id=\"#{"%9.0f"%(z[i]*a+r*b+(z[i-2]+z[i-3])*c+2*r*d+999)}\"
d=\"M#{(x[i]*a+p*b)} #{(y[i]*a+q*b)}L#{(x[i-2]*c+p*d)} #{(y[i-2]*c+q*d)}L#{(x[i-3]*c+p*d)} #{(y[i-3]*c+q*d)}\"
fill=\"##{m}\"/>"}}
a=233
b=377
z=[0,a,b,a,0]
y=[a,b,0,-b,-a]
x=[b,0,-a,0,b]
w=[-b,0,a,0,-b]
f[x,y,z,'F0F']
f[w,y,z,'0F0']
f[y,z,x,'00F']
f[y,z,w,'FF0']
f[z,x,y,'F00']
f[z,w,y,'0FF']
s=File.open("p.svg","w")
s.puts'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-450 -450 900 900">',o.sort,'</svg>'
s.close}

```

**Input as function parameters**

An integer 0..3 corresponding to regular dodecahedron, small stellated dodecahedron, great stellated dodecahedron

An array of three integers corresponding to degree angles for rotations about the x, y and x (again) axes (proper Euler angles, enabling any rotation to be achieved.)

**Output** a file `p.svg` that can be displayed in a web browser.

**Explanation**

the arrays x,y,z at the bottom of the code contain the coordinates of the outer points of one face of a small stellated dodecahedron. This can be inscribed in the icosahedron whose 12 vertices are defined by the cyclic permutations of (+/-377,+/-233,+/-0). Note that 377 and 233 are consecutive Fibonacci numbers and therefore 377/233 is an excellent approximation to the golden ratio.

an additional array w contains the x coordinates multiplied by -1, equivalent to reflection in the x plane. Function f is called 6 times, once for each colour, with the different cyclic permutations of x,y,z and w,y,z.

The three rotations are passed as parameters in n\[\]. to use sin and cos in Ruby, it is necessary to do `include Math`. to avoid this, the cosine and sine of the angle are obtained by raising the square root of -1 `"i"` to a power of (angle in degrees / 90) The real and imaginary parts of this number are stored in k (cosine) and l (sine)

Prior to rotation, x and y values are exchanged. Then matrix multiplication is applied to the y and z values to give a rotation about the x axis. The exchanging of values enables the three rotations to be carried out in a loop.

So far, we only have one ring of points. To obtain the rest, we need to find the centre of the pentagon/star. This is done by finding the average of coordinates of the 5 vertices, which are stored in p,q,r.

As mentioned before, only one function call per colour is made. The sign of r (the average of the z coordinates, and therefore the coordinate of the face) is tested. If it is positive, the face is a front face and therefore visible. If it is negative, the face is a back face. It is invisible, and we have no function call for the opposite face. Therefore, all three coordinates must be inverted. The sign of r is stored in e to facilitate this.

The face is constructed of 5 triangles, whose vertices are linear combinations of the outer vertices of the small stellated dodecahedron and the centre of the face. In the case of the small stellated dodecahedron, for the tips of the triangles we set a=1 and b=0 (contribution 1 from x,y,z and 0 from p,q,r). For the 2 base vertices of the triangle we set c=-0.382 (contribution 1/golden ratio^2 from x,y,z) and d=1.382 (contribution from p,q,r.) The reason for the negative contribution is that the base vertices of the triangle are defined in terms of the opposing tips, which are on the opposite side of the face. The obtained coordinates are multiplied by e as necessary.

The four unnamed arrays whose values are assigned to `a,b,c,d` contain the required values for the regular dodecahedron, small stellated dodecahedron, great dodecahedron and great stellated dodecahedron, selected according to variable `t` Note that for the small stellated dodecahedron and great dodecahedron, a+b=c+d=1. The relation a+b=c+d applies to the other shapes, but a different scale is applied.

A line of svg code is created for each triangle. This contains an ID derived from the sum of the z coordinates of the 3 vertices of the triangle, a description of the vertices of the three coordinates of the triangle, and a colour. note that we view straight down the z axis in orthographic projection. Thus 2D x = 3D x and 2D y = 3D y. The line is added to `h.`

finally, after all the function calls are finished, h is sorted so that the triangles of highest z value (in front) are plotted last, and the whole thing is saved as an svg file with the appropriate header and footer text.

**Ungolfed in test program**

```
h=->t,n{                                              #t=type of polygon,n=angles of rotation
o=[]                                                  #array for output
g=->a{a.reduce(:+)/5}                                 #auxiliary function for finding average of 5 points

f=->u,v,w,m{x=u.dup;y=v.dup;z=w.dup                   #function to take 5 points u,v,w and plot one face (5 triangles) of the output in colour m

  15.times{|i|                                        #for each of 3 rotation angle and 5 points
    k,l=("i".to_c**(n[i/5]/90.0)).rect                #calculate the cos and sine of the angle, by raising sqrt(-1)="i" to a power
    j=i%5                                             #for each of the 5 points
    x[j],y[j],z[j]=y[j],x[j]*k+z[j]*l,z[j]*k-x[j]*l}  #swap x and y, then perform maxtrix rotation on (new) y and z.

  p=g[x];q=g[y];r=g[z]                                #find centre p,q,r of the face whose 5 points (in the case of small stellated dodecahedron) are in x,y,z

  e=r<=>0                                             #if r is positive, face is front. if negative, face is back, so we need to transform it to opposite face.
  a=[0,              1,    -0.382,    -1][t]*e        #contribution of 5 points x,y,z to triangle tip vertex coordinates
  b=[1.382,          0,     1.382,     1.382][t]*e    #contribution of centre p,q,r to triangle tip vertex coordinates
  c=[-0.528,        -0.382, 1,         0.382][t]*e    #contribution of 5 points x,y,z to coordinates of each triangle base vertex
  d=[1.901,          1.382, 0,         0][t]*e        #contribution of centre p,q,r to coordinates of each triangle base vertex

  5.times{|i|
  o<<"<path id=\"#{"%9.0f"%(z[i]*a+r*b+(z[i-2]+z[i-3])*c+2*r*d+999)}\"
d=\"M#{(x[i]*a+p*b)} #{(y[i]*a+q*b)}L#{(x[i-2]*c+p*d)} #{(y[i-2]*c+q*d)}L#{(x[i-3]*c+p*d)} #{(y[i-3]*c+q*d)}\"
fill=\"##{m}\"/>"}                                    #write svg code for this triangle
}

  a=233                                               #a,b =coordinate standard values
  b=377
  z=[0,a,b,a,0]                                       #z coordinates for one face of stellated dodecahedron
  y=[a,b,0,-b,-a]                                     #y coordinates
  x=[b,0,-a,0,b]                                      #x coordinates
  w=[-b,0,a,0,-b]                                     #alternate  x coordinates

  f[x,y,z,'F0F']                                      #call f
  f[w,y,z,'0F0']                                      #to plot
  f[y,z,x,'00F']                                      #each
  f[y,z,w,'FF0']                                      #face
  f[z,x,y,'F00']                                      #in
  f[z,w,y,'0FF']                                      #turn

  s=File.open("p.svg","w")                            #sort output in o, plot front triangles last
  s.puts'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-450 -450 900 900">',o.sort,'</svg>'
  s.close                                             #add header and footer, and save as svg
}

t=gets.to_i
n=[]
3.times{n<<gets.to_i}
h[t,n]

```

**Output**

for small stellated dodecahedron (will add some images of the other polygons soon)

1,0,0,0 home position

1,30,0,0 rotate down 30 degrees

1,0,30,0 rotate right 30 degrees (note: for a perfect side view, the rotation would be `atan(1/golden ratio)`=31.7 degrees, hence we can still see a small sliver of blue)

1,0,20,0 rotate right 20 degrees

1,60,10,-63 rotate down, right and up (example of orientation only possible with 3 rotations)

0,30,0,0 regular dodecahedron

2,0,20,0 great dodecahedron

3,45,45,45 great stellated dodecahedron

---
Tags: code-golf, graphical-output, geometry
---


title: Find the Interwoven Source Codes (Cops)

text:
# Question
Title: Find the Interwoven Source Codes (Cops)
This is the cops' thread. For the robbers' thread, go here.

# Introduction

For this Cops/Robbers challenge, the cops will write output-producing programs and interweave them together. It is the robber's job to pick apart the cops' programs to produce the desired outputs.

# Cop rules

The cops may use up to 256 bytes total to write between 2 and 8 (inclusive) programs, all of which *must* produce some output. All programs written must be in the same language. The cops will "interweave" their programs together to make it harder for the robbers to figure out what the programs are.

Now for a description of interweaving. Consider the strings representing the different programs. The process of interweaving is the repeated pulling off of the first character of any of the programs and concatenating it to the end of a new string until no characters in any of the programs are left. For example, if two programs are `lion` and `TIGER`, a possible interweaving is `TIliGoEnR`. However, the programs cannot be scrambled in any way, so `RoITEnlGi` is not acceptable.

It should be noted that when the characters of all but one program are removed from the results of an interweaving, the remaining program would be shown intact. Removing the letters `TIGER` from `TIliGoEnR` results in `lion`.

All of the cops' programs and outputs must contain *only* printable ASCII characters (20-7E) and newlines. Programs must not contain errors and must run in 10 seconds on a reasonable machine. For any submission, there must be a free interpreter of the language somewhere. Adding comments to the submissions is not allowed, as are hashing and other forms of cryptography. Blank programs are not allowed (Sorry Stuck).

The cop will post the interweaved code, the language, the number of different programs used, and the output for each program. A big thanks to Martin for writing this CJam script to automatically interweave your programs.

Programs are deemed safe after one week has elapsed from the time of posting. At that point, the cops must post the individual programs in order to receive points.

# Scoring

There are two components that are added together when scoring a safe submission.

* 256 divided by the quantity 2 raised to the power of the number of programs used.
* Round the number of bytes in the interweaving **up** to the nearest power of 2 and divide it into 256.

For example, if the entry `TIliGoEnR` (9 bytes) were safe, it would receive 256/2^2+256/16=80 points.

When a cop's submission is cracked, the cop loses 16 points. The cop must indicate that their submission has been cracked.

The winner of the cops' challenge will be the person with the most points after a sufficient period of time for people to participate.

# Leaderboard

This is a work in progress that was adapted by intrepidcoder from this question.

To make sure that your answer shows up, please start your answer with a headline, using the **exact** Markdown template:

```
# Language Name, N programs, M bytes; Score ###/### (if safe/cracked)

```

Anything after a semicolon will be ignored, so you can put your score there.

If your submission is safe put a header like this:

```
# Language Name, safe, N programs, M bytes; Score ###

```

If it is cracked, put a header like this:

```
# Language Name, [cracked](link-to-crack), N programs, M bytes; Score -16

```

```
/* Configuration */

var QUESTION_ID = 64520; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author.
var SECONDSINDAY = 86400;
var SAFECUTOFFDAYS = 7;
var SORTBYTIME = true;
var SUBTRACTCRACKEDPOINTS = true;
var EXPIREDTIME = 1448232502000;

/* App */

var SAFE_REG = /<h\d>.*?[sS][aA][fF][eE].*<\/\h\d>/;
var POINTS_REG = /<h\d>.*(\d+)\s*program.*<\/h\d>/i; // /(?:<=|≤|<=)\s?(?:<\/?strong>)?\s?(\d+)/
// var POINTS_REG_ALT = /<h\d>.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var LENGTH_REG = /<h\d>.*?((\d+)\s*byte).*<\/h\d>/i;
var CRACKED_HEADER_REG = /<h\d>.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*<\/h\d>/;
var CRACKED_COMMENT_REG = /(.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*<a href=.*)|(.*<a href=.*[Cc][Rr][Aa][Cc][Kk][Ee][Dd].*)/
var OVERRIDE_REG = /^Override\s*header:\s*/i;
var LANGUAGE_REG = /<h\d>\s*(.+?),.*<\/h\d>/;
var LANGUAGE_REG_ALT = /<h\d>\s*(<a href=.+<\/a>).*<\/h\d>/
var LANGUAGE_REG_ALT_2 = /<h\d>\s*(.+?)\s.*<\/h\d>/;
var LANGUAGE_REG_ALT_3 = /<h\d>(.+?)<\/h\d>/;

var answers = [],
  answers_hash, answer_ids, answer_page = 1,
  more_answers = true,
  comment_page;

function answersUrl(index) {
  return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {

  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });

}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      data.items.forEach(function(c) {

        answers_hash[c.post_id].comments.push(c);

      });

      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {

  var valid = [];
  var open = [];

  answers.forEach(function(a) {

    var body = a.body.replace(/(<h\d>.*);.*(<\/h\d>)/,"$1$2"); // Ignore all text after a semicolon.
    var cracked = false;

    a.comments.forEach(function(c) {
      var was_safe = (c.creation_date + (SECONDSINDAY * SAFECUTOFFDAYS) > a.creation_date);
      if (CRACKED_COMMENT_REG.test(c.body) && !was_safe)
        cracked = true;
    });

    if (CRACKED_HEADER_REG.test(body)) cracked = true;

    // if (SUBTRACTCRACKEDPOINTS||!cracked) {

    var createDate = a.creation_date;
    var currentDate = Date.now() / 1000;
    var timeToSafe = (createDate + (SECONDSINDAY * SAFECUTOFFDAYS) - currentDate) / SECONDSINDAY;
    var SafeTimeStr = (timeToSafe > 2) ? (Math.floor(timeToSafe) + " Days") :
      (timeToSafe > 1) ? ("1 Day") :
      (timeToSafe > (2 / 24)) ? (Math.floor(timeToSafe * 24) + " Hours") :
      (timeToSafe > (1 / 24)) ? ("1 Hour") :
      "<1 Hour";

    var expired = createDate > (EXPIREDTIME);

    var safe = timeToSafe < 0;
    var programs = body.match(POINTS_REG);
    var length = body.match(LENGTH_REG);
    safe = safe && !cracked

    isOpen = !(cracked || safe);

    if (programs && length) {

      var safepoints = (256/Math.pow(2,parseInt(programs[1],10)) +
                    256/Math.pow(2,Math.ceil(Math.log2(parseInt(length[1],10)))));

      var crackedpoints = Math.pow(2, parseInt(programs[1],10),2) +
          Math.pow(2,Math.floor(Math.log2(parseInt(length[1],10))));

      valid.push({
        user: getAuthorName(a),
        numberOfSubmissions: (safe && !expired) ? 1 : 0,
        points: (safe && !expired) ? safepoints : 0,
        open: (isOpen && !expired) ? 1 : 0,
        cracked: (cracked && !expired) ? 1 : 0,
        expired: (expired) ? 1 : 0
      });

    }

    if ((isOpen || expired) && programs) {

      var language = body.match(LANGUAGE_REG);
      if (!language) language = body.match(LANGUAGE_REG_ALT);
      if (!language) language = body.match(LANGUAGE_REG_ALT_2);
      if (!language) language = body.match(LANGUAGE_REG_ALT_3);

      open.push({
        user: getAuthorName(a),
        safePts: programs ? safepoints : "???",
        crackedPts: programs ? crackedpoints : "???",
        language: language ? language[1] : "???",
        link: a.share_link,
        timeToSafe: timeToSafe,
        timeStr: (expired) ? "Challenge closed" : SafeTimeStr
      });
    }
    // }
  });

  if (SORTBYTIME) {
    open.sort(function(a, b) {
      return a.timeToSafe - b.timeToSafe;
    });
  } else {
    open.sort(function(a, b) {
      var r1 = parseInt(a.length);
      var r2 = parseInt(b.length);
      if (r1 && r2) return r1 - r2;
      else if (r1) return r2;
      else if (r2) return r1;
      else return 0;
    });
  }

  var pointTotals = [];
  valid.forEach(function(a) {

    var index = -1;
    var author = a.user;
    pointTotals.forEach(function(p) {
      if (p.user == author) index = pointTotals.indexOf(p);
    });

    if (index == -1) {
      if (SUBTRACTCRACKEDPOINTS && a.cracked) a.points -= 16;
      pointTotals.push(a);
    }
    else {
      pointTotals[index].points += a.points;
      pointTotals[index].numberOfSubmissions += a.numberOfSubmissions;
      pointTotals[index].cracked += a.cracked;
      pointTotals[index].expired += a.expired;
      pointTotals[index].open += a.open;
      if (SUBTRACTCRACKEDPOINTS && a.cracked) pointTotals[index].points -= 16;
    }

  });

  pointTotals.sort(function(a, b) {
    if (a.points != b.points)
      return b.points - a.points;
    else if (a.numberOfSubmissions != b.numberOfSubmissions)
      return b.numberOfSubmissions - a.numberOfSubmissions;
    else if (a.open != b.open)
      return b.open - a.open;
    else if (a.cracked != b.cracked)
      return a.cracked - b.cracked;
    else return 0;
  });

  pointTotals.forEach(function(a) {

    var answer = jQuery("#answer-template").html();
    answer = answer
      .replace("{{NAME}}", a.user)
      .replace("{{SAFE}}", a.numberOfSubmissions)
      .replace("{{OPEN}}", a.open)
      .replace("{{CLOSED}}", a.expired)
      .replace("{{CRACKED}}", a.cracked)
      .replace("{{POINTS}}", a.points);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

  });

  open.forEach(function(a) {
    var answer = jQuery("#open-template").html();
    answer = answer
      .replace("{{NAME}}", a.user)
      .replace("{{SAFE}}", a.safePts)
      .replace("{{CRACKED}}", a.crackedPts)
      .replace("{{LANGUAGE}}", a.language)
      .replace("{{TIME}}", a.timeStr)
      .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#opensubs").append(answer);
  });

}
```

```
body {
  text-align: left !important
}
#answer-list {
  padding: 10px;
  width: 350px;
  float: left;
}
#open-list {
  padding: 10px;
  width: 470px;
  float: left;
}
table thead {
  font-weight: bold;
  vertical-align: top;
}
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>Author</td>
        <td>Safe</td>
        <td>Open</td>

        <td>Cracked</td>
        <td>Late Entry</td>
        <td>Score</td>
      </tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>

<div id="open-list">
  <h2>Open submissions</h2>
  <table class="open-list">
    <thead>
      <tr>
        <td>Author</td>
        <td>Points if Safe</td>
        <td>Points if Cracked</td>
        <td>Language</td>
        <td>Time Remaining</td>
        <td>Link</td>
      </tr>
    </thead>
    <tbody id="opensubs">
    </tbody>
  </table>
</div>

<table style="display: none">
  <tbody id="answer-template">
    <tr>
      <td>{{NAME}}</td>
      <td>{{SAFE}}</td>
      <td>{{OPEN}}</td>

      <td>{{CRACKED}}</td>
      <td>{{CLOSED}}</td>
      <td>{{POINTS}}</td>

    </tr>
  </tbody>
</table>

<table style="display: none">
  <tbody id="open-template">
    <tr>
      <td>{{NAME}}</td>
      <td>{{SAFE}}</td>
      <td>{{CRACKED}}</td>
      <td>{{LANGUAGE}}</td>
      <td>{{TIME}}</td>
      <td><a target="_parent" href="{{LINK}}">Link</a>
      </td>
    </tr>
  </tbody>
</table>
```

# Answer
## Hexagony, 6 programs, 53 bytes; Score 8/96 (if safe/cracked)

```
  [&;//&z
 ;!X;!!/@!
@)6!< @[!.J
 @a5|9o;""
  |@!!!@]

```

Even if this goes safe, it will be very few points for me, but I thought I'd provide a nice puzzle for robbers to bank some points. :) I have no idea how easy or hard this actually is.

Here are the outputs:

```
Jazz

```

```
XX88XX88

```

```
1234562345610

```

```
111111111111111111111111

```

```
9999999999999999999999999999999999

```

```
66566565665656566565656566565656565665

```
> 19 votes

# Answer
# JavaScript, cracked, 2 programs, 110 bytes; Score -16

```
+(![]+!![])[[]+[]]+(![]+[])+[+[]]+(!![]+[])[[+[]]+[]]+(!![]+[])+[+[]]+(+(![]+!![])[])[+[]]+(![]+[])+[+[]](+[])

```

good luck with this one.

Note: I recommend running on a modern browser (basically not IE)

**Output, first program:**

```
ffttff

```

**Output, second program:**

```
1010

```
> 6 votes

# Answer
# CJam, safe, 2 programs, 250 bytes; Score 65

### Interweaved programs

```
"":9(x5M/Cle-Dn,1'AFjsQYirG3@+,~unY</CyUAJ!`L.Xkdq'hF_X&=-`!SnxM!hqv~'GW!4!qIfp$h,ld-;i0JM79Xs'orb@#+sE${?.Eet""""/4M.D:}~Cc^est+2]c9>^W<O%8rR(kg)(ra-P{^Fthm?WF[#KJfRxOe-5zYueb~SiX@tnFyb2-M}G8@0;Z.$u']Qc0R{\.M9V$_NyTc,HR]y""22{{''  ffmm9955bb\\}}****

```

### Output, first program

```
169004397811215505136757551914260640157209814479670875629464038264532260025741074366481672115039451444875174892900756838476896193165147376670615268045482935802126657286722969566601154866449492847343470441618498401

```

### Output, second program

```
236156588886135909534842810119847991195053526225488685859715966203756668582804035289768525426132740118856398404195457578486865119219669643999456580063310899697265496162944335336660228420754397359091438096239696929

```

## Solution

### First program

```
"9(M/l-n'FsQrG@~n<CyA`.XdhF&-`SMhq~W!qI$hd-0M7X'b#sE{Ee""/MD~c^s2]>^O%r(gra{FhmW#KfOezYbSi@Fy-}G0;$u]cR.9V_TcRy"2{' fm95b\}**

```

Try it online!

### Second program

```
":x5CeD,1AjYi3+,uY/UJ!Lkq'_X=!nx!v'G4!fp,l;iJ9sor@+$?.t""4.:}Cet+c9W<8Rk)(-P^t?F[JRx-5ue~Xtnb2M8@Z.'Q0{\M$Ny,H]"2{' fm95b\}**

```

Try it online!

### How it works

Both programs have this format:

```
 "…""…"2{' fm95b\}**

       2{        }*   Do the following twice:
         'fm            Subtract the char code of ' ' from each character.
            95b         Convert from base 95 to integer.
               \        Swap the two topmost stack elements.
                      This pushes two prime numbers on the stack.
                  *   Compute their product.

```

De-interweaving the programs should require either brute force or factoring the semi-primes.
> 4 votes

# Answer
# BitShift, cracked, 2 programs, 110 bytes; Score -16

### Interweaved programs

```
10011110011111001011101110110110110110011001100010110000010010011100101111000111100110111101011110011101001100

```

### Output, first program

```
! ?

```

### Output, second program

```
? !

```

I'm so sorry
> 4 votes

# Answer
# Java, cracked, 2 programs, 155 bytes; Score -16

### Interleaved programs

```
cliantsesr fai{pce ubc{stlaic sttatiic voidc  mavioin(Sd tmariinn(Stg[rin]g)g{Syst[em]n.)o{ut.prSiysntemtln.out.(prin"Hell"\u002bg.tlen(gth)"By;e!\n}")};}}

```

### Output, first program

```
Hell0

```

And trailing newline.

### Output, second program

```
Bye!

```

And trailing newline.

## Original programs

### First

```
class i{public static void main(String[]g){System.out.println("Hell"\u002bg.length);}}

```

### Second

```
interface c{static void main(String[]n){System.out.print("Bye!\n");}}

```
> 4 votes

# Answer
# Pyth, safe, 2 programs, 63 bytes; Score 68

### Interweaved programs

```
V8j5kIqlPN1[C7=3+Z1d=G"<"C38p5)IqdZ21=ZNB;C-jk[C9Zd\</.5n0T1dG2

```

### First program

Output:

```
 I <3 U

```

Program:

```
jk [C73d"<"3pdC-95T

j                   # Join
 k                  # Standard variable: ""
   [                # Creates a new list
    C73             # Char 73 = I
       d            # Standard variable: " "
        "<"         # String: "<"
           3        # Number 3
            pd      # Prints " ", the leading whitespace
              C     # Char
               -95T # -95T = 95 - 10 = 85. Char 85 = U

```

### Second program

Output

```
I <3 U2

```

Program:

```
V85IqlPN1=+Z1=GC85)IqZ21=ZNB;jk[CZd\</.n01dG2

                                              # implicit Z = 0
V85                                           # For N in range(85)
   I                                          # If
    qlPN1                                     # Length of the prime factors of N equals 1
         =+Z1                                 # Z = Z + 1
             =GC85                            # G = Char 85 = U
                  )                           # Ends the if statement
                   IqZ21                      # If Z equals 21(th prime)
                        =ZN                   # Z = N (73)
                           B                  # Break out of the for loop
                            ;                 # Infinite ), to close open parentheses
                             jk               # Join ""
                               [              # New list
                                CZ            # Char Z = Char 73 = I
                                  d           # Standard variable: " "
                                   \<         # Single character '<'
                                     /        # Floored division
                                      .n0     # Pi, 3.14159...
                                         1    # Divide by 1 and round down
                                          d   # Standard variable: " "
                                           G  # G = C85 = U
                                            2 # Number 2

```
> 4 votes

# Answer
# Befunge, Safe, 2 programs, 228 bytes; Score 65

## Interweaved programs

```
7b*2"!+:,l9ooa"v +2^*<>+:::v,v
  1- v2:,+9 -,\,,<$+":4b*,
v>"i g>:nb:"^,2$+,1'g#
+0^"gs "-*<  :-*,n,
v\,a3+v
-9*b6-3b ,*a<b:u,+|11 B'<
,:+>19v>,:'m+:9,:+3a^:,:a+"c*@9a, >': 'e^
<^;*+<v" gr"< ^
     >@,"+*or:\*:3pa, g"^0>'f^8<;

```

## Output, first program

```
Output, first program

```

## Output, second program

```
Befunge programming is cool!

```

I doubt this will be a easy one to crack. In fact you should just give up now. Who needs 132 points anyway?

## Answer

Program 1:

```
7b*2+:,9a+2*+:::,1-:,\5-,\,,4b*,v>::,2+,'+0g\1-:,\,3+v
-9*bb,,+1,:+1,:+9,:+3,:+c*9a,: '<^;    @,+*:\*:3a,g08<;

```

> Output, first program

Program 2:

```
"!loo"v ^<>vv
   v2+9 <$+":
>"i gnb"^$1g#
^"s "*<  -*n,
va6-3 *a<b:u|1 B'<
>9v>'m:a^:a"@ >'e^
*+<v"gr"<^
   >"orp "^>'f^

```

> Befunge programming is cool!
> 4 votes

# Answer
# Vitsy, cracked, 2 programs, 15 bytes; Score -16

### Interweaved Programs

```
a'5oF'2\\aI/NZO
```

Vitsy is so pretty, so clean. Look into its source, and be awed.

### Output, first program

```
NaNo
```

### Output, second program

```

```

That's 121 newlines.
> 4 votes

# Answer
# JavaScript (ES6), safe, 2 programs, 255 bytes; Score 65

### Interleaved programs

```
aalleerrtt((l=[](+(!l[=[l])+="(l "=l+[]l][[+l>=+1l]]=l+=>(l>l=>l=l<l,")"+l+(l(=l>l>=l)=+ (l)l+= +l)l+=>((ll==l)>(l=l)+l++ ()l+>l()+(l=>l(l===l>l=l)(l()l>=l)+))+""(l +(=""l=+)+(l+l(=)l<)+(=l+)+l++(ll=<<l)+++l)(l+=(=l(==ll)=>l+<l()(ll=))))(l<=l)<l)+(+l<l)))

```

### Output of First Program

```
false12truetruetruefalse

```

### Output of Second Program

```
falsefalseundefinedtruetruetruetruefalse116truetruefalse

```

I tried to use the characters `(l)+=<>` as much as possible. The rest is just type conversion.

### First program

```
alert((l=[l=" "][+l>=+1]=l=>l>=l<l,""+l(l=l>=l)+ +l)+((l>=l++ )+((l=>l=l>=l)(l>=l))+(l="")+(l+=l<=l)+l+(l=l)+(l==(l=>l<l)(l))))

```

### Second program

```
alert((l=[]+![])+(l=l+[l][l]+(l>=l)+(l>=l)+ (l=l=>l==l)(l)+l(l>l)+(l==l(l))+"" +(l=+l())+(++l<<++l)+(l==l)+(l=(l<=l)<l)+(+l<l)))

```
> 3 votes

# Answer
# JavaScript ES6, cracked, 2 programs, 255 bytes; Score -16

Good job @Bas! GG.

```
trvya{"fru nxcti;on{;ale"r;Otb(j(fe=c>t(.kfe.yrs(efv)e}rcsate(cf+h(e~)~{ff,=Mast=h>!.posw?f((12),:M"a"t;hal.Ee)r))t)((nfe(wf A(rfr(a0y/(909)) +.f(7/f5il)l()0))+.fma(pf()(x,+`i$,{ff)}=>i`/.s3p)l).ijt`o`.imn(ap"("e)=.>repela.cceh(/ar.Co.d/egA,t""())*)2}3))}

```

## Output 1:

```
36666666666666643333333333333336323666666666666668333333333333333231366666666666666833333333333333323026666666666666682333333333333332292666666666666668233333333333333228266666666666666823333333333333322726666666666666682333333333333332262666666666666668233333333333333225266666666666666823333333333333322426666666666666682333333333333332232666666666666668233333333333333222266666666666666823333333333333322126666666666666682333333333333332201666666666666668133333333333333219166666666666666813333333333333321816666666666666681333333333333332171666666666666668133333333333333216166666666666666613333333333333341516666666666666661333333333333334141666666666666666133333333333333413166666666666666613333333333333341216666666666666661333333333333334111666666666666666133333333333333410666666666666666333333333333334966666666666666633333333333333486666666666666673333333333333337666666666666667333333333333333666666666666666733333333333333356666666666666673333333333333334666666666666666533333333333333353666666666666666533333333333333352666666666666666733333333333333331666666666666666633333333333333330

```

## Output 2:

```
2645,1403,1426,759,2645,1449,2346,920,1127,943,1334,782,782

```
> 3 votes

# Answer
# PHP, cracked, 2 programs, 71 bytes; Score -16

**Interleaved**

```
$ec=tchR;$ho =qs;$cu=$ho.$tc.e_me.$tha(.'p^l/it]';e.cchoo.$c('[$$h'));;

```

**Output**

*1st program*

```
Array

```

*2nd program*

```
\^/\]co\[\$

```

---

**Note**: `Notices` should be suppressed.
> 3 votes

# Answer
# Ruby, cracked, 2 programs, 64 bytes; Score -16

**Interleaved**

```
p w,%=?(w.ord,40,?)(;"jb inv inv is{2").bytes{|*b|?aput%?c} b-w}

```

**Output**

*1st program*

```
"bananas"

```

*2nd program*

```
BANANAS

```

Both outputs have trailing newlines.
> 3 votes

# Answer
# Malbolge, 2 programs, 194 bytes; Score 65

## Interweaved

```
D'`D$'#`pK~A5:]|3!W1ICw;A|RXsWP0xgN;BLeJmd[c#bGa!`3p%n$BS9?~m*,+N)6ii9E%CAxw"Y!Xtbslw2SR|n^gf)9ex+ZLphuan`s_l%F2bS[ZRYn}@gVfUey+SL;QPba`O_s^$[MZR_K^JWO{N>G=kY.XJQuCHUAT@65d>QJ&nN<0;FjJ,H@G@9d]JQ

```

## Output 1

```
haha nope

```

## Output 2

```
malbolge

```

---

It was only a matter of time.

# Programs

## O1

```
D'`A:]\!I;|XWxgBedcba`pn9m*6iiE%CA"!bw|^)9xZpunsl2SRngfe+Lba`_^$\[Z_^W{>=YXQuUT65QJnN0FjJ,HG@dQ

```

## O2

```
D'`$#pK\~5|3W1CwARsP0N;LJm[#G!3%$BS?~,+N)9xwYXtsl2SRngfe+Lha`_%Fb[ZY}@VUyS;QPOsMRKJONGk.JCHA@d>&<;@9]J

```
> 3 votes

# Answer
# Perl, safe, 2 programs, 102 bytes; Score 66

```
sprint""@(u{[|<$/{W)xor$^ldH&~!<]#3,/H-61+e#]l#:l7o#3:3}>]3$^WS}[_$#:,=(~s#30-)3;)^#,]$")]>=">reverse]

```

---

**First Output**

```
Hello, World!

```

**Second Output**

```
Hello, World!

```

---

**Solution**

First Program:

> `print@{[<{World!,Hello}>]}[$,=~s)),$")=>rvrs]`

Second Program:

> `s""(u|$/)x$^H&~<]#3/-61+#]#:7#3:33$^WS_#:(#30-3;^#]]>"eee`
> 3 votes

# Answer
# Pyth, 2 programs, 61 bytes; Score 68/36 (if safe/cracked)

**Interleaved programs**

```
*vsC{`.m`DsPCd..[Gn9`T2vjkpv`/JmsC\Pid~T.n1tt`.VJp~T%n*TCG731

```

**Output, first program**

```
491670984540320247032212137862815

```

**Output, second program**

```
46252265449938954198657919684976120662891392853344868455756073
1063494620552721403954429737131814326362865215612332412466411486182225511644503132172962643458535768453543651970155938693047567602310634946205527214039544297371318143263628652156123324124664114861822255116445031321729626434585357684535

```

Shouldn't be too hard.
> 2 votes

# Answer
# Japt, safe, 3 programs, 63 bytes; Score 36

The version of the interpreter that this was built for can be found here. Unfortunately, I've lost the originals, so I'll have to see if I can crack it myself...

### Interweaved programs

```
"AARoooLv mLv m@(_y6Xpp33*  ay%2%|v2n"+95+'H+2   m@(Xdcq)q -A d

```

### Output 1

```
112221174199804510029601998159214179608538147196191138431341951029363738456410116231158105100149362111411782137669714451962921697122751841161758017110476673747582101138199681951421371867326511541191741031345182116631134159

```

That's *222* digits, in case you were wondering.

### Output 2

```
R!2,tR+dE34N('QM!2'e4Xx;e>+2YGaNsw`4Xs,Gk?(,Q>XFmta:d'Gk:xm~RNxwQklZ;tM+sm~M?ZEea?dw~ !(;`

```

### Output 3

```
Hello, World!

```
> 2 votes

# Answer
# Microscript II, safe, 2 programs, 44 bytes; score 68

Interleaved sources:

```
6$4sv{{3@0s>s"`+`"}s<s3320s*{1+s+K+s<}*p}*h`

```

Output, first program:

```
>=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"! >=<;:9876543210/.-,+*)('&%$#"!

```

Output, second program:

```
[5.477225575051661,2.340347319320716,1.5298193747370035,1.2368586720951604,1.1121414802511236,1.0545811871312343,1.026928034056542,1.0133745773683798,1.0066650770580947,1.0033270040510693,1.001662120702919,1.0008307153074985,1.0004152714285695,1.0002076141624645,1.0001038016938364,1.000051899500139,1.0000259494133834,1.0000129746225213,1.0000064872902181,1.0000032436398485,1.0000016218186092,1.0000008109089757,1.0000004054544056,1.0000002027271822,1.000000101363586,1.0000000506817917,1.0000000253408956,1.0000000126704478,1.000000006335224,1.000000003167612]

```

---

And here's the answer:

Program 1:

```
64s{30s>""s<32s{1+s>K+s<}*p}*h

```

Program 2:

```
$v{@s`+`}s30*`

```
> 2 votes

# Answer
# PHP, cracked, 3 programs, 31 bytes; Score -16

This should be an easy one using 3 programs.

**Interleaved**

```
print ppprrriiinnnttt!!$x'0';;;

```

**Output**

*1st program*

```
1

```

*2nd program*

```
1

```

*3rd program*

```
1

```

---

**Note**: `Notices` should be suppressed.
> 2 votes

# Answer
# Javascript, safe, 2 programs, 106 bytes; Score 66

```
alert(2ale98374rt("q883wope2jv+sjn[d]s^234j8kfdk7j9b|12f8ns7"[9]98+"jskfsd3"2+13()3892721+[]+{}*6^5|27&3))

```

### Output 1

```
-35655169

```

### Output 2

```
njskfsd7

```

## Solution

### Program 1

```
alert(2983748832+[]^234879|1287983213)

```

### Program 2

```
alert("qwopejvsjndsjkfdkjbfns"[9]+"jskfsd"+(3892721+[]+{}*6^5|27&3))

```
> 2 votes

# Answer
# JavaScript ES6, 2 programs, 225 bytes; Score 65/132 (if safe/cracked)

Interweaved:

```
 alaelretrt((((cb=>c=>b.replace(/.replace[a-(/[azA-Z]-z]/gi/g,a,s=>String=>String.fromCharCode(s.fromCharCode(("Z">=a.charCodeAt(0)?90:122)>=(a=a.charCodeAt(0+(s.toLowerCase())+13)?a<'n'?13:-13:a-26)))))))((""gfvbznfcyrg""))))

```

First output:

```
simple

```

Second output:

```
toast

```
> 2 votes

# Answer
# Brainfuck, 4 programs, 251 bytes; 17/144 (if safe/cracked)

**Interweaved programs**

```
--[+++++--+[----++[+-->+[+++++><-]--++->->---<>--]<]+>><.+-+[-+.--[+-++]+.>->-+.-+-.>-+<-<][]>[----+---+>->->.-+<+<]]>>+--..++----+-++-.---+--++-+..----.-----.-.--.--++..-+++++.++-+++[-++-[-->>++++++<+]<>-+.++]++>.+[->++++.<]>+.[--->+<]>++.---.------.

```

**Output, first program**

`Eridan`

**Output, second program**

`Ampora`

**Output, third program**

`PPCG`

**Output, fourth program**

`Code Golf`
> 2 votes

# Answer
# Vitsy, 4 programs, 228 bytes; Score 17

(Uses an older version, which is linked)

Heeeyyyy @VoteToClose. I don't expect this one to be up long, but you never know… I love your language, now that I'm using it a lot!

## Interweaved program

```
1E2P-0P1E^l*312359121E4/13+1*-205+-5Pv*92t\9\[931[2-\D+\*12/]1N5*[t22*^50\+[\72C]\[[2r***t]PC^s]]2TNL2l\*2v2-D2E12[+48/3*-]2\**v+i8+1D+++NL*5N]-*4Z525L5L2*26E/-{'^2N6+l"015v52\2[{v/\[1*12]/r+^ZDs"6p'TO2N{^v]1v{\/3N\[52*]*4-^*N\*

```

# Output 1

```
2014794345195992700000000000000000000000000.00000049.2129129367736101

```

# Output 2

```
679:;=>@ABDEFHIJLMNPQSTUWXY[\]_`b

```

# Output 3

```
44.5'+26

```

# Output 4

```
100000.315464876785728777498798913309289000000000000000000000000000000000000000000000000.000000

```

---

Good luck! I used the online interpreter, but it should work in the safe jar.

---

# Programs

# O1

```
El94+*2+Pt*t7\[rP^]N2248*2*8**2LLE{^N0v\[v1+DpN{v]v\N

```

# O2

```
EPP^*E/3-05-v\[32\[52]***vDE2/-v++]Z

```

# O3

```
12-1313111159991-\+12/152*0+\[2*]2Ll2-1+\+DN5-552*/-'+"5522\[*]rZ"6'O

```

# O4

```
0252*2\[D*]N2^\[CtCs]T2\[3]*i1++LN452626l1{/12/^sT2^1{/3\[52*]*4-^*N\*

```
> 1 votes

# Answer
# JavaScript, 2 programs, 255 bytes; Score 65/132 (if safe/cracked)

```
a=c(([]o[0]+[][0n]+[][0]s+[][0o]+"l")e+(((new .Date)+"l").osplit(" g")[8])+"".match((/aa/)+t([0o][1]+"b")).split(")").join("('").split("bn");Vconssole.blog(aA=[1]=.toUpperCase()+a[7]+a[13]+" '))"+a[4].toUpperCase()+"`"+a[5]+" "+a[15]+a[16]+a[17;]+a[018]);

```

First program output:

```
And I`m fine

```

Second Program output:

```
null

```

The second programs output is text and not JavaScript's:`null`

This should be easy for the robbers.
> 1 votes

# Answer
# Candy, safe, 2 programs, 85 bytes; Score 66

See: Candy

```
75~z43+/k20*416+k-1612+1++k2
8343-k92k*4+5k~7*Ak70kR(4122
5612=x53bAR2((hkDXhZ*h)))ZZ??

```

Outputs:

`51450000`

`1609944`

Update: This is the two programs followed by their interleaving:

```
7 ~z4  /k 0 41 +k  612   +k28 4 -k92k 4 5k~  Ak70k  41225612  53   2(  kD  Z*h)  Z  ?
 5   3+  2 *  6  -1   +1+    3 3     * +   7*     R(        =x  bAR  (h  Xh    )) Z?
75~z43+/k20*416+k-1612+1++k28343-k92k*4+5k~7*Ak70kR(41225612=x53bAR2((hkDXhZ*h)))ZZ??

```
> 1 votes

# Answer
# Foo, 6 programs, 197 bytes; Score 5/192 (if safe/cracked)

Interweaved code:

```
&(@@11&5@@756&@04$+110)c5*@@1$*1+c52$&&@+15*@@2c$(c61>(51/6+10)@<*2$0c*-$0+6c*$6@1$+$c-01c@1c4$c$@/2&-)$50c++c(+$@2*$c2($+6c+c>0*(>+42&$1c+1$6+c--2@<$<5)c>$c>+7$$cc)-<++1+11$$cc)@2(32/$c)&+5*2$c"B"

```

Output from 1st program:

```

@
B

```

Note the tab on first line and trailing space on second line

Output from 2nd program:

```

<83.-

```

Note that the first line is blank

Output from 3rd program:

```
<=$)

```

Output from 4th program:

```
72}

```

Output from 5th program:

```
$#%*+&

```

Output from 6th program:

```
Foo

```

There is only one interpreter for Foo which i know of, you can find it here
> 1 votes

# Answer
# Python 2, safe 2 programs, 148 bytes; Score 65

```
execexec'prin'""it`sum(map(ormpd,(stor.rparrt""('""thellitio"on.__n"'ame_)'_*".3**/7".__len.__()re)pl[ace++-2(]))**061`[+*+2]'.re'"_pl'a)ce(*"+:")

```

Output 1:

```
Hello world...

```

Output 2:

```
188381387815229576775053627587460257651836527329727069542076068076585927926328856199896

```

Program 1:

```
exec'""import""(\'""hello""\')'.replace(*'"_')

```

Program 2:

```
exec'print`sum(map(ord,(str.rpartition.__name__*".3**/7".__len__())[++-2]))**061`[++2]'.replace(*"+:")

```
> 0 votes

# Answer
# JavaScript, 8 programs, 233 bytes; Score 2/384 (if safe/cracked)

OK, now I'm being evil:

```
aalaaalaalllelreeereatlrterlreer(trtr(t(("t(t(!ft(!u\(untc!(y!t[0![p(!ty2!0p6ioee]a[8+0[0tbon(\o!fuo0)fb0 0 |(|h!6["t!Z5y!{!ze"[)0pb}b]01e]+"+")"+o\uo[]0]o0b1f110 al)]4d+1")+)]cl)"("\o!fu0u))0.4slc\incu00c6e(4,f"t)8))ion(){}+![])+"")

```

1st Output:

```
false

```

2nd Output:

```
true

```

3rd Output:

```
heLLo

```

4th Output:

```
2015

```

5th Output:

```
0

```

6th Output:

```
good

```

7th Output:

```
fine

```

8th Output:

```
string

```
> 0 votes

# Answer
# Python 2, 8 programs, 92 bytes; Score: -16

Another easy one:

```
ppprirnriipnnprtp rrpti"piirnrinio"ntt n n"bt"Tunht" t"is ""dot n"t ohhe"el""w lo"aleal"l"s"

```

8 outputs:

```
This

hello

well

no

alas

but

oh

done

```
> 0 votes

---
Tags: code-golf, cops-and-robbers
---


title: A 4x4 Challenge

text:
# Question
Title: A 4x4 Challenge
There exists a brain game called Enumerate (which I made, based on Takuzu). Your challenge is to play this game.

---

# Task

Solve a game of 4x4 Enumerate/Takuzu.

* Receive a starting grid via STDIN or command line.
* Output the solved grid via STDOUT or writing to file.

---

# Rules

A game is characterized by a 4x4 board, made up of red and purple cells.

* There must be the same number of red and purple cells in each row and column (2 red and 2 purple in each).
* There must be no identical rows or columns.

---

# Input

The starting grid will be given as a 16 character/byte string consisting of only `0`, `1`, and `2`. Here is an example:

```
0001100002001200

```

`1` represents a red cell and `2` represents a purple cell. All input boards will be solvable.

---

Note: ***If your language does not support string literal input***, you may take input as an array of integers. Please state in your answer that this is the case. So there is no confusion, this is what said array should look like:

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

```

No nested arrays are allowed.

---

# Output

The solved board should be output in the same format as above; a 16 character/byte string, consisting of only `1` and `2`. Here is the solution for the input above:

```
2121112222111212

```

Again, `1` represents a red cell and `2` represents a purple cell.

---

# Bonuses

A **-25 byte bonus** is offered for any answer that outputs the solved board as an ASCII grid. Here is an example of the previously mentioned board.

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

```

---

A **-50 bytes bonus** is offered for any answer that outputs the solved board in color. This can be output as an image or colored text.

If colored text is chosen, the output should look like this:

```
2121
1122
2211
1212

```

However, if an image is the chosen output method, the resulting file should be 20x20 pixels, where each cell is a colored 5x5 pixel block. Here is an example:

Here are the color codes:

```
Red      -   #a73cba   OR   (167,  60, 186)
Purple   -   #f94a32   OR   (249,  74,  50)

```

---

# Samples

```
In:  0020010100000100
Out: 1221212112122112

In:  0010000200121000
Out: 2211112221121221

In:  1000100102000000
Out: 1122122122112112

```

# Answer
> 10 votes
## CJam (score 13)

With coloured text bonus, only printable characters: 64 chars - 50 = 14

```
l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~{27c'[@_4*27+'m@}f%N*

```

This can be improved by one char using a non-printable character: `27c'[@` becomes `"^["\` where `^` represents character 27, giving a score of 13. xxd version:

```
0000000: 6c3a 7e3a 4c2c 4562 322a 6521 346d 2a5f  l:~:L,Eb2*e!4m*_
0000010: 3a7a 267b 5f4d 2a4c 3124 2e65 7c2e 3d31  :z&{_M*L1$.e|.=1
0000020: 2d21 2a5f 262c 343d 7d2c 7e7b 221b 5b22  -!*_&,4=},~{".["
0000030: 5c5f 342a 3237 2b27 6d40 7d66 254e 2a    \_4*27+'m@}f%N*

```

---

Straight solution with no bonus: 42 chars

```
l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},

```

Online demo

---

With grid bonus: 59 chars - 25 = 34

```
l:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~'|f*2N*'-4*'+***

```

Online demo

---

With image output, 83 chars - 50 = 33. Output is in netpbm format.

```
'P3NKSKS255Nl:~:L,Eb2*e!4m*_:z&{_M*L1$.e|.=1-!*_&,4=},~4f*M*:("§<ºùJ2":i3/f=4f*M*S*

```

Online demo

# Answer
> 6 votes
# CJam, 74-50=24 bytes (color output)

```
l:~:L;5ZbGm*{_L.-L.*:|!\[4/_z]_:::+e_6-!\__.&=**},s4/{"["\_~4*27+'m@}f%N*

```

I don't think this is very well-golfed, but it works! Try it here. Warning: **slow**.

`l:~:L;` reads a line of input into `L`. Then, `5Zb` is `[1 2]`, and we take the 16th Cartesian power (`Gm*`) of this list, to get all possible solutions `[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2] ...]`. The filter `{ },` contains the Takuzu logic.

I added a ANSI code color output bonus:

This doesn't work on the website, of course. There is an unprintable `ESC` byte in the string `"["`.

# Answer
> 2 votes
# C, Score ~~278~~ 257

(~~328~~ 307 bytes - 50 bytes for coloured output, or 291 bytes without colour bonus)

```
t,b,c,u,r,p;v(g){for(b=0,u=59799;b<16;b+=4)u&(c=1<<(g>>b&15))?b=u:0,u|=c;return b>16;}main(i,a)char**a;{for(char*A=a[1];*A;p=p*2|*A++>49)r=r*2|*A==49;for(;++i<6e4;t=0){for(b=16;b--;)t|=(i>>b&1)<<b%4*4+b/4;if(!(p&i^p|r&~i^r|v(i)|v(t))){for(b=16;b--;)printf("\x1b[3%s%s",i&1<<b?"5m2":"1m1",b&3?"":"\n");break;}}}

```

This is a brute-force method which prints the first matching grid. It actually works on a 180-degree rotated grid to simplify some loops, and uses a lookup table (59799) to figure out which rows are valid. Internally all grids are just 16-bit numbers. It takes a single string input from its arguments.

Due to the escape codes used for colouring, you might want to reset your terminal styling after running this (execute `printf "\x1b[0m"`)

Breakdown:

```
// Globals initialise to 0
t, // Transpose of current guess
b, // Bit counter for loops
c, // Current row value when validating
u, // Invalid row mask when validating
r, // Red squares mask (1s in input)
p; // Purple squares mask (2s in input)

// Validation function for rows (returns 0 if valid, shell-style)
v(g){
    for(b=0,u=59799;b<16;b+=4) // "magic" value 59799 is a map of invalid rows
        // For each row:
        u&(c=1<<(g>>b&15))?b=u:0,  // Check if row is valid
        u|=c;                      // Add row to mask (rows cannot be duplicates)
    return b>16; // b = <some massive number> + 4 if a check failed
}

main(i,a)char**a;{ // K&R style function declaration to save 2 bytes
    // Read input (in reverse to save some bytes when reading & printing)
    for(char*A=a[1];*A;
        p=p*2|*A++>49) // Find 2s (input is strictly 012) and go to next
        r=r*2|*A==49;  // Find 1s
    for(;++i<6e4;t=0){ // Brute-force grids (<3 and >=60000 are invalid anyway)
        for(b=16;b--;)t|=(i>>b&1)<<b%4*4+b/4; // Calculate transpose
        if(!(                           // Check...
            p&i^p|                      //  Matches input purples
            r&~i^r|                     //  Matches input reds
            v(i)|                       //  Rows are valid
            v(t)                        //  Columns are valid
        )){
            // Display grid (use ANSI escape codes for colour)
            for(;b--;) // b starts at 16 from last v() call
//              printf(b&3?"%c":"%c\n",(i>>b&1)+49); // no colour variant
                printf("\x1b[3%s%s",i&1<<b?"5m2":"1m1",b&3?"":"\n");
            break; // Stop search
        }
    }
}

```

# So what's 59799?

There are only 16 possible states for each row/column (it's a 4-bit binary number). Out of those, the valid options are:

```
0011 =  3 (decimal)
0101 =  5
0110 =  6
1001 =  9
1010 = 10
1100 = 12

```

Taking those values as bit indexes, we can create a mask:

```
0001011001101000 = 5736 (dec)

```

But here we want to know the *invalid* rows:

```
1110100110010111 = 59799 (dec)

```

# Answer
> 1 votes
# C (function) (with gcc builtins), 283

This seemed like an interesting challenge to tackle in C. Pretty sure it can be golfed more, but here's a start:

```
#define m(a,b)for(j=0;j<4;j++){l[j]=i&a<<j*b;if(__builtin_popcount(l[j])-2)goto l;for(k=0;k<j;k++)if(l[j]==l[k])goto l;}
i,j,k,l[4];f(char*s){for(i=0;i<65536;i++){m(15,4)m(4369,1)for(j=0;j<16;j++)if((!(i&1<<j)==s[j]-49)&&(s[j]!=48))goto l;for(j=0;j<16;j++)putchar(50-!(i&1<<j));l:;}}

```

Input passed as string to function `f()`. Output to STDOUT.

Try it online.

# Answer
> 1 votes
# JavaScript (ES6), 263 ~~300~~

```
g=>{[...g].map(c=>(t+=t+(c>1),u+=u+(c&1)),u=t=0);for(m=15,n=4369,i=0;i++<6e4;){for(x=y=i,s=new Set;x;x>>=4,y>>=1)[3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>(x&m)==v|(y&n)==v&&s.add(v));if(s.size>7&!(i&u)&!(~i&t))return g.replace(/./g,c=>1+(i>>--p&1),p=16)}}

```

Given the constraints, the number of possible solution seems surprisingly small: **72**

The whole board can be seen as a 16 bit number.
Allowed values for rows (masking 1111): 0011, 0101, 0110 and the inverted values 1100, 1010, 1001

Same for for columns, just with different masking and intermixed bits (masking 1000100010001): 0...0...1...1, 0...1...0...1, 0...1...1...0 and the inverted values

Note that rows and columns bit arrangements are different, so to check for uiniqueness you can add both rows and columns to a set and verify that the set size is == 8.

Code to enumerate all possible solutions in a grid 4x4

```
for(m=0xf,n=0x1111,t=i=0;i<0x10000;i++)
{
  // loop condition: row != 0, as valid values have 2 bits set in each row
  for(x=y=i,s=new Set; x; x>>=4, y>>=1)
    [3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>((x&m)==v||(y&n)==v)&&s.add(v))
  if (s.size==8)
    console.log(++t,i.toString(2))
}

```

**Test**

```
F=g=>{ // input as a string
  [...g].map(c=>(t+=t+(c>1),u+=u+(c&1)),u=t=0);
  for(m=15,n=4369,i=0;i++<6e4;) // max valid is 51862
  {
    for(x=y=i,s=new Set;x;x>>=4,y>>=1)
      [3,5,6,9,10,12,17,257,272,4097,4112,4352].map(v=>(x&m)==v|(y&n)==v&&s.add(v));
    if(s.size>7&!(i&u)&!(~i&t))
      return g.replace(/./g,c=>1+(i>>--p&1),p=16)
  }
}

// Basic test

console.log=x=>O.textContent+=x+'\n'

;[
['0020010100000100','1221212112122112'],
['0010000200121000','2211112221121221'],
['1000100102000000','1122122122112112']
].forEach(t=>{
  var i = t[0], x=t[1], r=F(i);
  console.log(i+' -> '+r+(r==x?' OK':' Fail (Expected '+x+')'))
})
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
## Ruby, 196 bytes

```
->g{[o=?1,p=?2].repeated_permutation(16).find{|x|a=x.each_slice(4).to_a
t=a.transpose
a.uniq.size==4&&t.uniq.size==4&&(a+t).all?{|y|y.count(o)==2}&&x.zip(g.chars).none?{|y|y==[o,p]||y==[p,o]}}*''}

```

`repeated_permutation`, why must your name be so long? -\_-

This simply goes through all possible solutions until one of them matches the input pattern.

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