title: Lucas Vs. The Garage Door Remote

text:
# Question
Title: Lucas Vs. The Garage Door Remote
## Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

## The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

## Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

* 0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.
* 1: The button for the left garage door has been pressed by Lucas
* 2: The button for the right garage door has been pressed by Lucas

## Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why). Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

* 0 sec: 0% open (closed); when button is pressed, door starts opening
* 1 sec: 25% open
* 2 sec: 50% open
* 3 sec: 75% open
* 4 sec: 100% open, door stops

And therefore, if open:

* 0 sec: 100% open; when button is pressed, door starts closing
* 1 sec: 75% open
* 2 sec: 50% open
* 3 sec: 25% open
* 4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```
2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)

```

## Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg. `212022112021202211202120221120212022112021202211202120221120`

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of: `N: (L:X% XXXXXXX, R:Y% YYYYYYY)` where:

* N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.
* X% is the percentage of openness of the left door (there is no zero padding)
* XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".
* Y% is the percentage of openness of the right door (there is no zero padding)
* YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```
2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)

```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

# Answer
> 2 votes
# Pyth, ~~156~~ ~~149~~ 145 bytes

```
jkJmO3U60K=G*]Z3=b*3]_1VJFHS2I&=T@KHq*2hT@XHGTH XbHT XKH0)) XKN*_@XbN|@KN@bNN!@KN%+N": (L:%s, R:%s)"m++*@Gd25"% "%3>"csoltpooespnipinengdg"h@KdS2

```

A direct translation of my Python answer.

Try it online!

Explanation:

```
jk                              " print ''.join(map(str,                   "
JmO3U60                         "  J = [randint(0,2) for _ in range(60)])) "
K=G*]Z3                         " K = copy(G = [0] * 3)                    "
=b*3]_1                         " b = [-1] * 3                             "
VJ                              " for N in J:                              "
FHS2                            "  for H in range(1, 3):                   "
I&=T@KH                         "   if ((T = K[H]) and                     "
q*2hT@XHGTH                     "       (2 * (T + 1) == (G[H] += T)[H]):   "
 XbHT                           "    b[H] = T                              "
 XKH0))                         "    K[H] = 0                              "
 XKN*_@XbN|@KN@bNN              "  K[N] = (-(b[N] = K[N] or B[N])[N] *     "
!@KN                            "   (not K[N]))                            "
%+N": (L:%s, R:%s)"             "  print(str(N) + ': (L:%s, R:%s)' %       "
m++                             "   map(lambda d:                          "
*@Gd25                          "    G[d] * 25 +                           "
"% "                            "    '% ' +                                "
%3>"csoltpooespnipinengdg"h@Kd  "    'csoltpooespnipinengdg'[K[d]+1::3]]   "
S2                              "   ), range(1, 3))                        "

```

# Answer
> 5 votes
## Javascript (ES6), ~~277~~ ~~275~~ ~~263~~ ~~253~~ ~~250~~ ~~247~~ 234 bytes

```
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)

```

### Ungolfed and commented

```
_ => (
  // Initialize array:
  //   - d = door states as integers
  //     - bits 0 to 2: door opening state (from 0b000 = 0% to 0b100 = 100%)
  //     - bit #3: door in motion (0: no, 1: yes)
  //     - bit #4: door direction (0: closing, 1: opening)
  d = [0, 0],

  // Initialize strings:
  //   - l = list of commands
  //   - s = door states in plain text
  l = s = '',

  // Iterate on an array of 60 entries.
  [...Array(60)].map(_ => (
    // c = new random command (0, 1 or 2)
    // Append new line and new command to s.
    s += `\n${c = Math.random() * 3 | 0}:(`,

    // Append new command to l.
    l += c,

    // For each door ...
    d = d.map((v, i) => (
      // If the door is in motion, update its opening state.
      // Clear the 'in motion' bit if a bound is reached (either closed or fully open).
      v = v & 8 ? v & 16 ? v - 27 ? v + 1 : 20 : v - 9 ? v - 1 : 0 : v,

      // If the current command is intended for this door, update its direction and
      // 'in motion' bit. Direction is changed on the 'stopped => moving' transition.
      v ^= c + ~i ? 0 : v & 8 || 24,

      // Translate the door state in plain text and append it to s
      s +=
        'LR'[i] +
        `:${(v & 7) * 25}% ` +
        (v & 8 ? v & 16 ? 'opening' : 'closing' : 'stopped') +
        ',)'[i],

      // Value to be taken into account by map()
      v
    ))
  )),

  // Final result to be returned
  l + s
)

```

### Demo

```
let f =
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)

console.log(f())
```

# Answer
> 4 votes
# Python 2, ~~377~~ ~~370~~ ~~361~~ ~~357~~ ~~345~~ ~~335~~ ~~326~~ ~~316~~ ~~312~~ ~~306~~ 304 bytes

The second indent level is a raw tab (`\t`), which plays *really* badly with Markdown, so it's been replaced by two spaces.

```
from random import*
p=[randint(0,2)for d in[[0]*3]*60]
print`p`[1::3]
v=[-1]*3
c=[0]*3
f=lambda y:str(c[y]*25)+'% '+'csoltpooespnipinengdg'[d[y]+1::3]
for x in p:
 for i in 1,2:
  q=d[i];c[i]+=q
  if(2*-~q==c[i])*q:v[i]=q;d[i]=0
 z=d[x]
 if z:v[x]=z
 d[x]=-v[x]*(z==0);print'%d: (L:%s, R:%s)'%(x,f(1),f(2))

```

I'm almost certain this can be golfed further.

Ungolfed, with comments:

```
import random

# Generate the random string - represented as a list of ints
presses = [random.randint(0, 2) for _ in range(60)]
print ''.join(map(str, presses))

# Constants for door states used for easier reading
CLOSING = -1
STOPPED = 0
OPENING = 1

# Variables representing the state of the garage doors
# There's a third element in these so that x[0] resolves to a dummy slot
# (this way, we can avoid a conditional down the road)
prev_states = [CLOSING, CLOSING, 0]
door_states = [STOPPED, STOPPED, 0]
door_pcts = [0, 0, 0]  # delta 1 = 25%

for press in presses:
  # Close/open the door 1 more
  for i in 1, 2:
    if door_states[i] != STOPPED:
      delta_pct, stop_pct = (-1, 0) if door_states[i] == CLOSING else (1, 4)
      door_pcts[i] += delta_pct
      if door_pcts[i] == stop_pct:
        prev_states[i] = door_states[i]
        door_states[i] = STOPPED

  # Handle pressing a button
  # If the press is 0 (no press), the 0th element resolves to a dummy
  # door, thus saving us an expensive conditional

  if door_states[press] == STOPPED:
    door_states[press] = -prev_states[press]
  else:
    prev_states[press] = door_states[press]
    door_states[press] = STOPPED

  # Print the status update
  print '%d: (L:%d%% %s, R:%d%% %s)' % (
    press,
    door_pcts[0]*25,
    ['closing', 'stopped', 'opening'][door_states[0]+1],
    door_pcts[1]*25,
    ['closing', 'stopped', 'opening'][door_states[1]+1],
  )

```

*Saved ~~4~~ ~~14~~ **15** bytes thanks to @TheBikingViking!*

*Saved 6 bytes thanks to @ValueInk!*

# Answer
> 2 votes
## C, ~~420~~ ~~433~~ ~~424~~ 374 bytes

```
#define F(X,x) X=x==1?X+1:x==2?X-1:X;X=X<0?0:X>4?4:X;x=X==0?0:X==4?3:x
#define G(x) x=x==1?3:x==2?0:x==3?2:x+1
#define H(X,x) X*25,x==0||x==3?"stopped":x==1?"opening":"closing"
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)G(l);else if(x[c]==2)G(r);printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],H(L,l),H(R,r));F(L,l);F(R,r);}}

```

Doesn't seed the random generator but does use random for a better distribution. There must be a better way to golf this logic though...

```
110121100121212100112200222111200020111100022122202112202211002
1: (L:0% opening, R:0% stopped)
1: (L:25% stopped, R:0% stopped)
0: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
1: (L:25% stopped, R:50% opening)
0: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
1: (L:25% closing, R:100% stopped)
2: (L:0% stopped, R:100% closing)
1: (L:0% opening, R:75% closing)
2: (L:25% opening, R:50% stopped)
1: (L:50% stopped, R:50% stopped)
2: (L:50% stopped, R:50% opening)
1: (L:50% closing, R:75% opening)
0: (L:25% closing, R:100% stopped)
0: (L:0% stopped, R:100% stopped)
1: (L:0% opening, R:100% stopped)
1: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
1: (L:25% closing, R:75% stopped)
1: (L:0% opening, R:75% stopped)
1: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
0: (L:25% stopped, R:75% closing)
1: (L:25% closing, R:50% closing)
1: (L:0% opening, R:25% closing)
1: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
2: (L:0% stopped, R:0% opening)
2: (L:0% stopped, R:25% stopped)
1: (L:0% opening, R:25% stopped)
2: (L:25% opening, R:25% closing)
2: (L:50% opening, R:0% opening)
2: (L:75% opening, R:25% stopped)
0: (L:100% stopped, R:25% stopped)
2: (L:100% stopped, R:25% closing)
1: (L:100% closing, R:0% stopped)
1: (L:75% stopped, R:0% stopped)
2: (L:75% stopped, R:0% opening)
2: (L:75% stopped, R:25% stopped)
0: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% closing)
2: (L:75% stopped, R:0% opening)
1: (L:75% opening, R:25% opening)
1: (L:100% closing, R:50% opening)

```

### Older version 1:

```
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}

```

### Older version 2:

```
c,i,l,r,L,R,x[60];g(){while(i<60)printf("%d",x[i++]=random()%3);}main(){g();while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("%d: (L:%d%% %s, R:%d%% %s)\n",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}

```

# Answer
> 2 votes
# Ruby, ~~263~~ ~~261~~ ~~260~~ 254 bytes

How did JavaScript's answer get so short??? It overtook mine while I was away and still is winning currently...

```
s=(1..60).map{rand 3}
puts s*''
D=1,2
d=[25]*3;a=[0]*3;m=[p]*3
s.map{|i|D.map{|j|m[j]&&a[j]+=d[j];(0..100)===a[j]+d[j]||i!=j&&(d[j]*=-1;m[j]=p)}
(m[i]^=1)||d[i]*=-1
puts"#{i}: (L%s, R%s)"%D.map{|j|":#{a[j]}% #{%w"stopped opening closing"[m[j]?d[j]:0]}"}}

```

# Answer
> 2 votes
# PHP, ~~254~~ ~~247~~ ~~246~~ ~~245~~ ~~235~~ ~~230~~ 226 bytes

beating ES again!

```
for($t=60;$t--;)$s.=rand()%3;echo$s;for(;++$t<60;print"
$c: ($o[1], $o[2])")for($i=3;--$i;$o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '.[opening,stopped,closing][abs($z-1)])if(((1&$z=&$r[$i])&&!(3&$d[$i]+=2-$z))|$i&$c=$s[$t])$z=++$z%4;

```

golfed down from these 311 (the first complete version, already had some golfing):

```
<?for($i=60;$i--;)$s.=rand(0,2);echo$s;$d=$r=[0,0];$n=[L,R];$p=[stopped,opening,stopped,closing];for($t=-1;++$t<60;print"
$c: (".join(', ',$x).")")for($m=$c=$s[$t],$i=-1;$i++<1;){if($r[$i]&1)if(!($d[$i]+=2-$r[$i])||4==$d[$i])$m|=$i+1;if($m&$i+1)$r[$i]=(1+$r[$i])%4;$x[$i]="$n[$i]:".($d[$i]*25)."% ".$p[$r[$i]];}

```

**breakdown**

```
for($t=60;$t--;)$s.=rand()%3;   // part 1               also initializes $t to -1
echo$s;
for(
    ;
    ++$t<60;
    print"\n$c: ($o[1], $o[2])" // print output
)
    for($i=3;--$i;  // loop $i from 2 to 1 (door number)
        // generate output
        $o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '
        .[opening,stopped,closing][abs($z-1)]           // map 0123 to 1012
    )
        if(((1&$z=&$r[$i])  // if door in motion        ... and reference the array item
            &&!(3&              // 2. if end position   "&&" needed for short circuit
            $d[$i]+=2-$z        // 1. move door         2-$z maps 1,3 to 1,-1 = delta
            )
        )|$i&$c=$s[$t])     // 3. or if button $i pressed   "|" needed for no short circuit
            $z=++$z%4;          // rotate direction     ++$z%4 maps 0,1,2,3 to 1,2,3,0
        // generate output (loop post condition)
    // print output (loop post condition)

```

# Answer
> 1 votes
## Java 8 lambda, 500 characters

I did my best, here is what I came up with:

```
()->{String r="";int i=0,l=0,m=0,n=1,o=1,p=0,q=0;for(;i++<60;)r+=(int)(Math.random()*3);for(char s:r.toCharArray()){l+=p;m+=q;if(l>99&p>0){l=100;p=25*(((n=++n%4)-1)%2);}if(l<1&p<0){l=0;p=25*(((n=++n%4)-1)%2);}if(m>99&q>0){m=100;q=25*(((o=++o%4)-1)%2);}if(m<1&q<0){m=0;q=25*(((o=++o%4)-1)%2);}if(s<49);else if(s>49)q=25*(((o=++o%4)-1)%2);else p=25*(((n=++n%4)-1)%2);r+="\n"+s+": (L:"+l+"% "+(p<0?"closing":p>0?"opening":"stopped")+", R:"+m+"% "+(q<0?"closing":q>0?"opening":"stopped")+")";}return r;}

```

Ungolfed into a complete class:

```
public class Q91479 {

    public static String movedDoorsCombined() {
        String result = "";
        int i = 0, leftDoor = 0, rightDoor = 0, stepLeft = 1, stepRight = 1, changeLeft = 0, changeRight = 0;

        for (; i++ < 60;) {
            result += (int) (Math.random() * 3);
        }

        for (char step : result.toCharArray()) {
            // update stats
            leftDoor += changeLeft;
            rightDoor += changeRight;

            if (leftDoor > 99 & changeLeft > 0) {
                leftDoor = 100;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (leftDoor < 1 & changeLeft < 0) {
                leftDoor = 0;
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            if (rightDoor > 99 & changeRight > 0) {
                rightDoor = 100;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            if (rightDoor < 1 & changeRight < 0) {
                rightDoor = 0;
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }

            if (step < 49) {
                // 0
            }
            else if (step > 49) {
                // right
                changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
            }
            else {
                // left
                changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
            }
            result += "\n" + step + ": (L:" + leftDoor + "% "
                        + (changeLeft < 0 ? "closing" : changeLeft > 0 ? "opening" : "stopped")
                        + ", R:" + rightDoor + "% "
                        + (changeRight < 0 ? "closing" : changeRight > 0 ? "opening" : "stopped")
                        + ")";
        }
        return result;
    }
}

```

Pretty straight forward. The stepLeft/stepRight variables circle from 0-3. Doing some simple maths changeLeft/changeRight hold the respective relative changes per step, which will be added to leftDoor/rightDoor. Many if statements for catching when the door has to stop on it's own.

Feel free to help me shorten this, I think there's a lot to do.

# Answer
> 1 votes
# Haskell (lambdabot) - 409 bytes

```
p=(cycle[0,1,0,-1],0)
t(d:q,s)=(if d/=0&&(s+d<1||3<s+d)then q else d:q,s+d)
k i(a,b)=[o i,": (L:",j a,", ","R:",j b,")"]>>=id
j(d:_,s)=o(round$(fromIntegral s/4)*100)++"% "++words"closing stopped opening"!!(d+1)
s=scanl$ \(a,b)i->i(t a,t b)
main=do b<-(fmap(round.(*(2::Float))).take 60<$>randoms)<$>getStdGen;putStrLn.unlines$(o=<<b):(zipWith k b.w.s(p,p)$([id,f$f w,second$f w]!!)<$>b)
o=show;f=first;w=tail

```

---
Tags: code-golf
---


title: HexaGolf: Wordagons

text:
# Question
Title: HexaGolf: Wordagons
***See also: Rotatagons***

## Challenge

Given a string as input, output its wordagon.

## Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string `hexa`:

Firstly, you start with the first character in the string a place it in the centre:

```
h

```

Then, you take the next character in the string and add a hexagonal layer:

```
 e e
e h e
 e e

```

Then, add the next layer:

```
  x x x
 x e e x
x e h e x
 x e e x
  x x x

```

Finally, add the last layer:

```
   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a

```

And you now have the wordagon for the string `hexa`.

## Examples

Here's some I prepared earlier:

**`hello`**

```
    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o

```

**`PPcg`**

```
   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g

```

**`o *`**

```
  * * *
 *     *
*   o   *
 *     *
  * * *

```

**`(T_T)`**

```
    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )

```

Note that trailing and/or leading newlines are allowed.

## Winning

The shortest code in bytes wins.

# Answer
> 1 votes
# Pyth - 29 bytes

```
j+_K.e+*kdjdjF+*bhk*L2>zhkztK

```

Test Suite.

# Answer
> 19 votes
# Python 2, 83 bytes

```
s=input()
l=len(s)
while 1:l-=1;y=abs(l);print' '*y+' '.join(s[:y:-1]+s[y]*y+s[y:])

```

Prints the wordagon and then crashes (which only prints to STDERR).

Example:

```
% python2.7 wordagon.py <<<'"abcde"' 2&>/dev/null
    e e e e e
   e d d d d e
  e d c c c d e
 e d c b b c d e
e d c b a b c d e
 e d c b b c d e
  e d c c c d e
   e d d d d e
    e e e e e

```

xnor saved 5 bytes. Thanks!

# Answer
> 10 votes
# Vim, 92 bytes

```
:se ri|s/./ &/g
ⓋCⓇ"Ⓓ␛$vpmlmrqqYpi ␛`ljxxhmlylv`rjlmr:s/\%V\(.\)./Ⓡ" /g
@qq@qVdy2G:g/^/m0
Gp

```

Circled letters represent `Control` \+ letter; ␛ is escape.

# Answer
> 6 votes
# Mathematica ~~100~~ 219 bytes

If ASCII-Art need not be Terminal-Art this should be valid.

My earlier submission mistakenly drew a star rather than a hexagon. I can't see how I was so off!

```
c = CirclePoints@6;
f@s_:=Graphics[{Text[s~StringPart~1,{0,0}],Flatten@Table[Text[StringPart[s,n+1],#]&/@Subdivide[Sequence@@#,n]&/@Partition[Riffle[(n)CirclePoints@6,RotateLeft[n CirclePoints@6]],2],{n,1,StringLength@s-1}]},BaseStyle->20]

```

`CirclePoints@6` returns the vertices of a unit hexagon, assuming that the center is at the origin.

`Subdivide`ing the coordinates for neighboring vertices finds equally spaced positions along the respective edge.

A counter from 1 through the `StringLength -1` of the input string allows each layer of the wordagon to be handled separately.
As `n` increases, so does the respective distance of each vertex from the origin.

`Text[s~StringPart~1,{0,0}]` prints the first letter of the input at the origin.

---

f@"Wordagon"

---

For the curious, this is what the star version looked like. I know, it was *way* off the mark. It only showed the letters at the hexagon's vertices.

```
Graphics@Table[Text[Style[StringPart[#, r + 1], 54], r {Cos@t, Sin@t}], {t, 0, 2π, π/3}, {r, 0, StringLength@# - 1}] &["Hexa"]

```

# Answer
> 3 votes
# Ruby, 82 bytes

```
->s{n=s.size-1
(r=-n..n).map{|i|(" "*k=i.abs)+r.map{|j|s[[k+j,k,-j].max]}*" "}*$/}

```

iterates through `1-n..n-1` in both i=y and j=x directions. Without the leading spaces on each line, the output looks like the below, as a result of picking a character from `s` with the index `[[i.abs+j,i.abs,-j].max]`. Adding leading spaces forms the required hexagon.

```
f f f f
f l l l f
f l o o l f
f l o G o l f
f l o o l f
f l l l f
f f f f

```

**Ungolfed in test program**

```
f=->s{
  n=s.size-1             n=string length - 1
  (r=-n..n).map{|i|      iterate from -n to n, build an array of lines
    (" "*k=i.abs)+       k=i.abs. Start each line with k spaces.
    r.map{|j|            iterate from -n to n, build an array of characters.
      s[[k+j,k,-j].max]  select character from s (store null string in array if index past end of string)
    }*" "                concatenate the array of characters into a line, separated by spaces
  }*$/                   concatenate the array of lines into a single string, separate by newlines
}

puts f[gets.chomp]

```

**Typical output**

```
   f f f f
  f l l l f
 f l o o l f
f l o G o l f
 f l o o l f
  f l l l f
   f f f f

```

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

```
s=>[...Array((l=s.length-1)*2+1)].map((_,i,a)=>a.map((_,j)=>s[Math.max(i-l,l-i,j-l,i-j,l+l-i-j)]||``).join` `).join`\n`

```

Where `\n` represents the literal newline character. Based on my answer to Hexplosive ASCII-art challenge although parts of the solution resemble @LevelRiverSt's Ruby answer. The various components of the `Math.max` produce the following output for `l=3`:

```
    i - l           l - i           j - l            i - j        l + l - i - j
- - - - - - -   3 3 3 3 3 3 3   - - - 0 1 2 3    0 - - - - - -    6 5 4 3 2 1 0
- - - - - - -   2 2 2 2 2 2 2   - - - 0 1 2 3    1 0 - - - - -    5 4 3 2 1 0 -
- - - - - - -   1 1 1 1 1 1 1   - - - 0 1 2 3    2 1 0 - - - -    4 3 2 1 0 - -
0 0 0 0 0 0 0   0 0 0 0 0 0 0   - - - 0 1 2 3    3 2 1 0 - - -    3 2 1 0 - - -
1 1 1 1 1 1 1   - - - - - - -   - - - 0 1 2 3    4 3 2 1 0 - -    2 1 0 - - - -
2 2 2 2 2 2 2   - - - - - - -   - - - 0 1 2 3    5 4 3 2 1 0 -    1 0 - - - - -
3 3 3 3 3 3 3   - - - - - - -   - - - 0 1 2 3    6 5 4 3 2 1 0    0 - - - - - -

```

The maximum value is taken, and the values greater than `l` are removed, thus producing the hexagon shape, while the remaining values map to characters from the string:

```
6 5 4 3 3 3 3      3 3 3 3          a a a a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
3 2 1 0 1 2 3   3 2 1 0 1 2 3    a x e h e x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
6 5 4 3 3 3 3      3 3 3 3          a a a a

```

# Answer
> 1 votes
# 05AB1E, 31 bytes

```
R.pvy`¹gN-©×NFs.ø}Sðý®ð×ì})Â¦«»

```

**Explanation**

Utilizing symmetry to only generate the top part of the hexagon,
then mirroring that to form the lower part.

```
R.pv                     }       # for each prefix of the reversed string
                                 # ['f', 'fl', 'flo', 'floG']
    y`                           # split into chars, ex: 'f', 'l', 'o'
      ¹gN-©×                     # repeat the last char len(input)-N times,
                                 # where N is the 0-based list index of the current prefix
                                 # ex: 'oo'
            NF   }               # N times do
              s.ø                # surround current char with the next char on stack
                                 # ex: 'floolf'
                  Sðý            # insert spaces between each letter, ex: 'f l o o l f'
                     ®ð×ì        # prefix string with len(input)-N spaces
                                 # ex: '  f l o o l f'
                          )      # wrap all strings in a list
                           Â¦    # create a reversed copy of the list and
                                 # remove the first item (as we only need the middle once)
                             «»  # concatenate the lists and merge with newlines

```

Try it online!

# Answer
> 0 votes
## Python 2, 104 bytes

```
def f(s):
 for n in range(len(s)*2-1):x=abs(n-len(s)+1);print' '*x+' '.join(s[x+1:][::-1]+s[x]*x+s[x:])

```

# Answer
> 0 votes
# PHP - 202 bytes

```
$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(" ",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad("",$a).strrev($s).($a%2?" ":" {$w[$a]} ")."$s
";$a=abs(--$i);}

```

Usage from command line:

```
php.exe -r "put the escaped code here" "put your desired word here"

```

for example:

```
php.exe -r "$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(\" \",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad(\"\",$a).strrev($s).($a%2?\" \":\" {$w[$a]} \").\"$s\n\";$a=abs(--$i);}" "example"

```

Test Suite.

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


title: Double rotation

text:
# Question
Title: Double rotation
# Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

# Examples

1: Hello world

```
Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution

```

2: codegolf

```
codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl

```

3.: empty string

```
(empty string) //Input
(empty string) //Output

```

# Input

String you need to rotate. May be empty. Does not contain newlines.

# Output

Rotated input string, trailing newline allowed
May be written to the screen or returned by a function.

# Rules

* No loopholes allowed
* This is code-golf, so shortest code in bytes solving the problem wins
* Program must return the correct solution

# Answer
> 1 votes
# MATL, 29 bytes

```
FT"ttk2Y213:lM@*+)m)1_@^YS9M(

```

Try it online!

### Explanation

```
FT        % Push arrray [0 1]
"         % For each
  t       %   Duplicate. Takes input string implicitly in the first iteration
  tk      %   Duplicate and convert to lower case
  2Y2     %   Predefined string: 'ab...yz'
  13:     %   Generate vector [1 2 ... 13]
  lM      %   Push 13 again
  @*      %   Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
  +       %   Add: this leaves [1 2 ... 13] as is in the first iteration and
          %   transforms it into [14 15 ... 26] in the second
  )       %   Index: get those letters from the string 'ab...yz'
  m       %   Ismember: logical index of elements of the input that are in
          %   that half of the alphabet
  )       %   Apply index to obtain those elements from the input
  1_@^    %   -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
  YS      %   Circular shift by 1 or -1 respectively
  9M      %   Push the logical index of affected input elements again
  (       %   Assign: put the shifted chars in their original positions
          % End for each. Implicitly display

```

# Answer
> 9 votes
# Retina, 55 bytes

```
O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1

```

Try it online!

Uses two sorting stages to rotate the first- and second-half letters separately.

# Answer
> 4 votes
# 05AB1E, ~~44~~ ~~43~~ 42 bytes

```
Ðžn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?

```

**Explanation**

Generate a list of the letters of the alphabet of both cases. `['Aa','Bb', ..., 'Zz']`

```
Ðžn2äø€J

```

Split into 2 parts and store a copy in the register.

```
2ä©

```

Extract the letters from the input that are a part of the 1st half of the alphabet, rotate it and store in **X**.

```
`ŠÃÁU

```

Extract the letters from the input that are a part of the 2nd half of the alphabet, rotate it and store in **Y**.

```
ÃÀV

```

Main loop

```
v                         # for each char in input
 ®`                       # push the lists of first and second half of the alphabet
   yåi                    # if current char is part of the 2nd half of the alphabet
      Y¬?                 # push the first char of the rotated letters in Y
         ¦V               # and remove that char from Y
           ëyåi           # else if current char is part of the 1st half of the alphabet
               X¬?        # push the first char of the rotated letters in X
                  ¦U      # and remove that char from X
                    ëy?   # else print the current char

```

Try it online!

**Note:** The leading `Ð` can be omitted in 2sable for a **41** byte solution.

# Answer
> 3 votes
# Javascript (ES6), ~~155~~ ~~142~~ 138 bytes

```
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

```

*Edit: saved ~~3~~ 4 bytes by using `unshift()` (inspired by edc65's answer)*

### How it works

The `R` function takes an array method as its parameter `m`:

```
R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))

```

It is first used with the `push` method to store extracted characters in `a[]` (first half of alphabet) and `b[]` (second half of alphabet). Once these arrays have been rotated, `R()` is called a second time with the `shift` method to inject the new characters in the final string.

Hence the slightly unusual syntax: `R`push``  and `R`shift`` .

### Demo

```
let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));
```

# Answer
> 2 votes
# CJam, 41 bytes

```
lee_{'N,_el^:A&},_1m>er_{ADf+&},_1m<erWf=

```

Try it online!

Uses a similar approach to my vowel shuffling answer.

# Answer
> 2 votes
# Python, 211 Bytes

```
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
 if y(i):r+=u[-1];u=[i]
 else:r+=i
for i in r[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
print l

```

Best i could do. Takes the string from STDIN and prints the result to STDOUT.

### alternative with 204 Bytes, but unfortunatly prints a newline after each char:

```
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
for i in l:
 a=i
 if y(i):a=u[-1];u=[i]
 print a

```

# Answer
> 1 votes
# Python 2, 149 bytes

```
s=input();g=lambda(a,b):lambda c:a<c.lower()<b
for f in g('`n'),g('m{'):
 t='';u=filter(f,s)[-1:]
 for c in s:
  if f(c):c,u=u,c
  t=c+t
 s=t
print s

```

# Answer
> 1 votes
# JavaScript (ES6), 144

Using `parseInt` base 36 to separate first half, second half and other. For any character `c`, I evaluate `y=parseInt(c,36)` so that

* `c '0'..'9' -> y 0..9`
* `c 'a'..'m' or 'A'..'M' -> y 10..22`
* `c 'n'..'z' or 'N'..'Z' -> y 23..35`
* `c any other -> y NaN`

So `y=parseInt(c,36), x=(y>22)+(y>9)` gives `x==1` for first half, `x==2` for second half and `x==0` for any other (as `NaN` \> any number is false)

First step: the input string is mapped to an array of 0,1 or 2. Meanwhile all the string characters ar added to 3 arrays. At the end of this first step the array 1 and 2 are rotated in opposite directions.

Second step: the mapped array is scanned, rebuilding an output string taking each character from the 3 temporary arrays.

```
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop(q.push(q.shift())))).join``

```

*Less golfed*

```
s=>[...s].map(
  c => a[ y = parseInt(c, 36), x=(y > 22) + (y > 9)].push(c)
       && x,
  a = [ [], p=[], q=[] ]
).map(
  x => a[x].shift(),  // get the output char from the right temp array
  p.unshift(p.pop()), // rotate p
  q.push(q.shift())   // rotate q opposite direction
).join``

```

**Test**

```
f=
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop()),q.push(q.shift())).join``

function update() {
  O.textContent=f(I.value);
}

update()
```

```
<input id=I oninput='update()' value='Hello, world'>
<pre id=O></pre>
```

# Answer
> 0 votes
# Perl. 53 bytes

Includes +1 for `-p`

Run with the input on STDIN:

```
drotate.pl <<< "Hello_world"

```

`drotate.pl`:

```
#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g

```

# Answer
> 0 votes
# Python, ~~142~~ 133 bytes

A better variation on the theme:

```
import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')

```

## ungolfed:

```
import re
def u(s,p):
    x = re.split('(?i)([%s])'%p,s)  # split returns a list with matches at the odd indices
    x[1::2] = x[3::2]+x[1:2]
    return ''.join(x)

def v(s):
  w = u(s[::-1],'A-M')
  return u(w[::-1],'N-Z')

```

## prior solution:

```
import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')

```

### ungolfed:

```
import re
def h(s,p):                              # moves matched letters toward front
    t=re.findall(p,s)                    # find all letters in s that match p
    t=t[1:]+t[:1]                        # shift the matched letters
    return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter

def f(s):
    t = h(s[::-1],'[A-Ma-m]')            # move first half letters toward end
    u = h(t[::-1],'[N-Zn-z]')            # move 2nd half letters toward front
    return u

```

# Answer
> 0 votes
## Ruby, 89 bytes

```
f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]

```

# Answer
> 0 votes
# PHP, 189 bytes

Quite hard to golf... Here is my proposal:

```
for($p=preg_replace,$b=$p('#[^a-m]#i','',$a=$argv[1]),$i=strlen($b)-1,$b.=$b,$c=$p('#[^n-z]#i','',$a),$c.=$c;($d=$a[$k++])!=='';)echo strpos(z.$b,$d)?$b[$i++]:(strpos(a.$c,$d)?$c[++$j]:$d);

```

---
Tags: code-golf
---


title: Two Symbol Math

text:
# Question
Title: Two Symbol Math
# Introduction

The four basic math operators (+, -, \*, /) can be reduced to just two, due to the fact that:

```
x + y = x - (-y)
x * y = x / (1/y), y != 0
x * 0 = 0/x

```

# Challenge

The challenge is to take input as a "string" containing:

* Numbers
* Single character variables ("x", "y")
* The four basic math operators (+, -, \*, /)
* Parenthesis

and output a string manipulated so that it would produce the same mathematical result as the input, but containing only the mathematical symbols '-' and '/'

# Specifics

* Input can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
* Output can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
* You must recognize and maintain balanced parenthesis
* Standard loopholes are disallowed
* It is your choice if you want to represent `x + y` as `x - -y` or `x - (-y)`
* You must maintain the order of operations
* You never have to handle invalid input
* Input can be empty or a single number/variable, in that case the program should output the input
* Note: You **do not** have to use the substitutions in the introduction, so long as `input = output`, your program could change `2 * 2` to `8/2`, if you wanted
* You can assume that "0" is the only way a zero will appear in the equation (I.e. you don't have to handle `1 * (4 - 4)`)
* Suggestion: to test your program, go to this website type in `input = output`, where input is the input, and output is the output, and if the result is "true" your program handled that case successfully (example, example)

# Test Cases

Below are some test cases, input as a single string and output as a single string.

```
x + y
x - (-y)

x * y
x / (1/y)

x / y
x / y

x - y
x - y

1
1

5
5

-6
-6

+x
x

1 + (x * 4) - (512 * 3)
1 - (-(x / (1/4))) - (512 / (1/3))

1 - 3 / 4 + l / g
1 - 3/4 - (-(l / g))

5 * 0 / 2
0/5 / 2

(a + g) * 0
0/(a - (-g))

```

# Scoring

It's , so shortest answer in bytes wins. Ties are resolved by first-post.

# Answer
# Python 3, 267 bytes

Thanks to @ConorO'Brien

```
import re
q=re.sub
g=lambda m:'--'+m.group()[1:]
h=lambda m:'/(1/'+m.group()[1:]+')'
i=lambda m:'0/'+m.group()[:-2]
print(q(r'\*[^\(\)]+',h,q(r'[^\(\)]\*0',i,q(r'\+[^\(\)]+',g,q(r'\*\([^\)]+\)',h,q(r'\([^\)]+\)\*0',i,q(r'\+\([^\)]+\)',g,input().replace(' ',''))))))))

```

**Ideone it!**
> 4 votes

# Answer
# Dyalog APL, 42 bytes

This maintains APLs order of operations. Note that `÷x` is `1÷x`

```
'\+' '×'⎕R'--' '÷÷'('(.*)×0'⎕R'0÷\1'~∘' ')

```

TryAPL online!

`(` on the result of...

`~∘' '` remove spaces

`'(.*)×0'⎕R'0÷\1'` replace anything followed by "×0" with "0÷" followed by it

`)` evaluate...

`'\+' '×'⎕R'--' '÷÷'` replace "+" with "--" and "×" with "÷÷"

### To verify:

1. Assign random non-zero numbers to `x`, `y`, `l`, `g`, and `a`.
2. Execute the original expressions.
3. Execute the modified expressions.
4. Compare the results.
> 1 votes

# Answer
# SED 272 246 239 213

```
s,^\+,,;s,[^+*/()-]\+,(&),g;t;:;s,)[^)]*)\*(0,&,;tr;s,\((.*)\)\*(0),(0/\1),;ty;s,\*([^)]*(,&,;tr;s,\*\(([^)]*)\),/(1/\1),;ty;s,\+([^)]*(,&,;tr;s,\+\(([^)]*)\),-(-\1),;ty;p;q;:r;s,(\([^()]*\)),!\1@,;t;:y;y,!@,(),;b

```

Take input without spaces (e.g. `x+y*2`).
This is one of the few cases where it is actually shorter to just escape `(` and `)` for capture groups instead of using `-r`. I'm sure this can be golfed more, but I'm happy for now.

Ungolfed, with comments:

```
s,^\+,, #remove leading +
s,[^+*/()-]\+,(&),g #suround numbers/variables in ()
t start #reset the test because the line above will always match

:start
#------------- deal with *0 ------------------
s,)[^)]*)\*(0,&, #remove inner matching ()
t replace
s,\((.*)\)\*(0),(0/\1),
t y
#------------- deal with generic * -----------
s,\*([^)]*(,&, #remove inner matching ()
t replace
s,\*\(([^)]*)\),/(1/\1),
t y
#------------- deal with + -------------------
s,\+([^)]*(,&, #remove inner matching ()
t replace
s,\+\(([^)]*)\),-(-\1),
t y

b end #all done, branch to the end

#------------- replace a set of () with !@ ---
#repeated application of this helps find the matching ( or )
:replace
s,(\([^()]*\)),!\1@,
t start

:y
y,!@,(),
b start

:end

```
> 0 votes

---
Tags: code-golf, string, arithmetic, balanced-string
---


# Question
Title: Help: Aliens Programmers only speak ASCII
# Setting the Scene:

It is an average afternoon, as you unwind after a long day by engaging in your favorite pastime: answering the plethora of captivating questions on PPCG. It hasn't been a good day for you; those damned Pyth programmers keep getting best answer and it's killing your vibe. Suddenly, you notice a new question has been posted! You make up your mind; not this time CJammers. Furiously, you begin to type, birthing a stream of characters; a fetus of the glorious BrainFuck loop that your end product will be. You type and type. Faster! Faster still! You're so focused you don't even notice the lights on your screen start to flicker on and off. Suddenly, the monitor glows green, an alien like symbol branded upon the desktop. Using your impeccable skills you `cat ~/Desktop/aliensymbol` and get presented with a bunch of numbers, a message! Being the shrewd PPCG programmer that you are, you notice that it looks like ASCII. No matter for you, you `print(chr(i) for i in file)` and decipher the message. Your first thought: "I need to share this with the community!".

...

Who would've thought it? That the first people to make contact with aliens would be the humble programmers of PPCG. Why us? Maybe it is because we are the epitome of human intelligence. Or maybe because BrainFuck is about as close as we have to an alien language. Nevertheless, the aliens - being the ultra-intelligent life forms that they are - want to test whether they should classify the human race as intelligent or not. As a test of our mental prowess, the aliens have asked us to send them a few computer programs to demonstrate that we are technologically cultured. The issue is, the only human language they understand is numerical ASCII!

Help humankind show those creatures who the real intellectual alpha is. We need to send them a script that will convert our text based source codes into their numerical ASCII versions. Unfortunately, due to our underdeveloped technology (thanks Obama), we must send as small a translating program as possible. Good thing they chose to contact PPCG!

# The Challenge:

The premise of this challenge is simple: you are to write a program that will take any program's source code (or any general text file for that matter), and output a space separated version of it with an ASCII translation below each line. That is, given an input of a text file, you need to output each line of that file followed by a line containing the ASCII representation of each character in the line above it (with each number lining up with the character it represents).

An example will greatly clarify this. Taking the source code of the infamous `hello world` as the input:

```
#include <stdio.h>

int main() {
    printf("hello, world\n");
    return 0;
}

```

your program should output:

```
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   (   )       {
105 110 116 32  109 97  105 110 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10

```

# Implementation Details:

You may choose to take the input in whatever form you wish (opening file, command line pipe, function parameter etc.) and you should output to stdout or return the output from a function.

Things to note

* Each character in the output is separated by a '\t' to allow for the space of 3 digits in the line below to line up (we are going to assume your tab is set to 4 spaces or more).
* The newlines are displayed on the line that the return key was pressed (notice the 10's in the example)
* The '\t' and '\n' printing requirements are lax. Your output must, in the general sense, look pleasing to the eye (need to show those aliens we have aesthetic sense as well), and if you can bend the previous two points while maintaining visual integrity, you will be forgiven.
* You can choose to assume whether or not there is a newline at the end of the last line.

# Scoring

This is code-golf so shortest program wins. Note, even if your program isn't the shortest, but uses really neat tricks relative to the language you are using, many +1's to you!

Good luck. The intergalactic intelligence ranking of humanity rests on your shoulders.

Note: Please forgive the plot holes. I'm not a writer :D

# Answer
> 5 votes
# Dyalog APL, 14 bytes

Takes list of strings that include newline sequences (10 or 13 10 etc.)

```
↑(⊢,[.5]⎕UCS)¨

```

matrify the list of lists consisting of

`(`... for each line return...

the text itself

`,[.5]` followed in a new dimension before the first dimension by

`⎕UCS` the **U**nicode **C**haracter **S**et code points

TryAPL online!

# Answer
> 9 votes
# Pyth, ~~17~~ 13 bytes

Another one of those Pyth programmers. *Sorry.*

The new code requires each line to be wrapped in quotes and escaped (including newlines if you desire them to be printed), but puts an extra newline between the line and the ASCII.

```
jjLC9smCMBd.Q

```

Try it online!

Explanation:

```
           .Q  Evaluate all input lines
      m        For each of those lines:
         Bd     Return the line and
       CM       the line mapped to ASCII characters
     s         Sum all these together to begin alternating between line and mapped line
 jLC9          Join all the characters and numbers in the lines and mapped lines on tabs
j              And join all of those on newlines

```

I'm keeping the old code and its' explanation below.

```
#Jw
jKC9J
jK+CMJT

```

Try it online! or use an easier-to-read test case.

Explanation:

```
#                  Until we run into an error:
 Jw                 Read in the next line of input and call it J.
                     (When there is no line of input, error is thrown that ends program.)

j                  Join:
    J               all characters in input line
 KC9                and insert tab characters (C9), which we can refer to later as K.
                        (Setting it to a variable doesn't save or lose bytes.)

                   Implicit print that join with trailing newline.

j                  Join:
   CMJ              the mapping of ASCII numbers to characters in the input,
 K                  inserting tab characters in between every number
  +   T             And with a trailing 10 for the newline at the end.

```

# Answer
> 8 votes
# Vim, ~~86,~~ 77 keystrokes

```
:g/^/norm A<C-v><C-v>10<C-v><esc>Yp:s/./\=char2nr(submatch(0))."\t"/g<C-v><cr>k:s/./&\t/g<C-v><cr>
:%s/<C-v><cr>0<cr>

```

This is way too long, but that's what you get when you use vim's `eval` feature (`\=`).

# Answer
> 8 votes
# Python 2, 105 bytes

This uses a slightly different approach than the OP's answer. Note that SO messes up my literal tabs with spaces.

```
def f(s):
 o=x=''
 for c in s:
    o+=c+"  ";x+="%s    "%ord(c)
    if"\n"==c:print o[:-1],x;o=x=''
 print o+"\n"+x

```

**Try it online**

# Answer
> 6 votes
# Perl, ~~\>33~~ 31 bytes

Includes +3 for `-F` (cannot be combined with `-e` and the code has `'` too, so space and `-` are counted too).

Run with the input on STDIN or give one or more filenames as argument

```
perl -M5.010 asciidump.pl <<< "Hoi"

```

`asciidump.pl`

```
#!/usr/bin/perl -F
$"=v9;say"@F@{[unpack'W*']}"

```

Output is not aesthetic if the text contains a tab or there is no final newline

# Answer
> 5 votes
## C, ~~136~~ ~~117~~ 114 Bytes

```
#define p(s)while(l[i])printf(s,l[i++]);i=0;puts("")
char l[99];i;f(f){while(fgets(l,99,f)){p("%c\t");p("%d\t");}}

```

~~`char l[99];i;f(f){while(fgets(l,256,f)){i=0;while(l[i])printf("%c\t",l[i++]);i=0;puts("");while(l[i])printf("%d\t",l[i++]);puts("");}}`~~

Can be tested like this

```
infile;
main(c,v)char**v;
{
    infile=fopen(v[1],"r");
    f(infile);
}

```

# Answer
> 5 votes
# Pyth, 21 bytes

```
j.imjC9d.zmjC9+CMdT.z

```

Here's an entry from one of *"those damned Pyth programmers"* ;)

A program that takes input of an unquoted multiline string on STDIN and prints the result. This assumes that all input has a trailing newline. If you want it to deal with no trailing newline, add `<` at the beginning of the program and `)_3` at the end.

Try it online

The output for the test case is difficult to see in the online interpreter, so I've included it here:

```
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   t   (   )       {
105 110 116 32  109 97  105 110 116 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10

```

**How it works**

```
j.imjC9d.zmjC9+CMdT.z  Program. Input: .z (All of STDIN split on newlines)
     C9                 Yield tab character by taking chr(9)
    j                   Join on tab
   m   d.z             Map that over .z
               CM       Map ord()
              +   T     Append 10
           jC9          Join on tab
          m      d .z  Map that over .z
 .i                    Interleave the results of the two mappings
j                      Join on newlines
                       Implicitly print

```

# Answer
> 4 votes
## PowerShell v2+, 85 bytes

```
gc $args|%{$a=$b='';$_-split'(.)'-ne''|%{$a+="$_`t";$b+="$(+[char]$_)`t"};$a;$b+"10"}

```

Input is via a path to a file. We then `Get-Content` (alias `gc`) on that file, which automatically splits on newlines. We loop over each of those `|%{...}`. Start by setting `$a` and `$b` to an empty string -- these are our ASCII characters and code points respectively. We then `-split` the input line on every character, keeping it `(.)`, and removing the empty values `-ne''` (it's due to how .NET regex parses), then send those into another loop.

Each inner loop, we string concatenate the current character with a tab ``t` and add that onto `$a`. Similarly for `$b`, excepting we're explicitly casting as a `char` and then as an int `+`.

Outside the inner loop, we place the resulting `$a` and `$b` (with a linefeed designator, since that'll never come up in our looping) on the pipeline. Those are gathered up with an implicit `Write-Output` at program completion.

### Example

(with the understanding that I've got a trailing linefeed and Markdown mangles the tab character)

```
PS C:\Tools\Scripts\golfing> .\aliens-only-understand-ascii.ps1 '.\aliens-only-understand-ascii.txt'
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   t   (   )       {
105 110 116 32  109 97  105 110 116 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   w   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 119 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10

```

# Answer
> 4 votes
# PHP, ~~131~~ 115 bytes

Just a FGITW, maybe I can improve upon it more. Turns out, I can!

First version at 131 bytes:

```
<?$s=file($argv[1]);foreach($s as$l){$a=str_split(trim($l));echo join(' ',$a).'
';$i=0;while($c=ord($l{$i++}))echo$c.'  ';echo'
';};

```

The filename is supplied as the first argument after the script name: `php aliens.php helloworld.c`

Second version at 115 bytes:

```
function($s){foreach($s as$l){$a=str_split($l);echo join('  ',$a);$i=0;while($c=ord($a[$i++]))echo$c.'  ';echo'
';}};

```

The first version accounts for missing newlines at the end of the line, but after the additional clarification, we can leave that code out and put everything in a function to save 16 bytes.

The whitespace characters in `join(' ',$a)` as well as in `echo$c.' '` are tab characters = `\t`. The newlines in the code are on purpose.

# Answer
> 4 votes
# \>\<\> (Fish), 48 Bytes

```
>i:0(?v::oa=?v9o
2';'oa<.20r  <~p3
o9nv?=0l
voa<

```

A task the language shines at! I'm sure I could probably have golfed out a little bit more, but it's been a long week. Might take a look at it later though.

Try it online!

Alternate try it online that looks nicer in my opinion, but the text wrapping messes up a bit for input with long lines like the test case.

# Answer
> 3 votes
# Python 3, ~~89~~ 77 bytes

more golfed version based on the same idea:

```
def f(s):
 for a in s:print(*map('{:>4}'.format,[*a,*a.encode()]),end='\n\n')

```

If there are '\t's in the input, then change the `4` to a `9`.

### Prior version:

```
def f(s):
 for l in s:
  print(*l,sep='\t',end='');print(*l.encode(),sep='\t',end='\n\n')

```

Takes a list of strings, each ending with a '\n'.

# Answer
> 3 votes
# Powershell, 56 Bytes

```
gc $args|%{($a=[char[]]$_)-join"    ";[int[]]$a+10-join"    "}

```

Script accepts a filepath as input. Get-Content automatically splits input into an array of strings split on newlines in the source.

From there I enter a foreach, cast to an array of characters and set that to $a, join that with tabs and print it. Next but still within the foreach I cast the character array to an integer array, append a linefeed and join again with a tab.

Call looks like this:

```
PS C:\PretendFolder> .\aoua.ps1 ".\aoua.txt"

```

and here is an output sample

```
#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   (   )       {
105 110 116 32  109 97  105 110 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10

```

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

```
s=>s.replace(/(.*)\n?/g,(s,n)=>n&&[...s].join`␉`+`
${[...n].map(c=>c.charCodeAt()).join`␉`}
`)

```

Where ␉ represents the literal tab character. Works as long as the input doesn't contain tab characters. 81-byte version that also requires the input to have a trailing newline:

```
s=>s.replace(/.*\n/g,s=>[...s].join`␉`+[...s].map(c=>c.charCodeAt()).join`␉`+`
`)

```

# Answer
> 2 votes
# C#, ~~64~~ 63 bytes

```
s=>{foreach(int c in s+(s=""))s+=c+(10==c?"\n":"    ");return s;};

```

*-1 byte by using actual tab character instead of `\t`. Note: renders as 4 spaces above and 2 spaces in the ungolfed version below.*

Ungolfed:

```
/*Func<string, string> Lambda =*/ s =>
{
    // Enumerate the ascii (int) values of the chars in s,
    // but at the same time set input s to "" to use at the output var.
    // +(s="")   is 2 bytes less than   var o="";
    foreach (int c in s + (s=""))
        // Append the string representation of the ascii value,
        // Append new line if c was new line, otherwise append tab.
        s += c + (10==c ? "\n" : "  ");
    return s;
};

```

Results:

(Note: Visual Studio has used `\r\n` for the new lines when I pasted the input in, hence the `13 10` line endings in output)

```
Input:

#include <stdio.h>

int maint() {
    printf("hello, world\n");
    return 0;
}

Output:

35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  13  10
13  10
105 110 116 32  109 97  105 110 116 40  41  32  123 13  10
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  13  10
32  32  32  32  114 101 116 117 114 110 32  48  59  13  10
125

```

# Answer
> 2 votes
# CJam, 27 bytes

```
qN/{_1/9c*N+\{is9c}%+}%AN+*

```

Try it online!

**Explanation**

```
q       e# Take the whole input
N/      e# Split on newlines
{       e# Map this block to every line:
_        e# Duplicate
1/       e# Split into characters
9c*      e# Join with tabs (ASCII code 9)
N+       e# Append a newline
\        e# Swap top elements
{is9c}%  e# Map each character to its ASCII code plus a tab character
+        e# Concatenate the two lines
}%      e# (end of block)
AN+*    e# Join with "10" plus a newline

```

# Answer
> 2 votes
# PowerShell, ~~61~~ 59 bytes

```
gc m|%{$b="$_
"[0..$_.Length]
$b-join'    '
[int[]]$b-join' '}

```

Things to note:

* Reads the input from a file named `m` in the current directory.
* All line breaks, (including the one embedded in the string after the first `$_`) are literal linefeeds only (0xA), so one byte each.
* The contents of the strings directly after the `-join` operators are each a single tab character (regardless of how it's rendered here).

### Ungolfed

```
Get-Content m | ForEach-Object -Process { # Read the file line by line
    $b = "$_`n"[0..$_.Length]   # Line by line processing strips line endings, so add a newline
                                # Index operator on a [string] returns a [char], or given a [range], a [char[]]
                                # Using $_.Length automatically accounts for the extra linebreak (0 based index)
    $b -join "`t"               # PowerShell displays [char] as the printable character by default, so join the array with a tab
    [int[]]$b -join "`t"        # We need to convert the [char]s to an [int]s so we can display it as a number
                                # So cast the [char[]] as [int[]], then join with tab again

}

```

# Answer
> 0 votes
# Java, 202 bytes

```
s->{for(String g : s.split("\n")){g.chars().forEach(c->System.out.print((char)c+"   "));System.out.println();g.chars().forEach(c->System.out.print(c+(c<10?"  ":c<100?"  ":" ")));System.out.println();}};

```

I can't even be bothered making this shorter..

# Answer
> 0 votes
# Haskell - 71 bytes

```
f q=unlines[(x>>=(++"\t").show.ord)++'\n':intersperse '\t'x|x<-lines q]

```

# Answer
> -1 votes
# **Python 3, ~~92 97~~ 107 bytes**

~~for i in list(open(input()).read().split("\n")): for j in i: print(i+"\n"+ord(j))~~

```
p=print
for i in list(open(input()).read().split("\n"))
    s=t=''
    for j in i:
        r=str(ord(j))
        s+=j+' '*len(r)
        t+=r+' '
    p(s)
    p(t)

```

This is untested, but should work.

Thanks @gowrath for pointing out that the code isn't doing as the question specifies.

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


title: Dimensional countdown

text:
# Question
Title: Dimensional countdown
**Write a function f(n,k) that displays the k-dimensional countdown from n.**

A 1-dimensional countdown from 5 looks like

```
 54321

```

A 2-dimensional countdown from 5 looks like

```
 54321
 4321
 321
 21
 1

```

Finally, a 3-dimensional countdown from 5 looks like

```
 54321
 4321
 321
 21
 1
 4321
 321
 21
 1
 321
 21
 1
 21
 1
 1

```

## Formal definition

The 1-dimensional countdown from any n is a single line with the digits n, n-1,...,1 concatenated (followed by a newline).

For any k, the k-dimensional countdown from 1 is the single line

```
 1

```

For n \> 1 and k \> 1, a k-dimensional countdown from n is a (k-1)-dimensional countdown from n followed by a k-dimensional countdown from n-1.

## Input

Two positive integers k and n \<= 9, in any format you choose.

## Output

The k-dimensional countdown from n, with a newline after each 1-dimensional countdown. Extra newlines are permitted in the output.

## Scoring

Standard golf scoring.

## Bonus example

Here's an example with k \> n, a 4-dimensional countdown from 3 (with extra comments that are not to be included in actual solutions):

```
 -- 3-dimensional countdown from 3
 321
 21
 1
 21
 1
 1
 -- 4-dimensional countdown from 2:
 ---- 3-dimensional countdown from 2:
 21
 1
 1
 ---- 4-dimensional countdown from 1:
 1

```

**Clarifications:**

Digits on a line do not need to be adjacent, but they must be evenly-spaced.

You may write a full program instead of just a function, if you prefer.

# Answer
> 15 votes
# Python, 60 bytes

```
f=lambda n,k:n>1<k and f(n,k-1)+f(n-1,k)or'987654321\n'[~n:]

```

Test it on Ideone.

### How it works

The ***k****-dimensional countdown from **n*** can be defined with a single base case:

> If **n = 1** or **k = 1**, the output is **n || n-1 || ... || 1 || ¶**, where **||** indicates concatenation.

Using the recursive definition from the question, `f(n,k)` returns `f(n,k-1)+f(n-1,k)` if **n \> 1** and **k \> 1**; otherwise it returns the last **n + 1** characters from `'987654321\n'`.

# Answer
> 8 votes
# Jelly, 8 bytes

```
R¡UḌFṚp⁷

```

This is a full program that expects **n** and **k** as command-line arguments.

Try it online!

### How it works

```
R¡UḌFṚp⁷  Main link. Left argument: n. Right argument: k

 ¡        Repeat the link to the left k times.
R           Range; map each integer j in the previous return value to [1, ..., j].
  U       Upend; reverse each 1-dimensional array in the result.
   Ḍ      Undecimal; convert each 1-dimensional array from base 10 to integer.
    F     Flatten the resulting array.
     Ṛ    Reverse the result.
      p⁷  Cartesian product with '\n'. (Join is weird for singleton arrays.)

```

# Answer
> 5 votes
# Javascript, 40 38 37 bytes

Saved 1 bytes thanks to @edc65:

```
f=(n,k)=>k*n?f(n,k-1)+f(n-1,k):n||`
`

```

*Previous answers*

38 bytes thanks to @Neil:

```
f=(n,k)=>k&&n?f(n,k-1)+f(n-1,k):n||`
`

```

40 bytes:

```
f=(n,k)=>k&&n?f(n,k-1)+f(n-1,k):n?n:'\n'

```

# Answer
> 3 votes
# Python, ~~86~~ ~~81~~ 80 bytes

```
o=lambda d,n:"987654321"[-n:]if d<2else"\n".join([o(d-1,n-x) for x in range(n)])

```

`d` is the number of dimensions, `n` is the countdown number.

Will post an explanation soon.

EDIT #1: Changed it to lambda.

EDIT #2: Saved 1 byte thanks to @DestructibleWatermelon.

# Answer
> 3 votes
# Python, ~~76~~ 75 bytes

-1 byte thanks to @Sp3000

```
c=lambda n,k:k>1and'\n'.join(c(n-i,k-1)for i in range(n))or'987654321'[-n:]

```

Caries out the procedure as described in the OP: joins the decreasing `n` results for `k-1` on newlines with a base of the recursion of the `'n...1'` string when `k` is `1` (`k` not greater than `1` since we are guaranteed positive `k` input).

Test cases on **ideone**

# Answer
> 3 votes
## Haskell, 57 bytes

```
n#1='\n':(show=<<[n,n-1..1])
1#_=1#1
n#k=n#(k-1)++(n-1)#k

```

Usage example: `5 # 3` -\> `"\n54321\n4321\n321\n21\n1\n4321\n321\n21\n1\n321\n21\n1\n21\n1\n1"`.

A direct implementation of the definition.

# Answer
> 2 votes
# Racket 215 bytes

```
(define(g n k(s(number->string n)))(cond [(< k 2) n]
[else(define o(for/list((i(string-length s)))
(string->number(substring s i))))(for/list((x o))(g x(- k 1)))]))
(define(f n k)(for-each println(flatten(g n k))))

```

Testing:

```
(f 54321 3)

54321
4321
321
21
1
4321
321
21
1
321
21
1
21
1
1

```

# Answer
> 2 votes
# J, ~~38~~ ~~37~~ 32 bytes

```
a:":@>@-.~&,0<@-."1~0&(](-i.)"0)

```

This is a function that takes *k* on the LHS and *n* on the RHS.

Saved 5 bytes with ideas from @Adám.

## Usage

```
   f =: a:":@>@-.~&,0<@-."1~0&(](-i.)"0)
   3 f 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
4 3 2 1
3 2 1
2 1
1
3 2 1
2 1
1
2 1
1
1

```

## Explanation

```
a:":@>@-.~&,0<@-."1~0&(](-i.)"0)  Input: k on LHS, n on RHS
                    0&(        )  Repeat k times on initial value n
                        (   )"0   For each value x
                          i.        Make the range [0, x)
                         -          Subtract x from each to make the range [x, 1]
                       ]            Return the array of ranges
            0  -."1~              Remove the zeros from each row
             <@                   Box each row
          &,                      Flatten the array of boxes
a:     -.~                        Remove the empty boxes
     >@                           Unbox each
  ":@                             Convert it into a string and return

```

# Answer
> 2 votes
# Dyalog APL, 18 bytes

Prompts for **n**, then for **k**.

```
~∘'0'⍤1⍕(⌽⍳)⍤0⍣⎕⊢⎕

```

`~∘'0'⍤1` remove (`~`) the () zeros (`'0'`) from the rows (`⍤1`) (padding with spaces as needed) of

the character representation of

`(⌽⍳)⍤0⍣⎕` the reversed () count until () each scalar (`⍤0`), repeated () input () times

on

numeric input

TryAPL online!

# Answer
> 2 votes
# C 93 Bytes

Iterative implementation.

```
m,i,j;f(n,k){for(;m<k+2;m++)for(j=0;j<n;j++){for(i=m;i<n-j;i++)printf("%d",n-j-i);puts("");}}

```

# C ~~67~~ ~~65~~ ~~61~~ ~~56~~ 52 Bytes

Recursive implementation

```
f(n,k){n*k?f(n,k-1)+f(n-1,k):puts("987654321"+9-n);}

```

# Answer
> 1 votes
## Ruby, 56 bytes

```
f=->n,k{n>1&&k>1?[f[n,k-1],f[n-1,k]]:[*1..n].reverse*""}

```

### Usage

When you display any solutions, you should use "Kernel#puts".

Example:

```
puts f[9,3]

```

# Answer
> 1 votes
## Batch, 117 bytes

```
@setlocal
@set/an=%1-1,k=%2-1,p=n*k,s=987654321
@if %p%==0 (call echo %%s:~-%1%%)else call %0 %1 %k%&call %0 %n% %2

```

Port of Dennis♦'s Python answer.

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


title: The Path to the Result

text:
# Question
Title: The Path to the Result
**Input:**

A grid of varying size only containing numbers in the range `00-99`, the following four characters: `^`; `>`; `v`; `<`, and spaces to fill (and new-lines of course).

**Output:**

The result of the sum (integer) when you follow the path.

**How does this work?**

You start at the arrow with the highest number, and follow the path the arrows point to.
For each of the four arrows we'll do a different arithmetic calculation:

* `>` = Addition (+);
* `<` = Subtraction (−);
* `^` = Multiplication (\* or × or ·);
* `v` = Real / Calculator Division (/ or ÷);

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the arithmetic operation than the examples, then that is of course completely acceptable.)

**Challenge rules:**

* You can choose the input (to some extent). A string-array would be most logical I think, but a symbol/newline-separated single string is also fine. (Full functions as input that are simply executed in the actual code snippet aren't allowed!)
* Trailing spaces for the input are optional.
* Numbers `0-9` will have a leading `0` so all numbers plus arrow are of an equal three-character length.
The number & arrow will always have the following format: `DDA` (`D` being a digit; `A` being one of the four arrows).
* You use the current value with the previous arithmetic operation (the example below explains this better).
* The final arithmetic operation can be ignored because of the rule above.
* It is possible to have *DDA*'s in the input-grid that aren't being used in the path to the resulting sum.
* There won't be any test-cases for arrows that form a loop.
* There won't be any test-cases for dividing by 0.
* There won't be any test-cases where dividing creates a decimal sum-result. You only have to worry about integers.
* ***EDIT: Since there weren't any answer yet, I decided to change the grids slightly to perhaps make it easier. I know this is usually not recommended to do with challenges, but since no answers were given yet, I think this will make it slightly easier, giving more (/any) answers:*** ~~The spaces between de *DDA*'s are random. There could even be no spaces in between at all.~~ All *DDA*'s and spaces are grouped per three. Also, it is possible to have no spaces between *DDA*'s at all.

**Example:**

*Input:*

```
94>      66v
   05v   08<
         43>
   03>   00^

```

*Path it follows:*

```
Path it follows   |   Current sum value
________________________________________
94>               |   94  (highest value)
66v               |   160 (+)
08<               |   20  (/)
05v               |   15  (-)
03>               |   5   (/)
00^               |   5   (+)
43>               |   215 (*)
                          '>' after 43 is ignored because it's the last number

```

*Output:* 215

**General Rules:**

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

**Test cases:**

```
94>      66v           ->     215
   05v   08<
         43>
   03>   00^

77>   80v55^02<        ->     -19
      20>   14^

22>11>15>80>14v        ->     -16
18^17>      10v
00^   90v43^02v
07^11<15<22v01<

99>98>97>96>95>94v     ->     102
93>92>   91v   03<

```

# Answer
# Python 2, ~~409~~ ~~390~~ 377 bytes

```
def f(p):
 p=map(lambda s:map(lambda d:d==3*(' ',)and(0,-1)or(int(d[0]+d[1]),'><^v'.index(d[2])),zip(s[::3],s[1::3],s[2::3])),p);x,y=max([(x,y)for x in range(len(p[0]))for y in range(len(p))],key=lambda(x,y):p[y][x][0]);r=o=0
 try:
  while 1:
   1/(y*x>=0);d=p[y][x]
   if-1<d[1]:r=eval('r%sd[0]'%'+-*/'[o]);o=d[1];a=(-(o==1),1)[o<1];b=(-(o==2),1)[o>2]
   x+=a;y+=b
 except:print r

```

The second and third indent levels are a raw tab and a raw tab plus a space, respectively. Markdown mangles the raw tabs, so they've been replaced by two spaces.

Ungolfed:

```
def follow(path):
  # Split path's strs into DDAs ((0, -1) for blank, else (int, int))
  path = map(
    lambda s: map(
      lambda dda: (0, -1) if dda == (' ', ' ', ' ') else (int(dda[0] + dda[1]), '><^v'.index(dda[2])),
      zip(s[::3], s[1::3], s[2::3])
    ),
    path
  )

  # Find highest DDA
  x, y = max([(x, y) for x in range(len(path[0])) for y in range(len(path))], key=lambda (x, y): path[y][x][0])

  result = 0
  op = 0  # addition
  try:
    # Keep following the path until we get an IndexError
    while True:
      if y < 0 or x < 0: raise IndexError

      dda = path[y][x]
      if dda[1] != -1:
        # It's not empty - do the operation & change direction
        const = dda[0]

        result = eval('result %s const' % '+-*/'[op])

        op = dda[1]

        dx = 1 if op == 0 else -1 if op == 1 else 0
        dy = 1 if op == 3 else -1 if op == 2 else 0

      # Move to the next thing
      x += dx
      y += dy
  except IndexError:
    # We've exited the path - return
    print result

```

Ideone it! (all test cases)
> 1 votes

# Answer
## Python 2, 449 bytes

```
i=input();p,d,a,o,l=[-1,0],">",0,"+",0
for y in range(len(i)):
 for x in range(len(i[0])):
  if i[y][x]in"><^v":
   v=int(i[y][x-2]+i[y][x-1])
   if v>l:l=v;p=[x-2,y]
while 1:
 if d==">":p[0]+=1
 if d=="<":p[0]-=1
 if d=="^":p[1]-=1
 if d=="v":p[1]+=1
 try:
  c=i[p[1]][p[0]]
  if c in"><^v":
   d=c
   if p[0]<0 or p[1]<0:1/0
   a=eval(str(a)+o+str(int(i[p[1]][p[0]-2]+i[p[1]][p[0]-1])));o={">":"+","<":"-","^":"*","v":"/"}[c]
 except:print a;break

```

This takes an array of strings as input

Ungolfed:

```
pointer = [-1,0]
dir = ">"
output=0
operation="+"

largest = 0
for y in range(len(input)):
    for x in range(len(input[0])):
        if input[y][x] in "><^v":
            value = int(input[y][x-2]+input[y][x-1])
            if value > largest: largest = value; pointer = [x-2, y]

while 1:
    if dir==">":pointer[0]+=1
    if dir=="<":pointer[0]-=1
    if dir=="^":pointer[1]-=1
    if dir=="v":pointer[1]+=1
    try:
        current = input[pointer[1]][pointer[0]]
        if current in "><^v":
            dir = current
            value = int(input[pointer[1]][pointer[0]-2]+input[pointer[1]][pointer[0]-1])

            if pointer[0]<0 or pointer[1]<0:1/0
            output=eval(str(output)+operation+str(value))

            if current==">":operation="+"
            if current=="<":operation="-"
            if current=="^":operation="*"
            if current=="v":operation="/"

    except:
        print output;break

```
> 0 votes

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


# Question
Title: Can you beat the British Intelligence? (Nonogram Solver)
It is time to embark on a perilous quest to defeat the British Intelligence. The aim of this challenge is to write the shortest code that will solve a Nonogram.

# What is a Nonogram?

> The rules are simple. You have a grid of squares, which must be either filled in black or left blank. Beside each row of the grid are listed the lengths of the runs of black squares on that row. Above each column are listed the lengths of the runs of black squares in that column. Your aim is to find all black squares. In this puzzle type, the numbers are a form of discrete tomography that measures how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of "4 8 3" would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups. \[\]\[\]

So the solution to the above Nonogram would be:

# Implementation Details

You can chose to represent the Nonogram however you would like and take it as an input in whatever way you deem fit for your language. Same goes for output. The aim of this challenge is to literally just get the job done; if you can solve the nonogram with whatever output your program gives, that is valid. One caveat is you can't use an online solver :)

This problem is very algorithmically challenging (np-complete) in that there is no completely efficient solution to it and as such, you won't be penalized for not being able to solve larger ones, although your answer will be heavily rewarded if it is able to handle big cases (see bonus). As a benchmark, my solution works for up to roughly 25x25 within 5-10 seconds. To allow for flexibility amongst different languages, solutions that take less than 5 mins for a 25x25 nonogram are good enough.

You may assume a puzzle in always a square NxN nonogram.

You can use this online nonogram puzzle maker to test your solutions.

# Scoring

You are, of course, free to use any language you want and since this is code golf, the entries will be sorted in the order: `accuracy -> length of code -> speed.` However, don't be discouraged by code golfing languages, answers in all languages that show attempts at golfing in an interesting way will be upvoted!

# Bonus

I actually learnt about Nonograms from a cryptographic Christmas card released by the British Intelligence here. The first part was basically a massive 25x25 Nonogram. If your solution is able to solve this, you will get kudos :)

To make your life easier in terms of data entry, I have provided how I represented the data for this specific puzzle for your free use. The first 25 lines are the row clues, followed by a '-' separator line, followed by 25 lines of the col clues, followed by a '#' separator line, and then a representation of the grid with the square clues filled in.

```
7 3 1 1 7
1 1 2 2 1 1
1 3 1 3 1 1 3 1
1 3 1 1 6 1 3 1
1 3 1 5 2 1 3 1
1 1 2 1 1
7 1 1 1 1 1 7
3 3
1 2 3 1 1 3 1 1 2
1 1 3 2 1 1
4 1 4 2 1 2
1 1 1 1 1 4 1 3
2 1 1 1 2 5
3 2 2 6 3 1
1 9 1 1 2 1
2 1 2 2 3 1
3 1 1 1 1 5 1
1 2 2 5
7 1 2 1 1 1 3
1 1 2 1 2 2 1
1 3 1 4 5 1
1 3 1 3 10 2
1 3 1 1 6 6
1 1 2 1 1 2
7 2 1 2 5
-
7 2 1 1 7
1 1 2 2 1 1
1 3 1 3 1 3 1 3 1
1 3 1 1 5 1 3 1
1 3 1 1 4 1 3 1
1 1 1 2 1 1
7 1 1 1 1 1 7
1 1 3
2 1 2 1 8 2 1
2 2 1 2 1 1 1 2
1 7 3 2 1
1 2 3 1 1 1 1 1
4 1 1 2 6
3 3 1 1 1 3 1
1 2 5 2 2
2 2 1 1 1 1 1 2 1
1 3 3 2 1 8 1
6 2 1
7 1 4 1 1 3
1 1 1 1 4
1 3 1 3 7 1
1 3 1 1 1 2 1 1 4
1 3 1 4 3 3
1 1 2 2 2 6 1
7 1 3 2 1 1
#
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```

And here is a slightly different version for your convenience; a comma separated tuple (row, col) where each element is list of lists.

```
([[7, 3, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 1, 3, 1],
  [1, 3, 1, 1, 6, 1, 3, 1],
  [1, 3, 1, 5, 2, 1, 3, 1],
  [1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [3, 3],
  [1, 2, 3, 1, 1, 3, 1, 1, 2],
  [1, 1, 3, 2, 1, 1],
  [4, 1, 4, 2, 1, 2],
  [1, 1, 1, 1, 1, 4, 1, 3],
  [2, 1, 1, 1, 2, 5],
  [3, 2, 2, 6, 3, 1],
  [1, 9, 1, 1, 2, 1],
  [2, 1, 2, 2, 3, 1],
  [3, 1, 1, 1, 1, 5, 1],
  [1, 2, 2, 5],
  [7, 1, 2, 1, 1, 1, 3],
  [1, 1, 2, 1, 2, 2, 1],
  [1, 3, 1, 4, 5, 1],
  [1, 3, 1, 3, 10, 2],
  [1, 3, 1, 1, 6, 6],
  [1, 1, 2, 1, 1, 2],
  [7, 2, 1, 2, 5]],
 [[7, 2, 1, 1, 7],
  [1, 1, 2, 2, 1, 1],
  [1, 3, 1, 3, 1, 3, 1, 3, 1],
  [1, 3, 1, 1, 5, 1, 3, 1],
  [1, 3, 1, 1, 4, 1, 3, 1],
  [1, 1, 1, 2, 1, 1],
  [7, 1, 1, 1, 1, 1, 7],
  [1, 1, 3],
  [2, 1, 2, 1, 8, 2, 1],
  [2, 2, 1, 2, 1, 1, 1, 2],
  [1, 7, 3, 2, 1],
  [1, 2, 3, 1, 1, 1, 1, 1],
  [4, 1, 1, 2, 6],
  [3, 3, 1, 1, 1, 3, 1],
  [1, 2, 5, 2, 2],
  [2, 2, 1, 1, 1, 1, 1, 2, 1],
  [1, 3, 3, 2, 1, 8, 1],
  [6, 2, 1],
  [7, 1, 4, 1, 1, 3],
  [1, 1, 1, 1, 4],
  [1, 3, 1, 3, 7, 1],
  [1, 3, 1, 1, 1, 2, 1, 1, 4],
  [1, 3, 1, 4, 3, 3],
  [1, 1, 2, 2, 2, 6, 1],
  [7, 1, 3, 2, 1, 1]])

```

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

```
[R:C]hlL~l:L:1f=.:3aR,.z:3aC,
tL,?he##ElL,E:2a
.<2,_1<
@b:4f:la
e.h1,

```

This takes a list of two lists (first the rows indicators, then the column ones). Each indicator is itself a list (for situtions like `[3,1]` on one row).

This version takes about 3 minutes to solve the 5 by 5 example of the challenge.

## Way more efficient version, 91 bytes

```
[R:C]hlL~l:L:1f:Cz:3az:Rz:3a=.:4aR,.z:4aC,
tL,?he##ElL,E:2a
.<2,_1<
:+a#=,?h
@b:5f:la
e.h1,

```

Try it online!

This one is not complete brute force: the only difference is that this one imposes constraints on the values of cells such that the number of 1s in each row and column matches the numbers given as indicators in the input. The only brute force part is then in finding the one grid with those constraints for which the "blocks" of 1s match what is given as indication.

This one takes about 0.05 seconds on the 5 by 5 example of the challenge. This is still way too slow for the bonus case, as I have no idea how to express the blocks of ones separated by one or more zeroes in terms of constraints.

### Explanation

I will explain below the 93 bytes version. The only difference between the two is the call to predicate 3 which doesn't exist in the 70 bytes version, and the numbering of the predicates (since there is one less).

* Main predicate:

```
[R:C]     Input = [R, C]
hlL       The length of R is L
~l        Create a list of length L
:L:1f     Each element of that list is a sublist of length L with cells 0 or 1 (Pred 1)
          %%% Part unique to the 93 bytes version
:Cz       Zip the rows of the list of lists with C
:3a       The sum of 1s in each row is equal to the sum of the indicators (Pred 3)
z         Transpose
:Rz       Zip the columns of the list of lists with R
:3a       The sum of 1s in each column is equal to the sum of the indicators (Pred 3)
          %%%
=.        Assign values to the cells of the list of lists which satisfy the constraints
:4aR,     The blocks of 1s must match the indicators on rows
.z        Transpose
:4aC,     The blocks of 1s must match the indicators on columns

```
* Predicate 1: Forces the rows to have a specific length, and that each cell is 0 or 1.

```
tL,       L is the length given as second element of the input
?he       Take an element from the list
##ElL,    That element E is itself a list of length L
E:2a      The elements of E are 0s and 1s (Pred 2)

```
* Predicate 2: Constrain a variable to be either 0 or 1

```
.<2,      Input = Output < 2
_1<       Output > -1

```
* Predicate 3: The sum of 1s in a list must be equal to the sum of indicators (e.g. if the indicator is \[3:1\] then the list must have sum 4)

```
:+a       Sum the elements of the list and sum the indicator
#=,       Both sums must be equal
?h        Output is the list

```
* Predicate 4: Check that blocks of 1s match the indicator

```
@b        Split the list in blocks of the same value
:5f       Find all blocks of 1s (Pred 5)
:la       The list of lengths of the blocks results in the indicator (given as output)

```
* Predicate 5: True for blocks of 1s, false otherwise

```
e.        Output is an element of the input
  h1,     Its first value is 1

```

# Answer
> 9 votes
## Haskell, ~~242 230 201 199 177 163 160 149~~ 131 bytes

```
import Data.Lists
m=map
a#b=[x|x<-m(chunk$length b).mapM id$[0,1]<$(a>>b),g x==a,g(transpose x)==b]
g=m$list[0]id.m sum.wordsBy(<1)

```

Finally under 200 bytes, credit to @Bergi. Huge thanks to @nimi for helping almost halving the size.

Wow. Almost at half size now, partly because of me but mainly because of @nimi.

The magic function is `(#)`. It finds **all** solutions of a given nonogram.

This is able to solve all cases, but may be super slow, since it's complexity is about `O(2^(len a * len b))`. A quick benchmark revealed 86GB allocated for a 5x5 nonogram.

Fun fact: It works for all nonograms, not only square ones.

---

How it works:

* `a#b`: Given lists of lists of integers which represent the number of squares, generate all grids (`map(chunk$length b).mapM id$a>>b>>[[0,1]]`) and filter the results to keep only the valid ones.
* `g`: Given a potential nonogram it sums the runs of 1's horizontally.

# Answer
> 4 votes
# Pyth, ~~91~~ ~~72~~ 71 bytes

```
D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb

```

A program that takes input of a list of the form `[size, [horizontal clues], [vertical clues]]` where each clue is a list of integers (empty clues are the empty list, `[]`), and prints every solution, newline separated, in the form of a binary grid where `1` is shaded and `0` is unshaded.

This is a brute force, so is roughly `O(2^n^2)`. It starts taking a very long time for larger puzzles, but will solve any arbritrary size given sufficient time.

Try it online

**How it works**

The program generates every possible layout by taking the repeated Cartesian product of `[0, 1]` with a length equal to `size^2`. This is then split into chunks, giving a list for each horizontal line. Each line is run-length encoded, filtered by the presence of `1` and flattened, leaving the clue for that line. This is then checked against the input. The above process is repeated for the transpose of the chunks, checking the vertical lines. If there is a hit, each chunk is concatenated, and the concatenated chunks are joined on newlines and implicitly printed, with a trailing newline.

```
D:GHdRq@@QdG.nCf.)TrH8V^,01^hQ2=TcNhQ=Y1VhQ=*Y*:H@TH1:H@CTH2)IYjbmjkdTb  Program. Input: Q
                            hQ                                           Q[0], size
                           ^  2                                          Square
                        ,01                                              [0, 1]
                       ^                                                 Cartesian product
                      V                                     )            For N in the Cartesian product:
                                 cNhQ                                    Split N into Q[0] chunks
                               =T                                        Assign that to T
                                     =Y1                                 Y=1
                                        VhQ                              For H in range [0, Q[0]-1]:
D:GHd                                                                     def :(G, H, d)
                   rH8                                                     Run-length-encode(H)
               f.)T                                                        Filter by presence of 1 in character part
            .nC                                                            Transpose and flatten, giving the clue
       @@QdG                                                               Q[d][G], the relevant input clue
     Rq                                                                    Return clue==input clue
                                               :H@TH1                     :(H, T, 1)
                                                     :H@CTH2              :(H, transpose(T), 2)
                                           =*Y*                           Y=Y*product of above two
                                                             IY           If Y:
                                                                 mjkdT     Conacatenate each element of T
                                                               jb          Join on newlines
                                                                      b    Add a newline and implicitly print

```

*Thanks to @Pietu1998 for some tips*

# Answer
> 2 votes
## Javascript (ES6), ~~401~~ ~~386~~ 333 bytes

This is an early attempt. It's not very efficient but I was curious to test a solution using regular expressions on the binary representation of the rows and columns.

For example, it will translate the clue `[3,1]` into the following regular expression:

```
/^0*1{3}0+1{1}0*$/

```

Right now, this version is not taking square clues into account. I will probably add this later.

### Code

```
(c,r)=>{W=c.length;w=[];S=0;M=(n,p)=>eval(`/^0*${p.map(v=>`1{${v}}`).join`0+`}0*$/`).exec(n);R=(y,i=0)=>S||(w[y]=r[y][i],y+1<W?R(y+1):c.every((c,y)=>(n=0,w.map((_,x)=>n+=w[W-1-x][y]),M(n,c)))&&(S=w.join`
`),r[y][i+1]&&R(y,i+1));r=r.map(r=>[...Array(1<<W)].map((_,n)=>((1<<30)|n).toString(2).slice(-W)).filter(n=>M(n,r)));return R(0)}

```

### Output

The solution is displayed in binary format. Such as:

```
00110
01110
11100
11101
00001

```

### Test

This is a simple test on the example grid.

```
let f =
(c,r)=>{W=c.length;w=[];S=0;M=(n,p)=>eval(`/^0*${p.map(v=>`1{${v}}`).join`0+`}0*$/`).exec(n);R=(y,i=0)=>S||(w[y]=r[y][i],y+1<W?R(y+1):c.every((c,y)=>(n=0,w.map((_,x)=>n+=w[W-1-x][y]),M(n,c)))&&(S=w.join`
`),r[y][i+1]&&R(y,i+1));r=r.map(r=>[...Array(1<<W)].map((_,n)=>((1<<30)|n).toString(2).slice(-W)).filter(n=>M(n,r)));return R(0)}

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

# Answer
> 2 votes
## Haskell, 109 bytes

Disclaimer: this is derived from @ThreeFx's answer. I helped him to golf down his answer but he seems to have lost interest to include my last substantial improvements, so I post them as new answer.

```
import Data.List
n=mapM id
a#b=[x|x<-n$(n$" #"<$a)<$b,g x==a,g(transpose x)==b]
g=map$max[0].map length.words

```

Usage example: `[[2],[3],[3],[3,1],[1]] # [[2],[3],[4],[2],[2]]` -\> `[[" ## "," ### ","### ","### #"," #"]]`.

Brute force. Try all combinations of  and `#`, split int chunks of `#`, count the lengths and compare to the input.

# Answer
> 1 votes
# PHP, ~~751~~ ~~833 (720)~~ ~~753~~ ~~724~~ ~~726~~ ~~710~~ ~~691~~ ~~680~~ 682 bytes

I was eager to build a specialised sequence increment and try my cartesian generator once more;
but dropped the cartesian in favour of backtracking to solve the large puzzle faster.

```
$p=[];foreach($r as$y=>$h){for($d=[2-($n=count($h)+1)+$u=-array_sum($h)+$w=count($r)]+array_fill($i=0,$n,1),$d[$n-1]=0;$i<1;$d[0]+=$u-array_sum($d)){$o=$x=0;foreach($d as$i=>$v)for($x+=$v,$k=$h[$i];$k--;)$o+=1<<$x++;if(($s[$y]|$o)==$o){$p[$y][]=$o;$q[$y]++;}for($i=0;$i<$n-1&$d[$i]==($i?1:0);$i++);if(++$i<$n)for($d[$i]++;$i--;)$d[$i]=1;}}
function s($i,$m){global$c,$w,$p;for(;!$k&&$i[$m]--;$k=$k&$m<$w-1?s($i,$m+1):$k){for($k=1,$x=$w;$k&&$x--;){$h=$c[$x];for($v=$n=$z=$y=0;$k&&$y<=$m;$y++)$n=$n*($f=($p[$y][$i[$y]]>>$x&1)==$v)+$k=$f?:($v=!$v)||$n==$h[$z++];if($k&$v)$k=$n<=$h[$z];}}return$k?is_array($k)?$k:$i:0;}
foreach(s($q,0)as$y=>$o)echo strrev(sprintf("\n%0{$w}b",$p[$y][$o]));

```
* expects hints in arrays `$r` for row hints, `$c` for column hints and `$s` for square hints.
* throws `invalid argument supplied for foreach` if it finds no solution.
* to get the correct byte count, use a physical `\n` and remove the other two line breaks.

**description**

1) from row hints
generate possible rows that satisfy the square hints
and remember their counts for each row index.

2) backtrack over the row combinations:
If the combination satisfies the column hints, seek deeper or return successful combination,
else try next possibility for this row

3) print solution

---

The last golfing had severe impact on the performance;
but I removed profiling assignments for the final benchmarks.

Replace `$n=$n*($f=($p[$y][$i[$y]]>>$x&1)==$v)+$k=$f?:($v=!$v)||$n==$h[$z++];`
with `if(($p[$y][$i[$y]]>>$x&1)-$v){$k=($v=!$v)||$n==$h[$z++];$n=1;}else$n++;`
to undo the last golfing step.

**examples**

For the small example (~~17 to 21~~ around ~~12~~ ~~8~~ ~~7~~ ~~6.7~~ 5.3 ms), use

```
$r=[[2],[3],[3],[3,1],[1]];$c=[[2],[3],[4],[2],[2]];$s=[0,0,0,0,0];

```

for the christmas puzzle:

* killed my small home server with the old solution
* killed the browser with test outputs
* now solved in ~~50~~ ~~37.8~~ ~~45.5~~ around 36 seconds

put data from question to a file `christmas.nonogram` and use this code to import:

```
$t=r;foreach(file('christmas.nonogram')as$h)if('-'==$h=trim($h))$t=c;elseif('#'==$h){$t=s;$f=count($h).b;}else
{$v=explode(' ',$h);if(s==$t)for($h=$v,$v=0,$b=1;count($h);$b*=2)$v+=$b*array_shift($h);${$t}[]=$v;}

```

---

**breakdown**

```
$p=[];  // must init $p to array or `$p[$y][]=$o;` will fail
foreach($r as$y=>$h)
{
    // walk $d through all combinations of $n=`hint count+1` numbers that sum up to $u=`width-hint sum`
    // (possible `0` hints for $h) - first and last number can be 0, all others are >0
    for(
        $d=[2-
            ($n=count($h)+1)+               // count(0 hint)=count(1 hint)+1
            $u=-array_sum($h)+$w=count($r)  // sum(0 hint) = width-sum(1 hint)
        ]                           // index 0 to max value $u-$n+2
        +array_fill($i=0,$n,1)      // other indexes to 1
        ,$d[$n-1]=0;                // last index to 0
                                    // --> first combination (little endian)
        $i<1;   // $i:0 before loop; -1 after increment; >=$n after the last combination
        $d[0]+=$u-array_sum($d) // (see below)
    )
    {
        // A: create row (binary value) from 1-hints $h and 0-hints $d
        $o=$x=0;
        foreach($d as$i=>$v)
            for($x+=$v,$k=$h[$i];$k--;)
                $o+=1<<$x++;
        // B: if $o satisfies the square hints
        if(($s[$y]|$o)==$o)
        {
            $p[$y][]=$o;    // add to possible combinations
            $q[$y]++;       // increase possibility counter
        }
        // C: increase $d
            // find lowest index with a value>min
                // this loop doesn´t need to go to the last index:
                // if all previous values are min, there is nothing left to increase
        for($i=0;$i<$n-1&$d[$i]==($i?1:0);$i++);
        if(++$i<$n)             // index one up; increase $d if possible
            for($d[$i]++        // increase this value
            ;$i--;)$d[$i]=1;    // reset everything below to 1
            // adjust $d[0] to have the correct sum (loop post condition)
    }
}

// search solution: with backtracking on the row combinations ...
function s($i,$m)
{
    global $c,$w,$p;
    for(;
        !$k // solution not yet found
        &&$i[$m]    // if $i[$m]==0, the previous iteration was the last one on this row: no solution
            --;     // decrease possibility index for row $m
        $k=$k&$m<$w-1? s($i,$m+1) : $k      // if ok, seek deeper while last row not reached ($m<$w-1)
    )
    {
        // test if the field so far satisfies the column hints: loop $x through columns
        for($k=1,$x=$w;$k&&$x--;)   // ok while $k is true
        {
            $h=$c[$x];
            // test column hints on the current combination: loop $y through rows up to $m
            for($v=$n=$z=   // $v=temporary value, $n=temporary hint, $z=hint index
                $y=0;$k&&$y<=$m;$y++)
                // if value has not changed, increase $n. if not, reset $n to 1
                // (or 0 for $k=false; in that case $n is irrelevant)
                $n=$n*
                    // $f=false (int 0) when value has changed, true (1) if not
                    ($f=($p[$y][$i[$y]]>>$x&1)==$v)
                    +$k=$f?:    // ok if value has NOT changed, else
                        ($v=!$v)        // invert value. ok if value was 0
                        || $n==$h[$z    // value was 1: ok if temp hint equals current sub-hint
                        ++]             // next sub-hint
                ;
            // if there is a possibly incomplete hint ($v==1)
            // the incomplete hint ($n) must be <= the next sub-hint ($c[x][$z])
            // if $n was <$h[$z] in the last row, the previous column hints would not have matched
            if($k&$v)$k=$n<=$h[$z];
        }
        // ok: seek deeper (loop post condition)
        // not ok: try next possibility (loop pre condition)
    }
    return$k?is_array($k)?$k:$i:0;  // return solution if solved, 0 if not
}

// print solution
foreach(s($q,0)as$y=>$o)echo strrev(sprintf("\n%0{$w}b",$p[$y][$o]));

```

---
Tags: code-golf, puzzle-solver
---