27
\$\begingroup\$

See the cop thread for more information. Each answer to this question should crack an answer there. That is to say, it should be code to find the third-largest integer in the input when run in the interpreter given in that answer.

If you post a crack that turns out to be invalid, you should delete it and are ineligible to post another attempt against the same answer.

Scoring

The winner of this question is the robber who makes the highest number of successful cracks.

\$\endgroup\$
25
\$\begingroup\$

Shuffle, by Liam Noronha

cinpush

main:
    gte Hans 1s Leopold
    jnz Leopold done

    mov 1s Hans

    gte Gertrude Hans Leopold
    jnz Leopold done

    mov Gertrude ShabbySam
    mov Hans Gertrude
    mov ShabbySam Hans

    gte Alberto Gertrude Leopold
    jnz Leopold done

    mov Alberto ShabbySam
    mov Gertrude Alberto
    mov ShabbySam Gertrude

    done:

    mov 10 ShabbySam

    gte 1s ShabbySam Leopold
    jz Leopold undo_u

    mov 30 ShabbySam
    gte 1s ShabbySam Leopold
    jz Leopold undo_d

    undo_r:

        POP!! 1

        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" l
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b

        jmp end

    undo_u:

        POP!! 1

        "shuffle" f
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" b
        "shuffle" l
        "shuffle" l
        "shuffle" l
        "shuffle" f
        "shuffle" b

        jmp end

    undo_d:

        POP!! 1

        "shuffle" f
        "shuffle" b
        "shuffle" l
        "shuffle" f
        "shuffle" f
        "shuffle" f
        "shuffle" b
        "shuffle" b
        "shuffle" b

    end:
    jnz 1s main

print Hans
done!

This was really great fun, thank you Liam! :)

Thanks to Sp3000 for a slight but necessary nudge in the right direction.

How?

Two words: Pocket Cube.

It turns out that the stacks correspond to the faces of a 2x2x2 Rubik's cube as follows:

           ____ ____
          |    |    |
          | 19 | 17 |
          |____U____|
          |    |    |
          | 20 | 18 |
 _________|____|____|____ ____ ____ ____
|    |    |    |    |    |    |    |    |
| 13 | 14 |  1 |  2 |  9 | 10 |  6 |  5 |
|____L____|____F____|____R____|____B____|
|    |    |    |    |    |    |    |    |
| 15 | 16 |  3 |  4 | 11 | 12 |  8 |  7 |
|____|____|____|____|____|____|____|____|
          |    |    |
          | 22 | 24 |
          |____D____|
          |    |    |
          | 21 | 23 |
          |____|____|

Where ULFRBD indicate which face corresponds to up, left, front, right, back, down when the cube is folded properly.

The permutations correspond to rotating any one side by 90 degrees (where the names thankfully match up). It turns out that f, r and d are clockwise rotations (when viewing the face) and r, l and u are counter-clockwise rotations (when viewing the face).

Now the cinpush command operates such that it applies one of the rotations u, d or r (depending on the given value) and then pushes the input value onto the stack in position 1. (And then it repeats doing this for every element in the input.) That means we can reverse this process (to ensure we end up with the correct order of stacks without having to solve an arbitrary Rubik's cube) by repeatedly looking at the stack in position 1, undoing the corresponding permutation and popping the value of that stack (so that next time we see the stack, we get the value underneath).

How do we undo the rotations? Thankfully, we have both f and b at our disposal. If we apply both of them, we rotate the entire cube by 90 degrees. This means we can move the affected side (U, R or D) to L, undo the rotation using one or three ls (depending on the relative direction of l and the rotation performed during the input), and then rotate the cube back to its previous orientation using f and b again.

In particular, each of the rotations performed during input can be undone as follows:

u --> fffbbblllfb
r --> ffbblffbb
d --> fblfffbbb

I'll see if I can come up with some animations to show that this works.

Now this gives us a way to iterate through the entire input once. But with 5 registers, that's all we need:

  • Alberto is the maximum value encountered so far.
  • Gertrude is the 2nd largest value encountered so far.
  • Hans is the 3rd largest value encountered so far.

When we encounter a new value, we bubble it up those three as far as necessary, where we can use ShabbySam as a temporary register for the swaps. That still leaves Leopold which we can use to hold a conditional when making the necessary comparisons.

At the end of the process, we simply print the contents of Hans, which will already hold the 3rd largest value.

\$\endgroup\$
  • 1
    \$\begingroup\$ It's funny that you used each of the five registers in exactly the same way that I did. \$\endgroup\$ – Liam Oct 28 '15 at 20:00
21
\$\begingroup\$

TKDYNS by Sam Cappleman-Lynes

This is probably not optimal, but I think it does the trick...

cvcvc>v>^>>^^>>v>vvvvvvvv<<<^<<^<<^^>^<^cvc>v<cvcvcvc^>>vv<<c
>>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^>v>^cv<<^<^^>^>^^^^^>
>^>v>c<<^<^^>^>^^^^^>
c>v<cvc>v<cvcvc^>vv<cvc>vv<^cvc
>^^<^>^^<^>^<^>^cv><^
>^^<^>^^<^>^<^>c^v><^
>^^<^>^^<^>^cv<vvv>v<<^^^^^^>>^
>^^<^>^^<^>c<vvv>v<<^^^^^^>>^
>^^<^>^^c^<vvv>v<<^^^^^^>>^
>^^<^>^c^^<vvv>v<<^^^^^^>>^
>^^<^>cv<<^^^^^^>>^
>^^c<<^^^^^^>>^
>^cv<<<^<<<^>>>>^^^^^^>>^
>c<<<^<<<^>>>>^^^^^^>>^
>^^<^>^^<^>^>^^c<>
>^^<^>^^<^>^>^c^<>
>^^<^>^^<^>^>c^^<>
>^^<^>^^<^>>c^^^
>^^<^>^^>cvv<^^^^^^>
>^>^^^cv<^^^^^^>
>^>^^c<^^^^^^>
>^>^cvv<<^<^^>^>^^^^^>
>^>cv<<^<^^>^>^^^^^>
>^>vc<<^<^^>^>^^^^^>
cvc<<vvvvvv>>^<^^^>^cvcvcvc^^<vvv>cvc<<<<<<v>>>v>>>^cvc
<<<^<<<^>>>>^^^^^^>>>^c<>
<<<^<<<^>>>>^^^^^^>>>c^<>
<<<^<<<^>>>>^^^^^^>>>vc^^<>
<<<^<<<^>>>>>>^<^^^>v>^c^^^
<<<^<<<^>>>>>>^<^^^>v>cvv<^^^^^^>
<<<^<<<^>>>>>>^>^cv<^^^^^^>
<<<^<<<^>>>>>>^>c<^^^^^^>
<<<^<<<^>>>>>>^>vcvv<<^<^^>^>^^^^^>
^>cv<<^<^^>^>^^^^^>
>c<<^<^^>^>^^^^^>
cvcvcvc^^^<vvvvvv>^^cvcvc<^<v<vv>v>>^^cvcvc

This may come as a surprise, but I didn't write this by hand... the code was generated by the following Mathematica program:

layouts = Graph /@ {Labeled[DirectedEdge[#, #2], #3] & @@@ {{0, 1, ">"}, ... };
path[layout_, a_, b_] := 
 StringJoin[
  PropertyValue[{layouts[[layout + 1]], #}, EdgeLabels] & /@ 
   DirectedEdge @@@ 
    Partition[FindShortestPath[layouts[[layout + 1]], a, b], 2, 1]]
safetyCheck[layout_, target_] = "";
safetyCheck[0, 1] = safetyCheck[0, 11] = "v<>^";
safetyCheck[0, 2] = "v^";
safetyCheck[0, 3] = safetyCheck[0, 13] = "<>";
safetyCheck[0, 4] = "<<>>";
safetyCheck[0, 5] = "v^";
safetyCheck[0, 6] = "<v^>";
safetyCheck[0, 7] = "><";
safetyCheck[0, 8] = safetyCheck[0, 18] = "<>";
safetyCheck[0, 9] = "v^";
safetyCheck[1, 2] = "v^";
safetyCheck[1, 3] = safetyCheck[1, 13] = safetyCheck[1, 23] = "<<>>";
safetyCheck[1, 4] = "<v<>^>";
safetyCheck[1, 5] = "v^";
safetyCheck[1, 6] = "<v^>";
safetyCheck[1, 7] = "<v^>";
safetyCheck[1, 8] = "v^";
safetyCheck[1, 9] = safetyCheck[1, 19] = "<v^>";
safetyCheck[2, 3] = safetyCheck[2, 13] = "<>";
safetyCheck[2, 4] = "<<>>";
safetyCheck[2, 5] = safetyCheck[2, 15] = "v<>^";
safetyCheck[2, 6] = safetyCheck[2, 16] = "<<<<>>>>";
safetyCheck[2, 7] = "><";
safetyCheck[2, 8] = safetyCheck[2, 18] = "<>";
safetyCheck[2, 9] = safetyCheck[2, 19] = safetyCheck[2, 29] = "<>";
safetyCheck[3, 4] = "<>";
safetyCheck[3, 5] = "v^";
safetyCheck[3, 6] = ">><<";
safetyCheck[3, 7] = safetyCheck[3, 17] = "<<>>";
safetyCheck[3, 8] = safetyCheck[3, 18] = "v><^";
safetyCheck[3, 9] = safetyCheck[3, 19] = safetyCheck[3, 29] = "vvv^^^";
safetyCheck[4, 5] = safetyCheck[4, 15] = "<>";
safetyCheck[4, 6] = safetyCheck[4, 16] = "<<>>";
safetyCheck[4, 7] = ">v^<";
safetyCheck[4, 8] = "v^";
safetyCheck[4, 9] = safetyCheck[4, 19] = safetyCheck[4, 29] = "<>";
safetyCheck[5, 6] = "<>";
safetyCheck[5, 7] = "><";
safetyCheck[5, 8] = "<>";
safetyCheck[5, 9] = safetyCheck[5, 19] = "<<>>";
safetyCheck[6, 7] = "><";
safetyCheck[6, 8] = safetyCheck[6, 18] = "<>";
safetyCheck[6, 9] = "v^";
safetyCheck[7, 8] = safetyCheck[7, 18] = "v><^";
safetyCheck[7, 9] = safetyCheck[7, 19] = safetyCheck[7, 29] = "<>";
safetyCheck[8, 9] = safetyCheck[8, 19] = safetyCheck[8, 29] = "<>";

minions = {};
For[i = 0, i < 10, ++i,
  collector = "c";
  For[j = i, j < 90, j += 10,
   collector = collector <> path[i, j, j + 10] <> "c"
   ];
  AppendTo[minions, collector];
  For[newI = i + 1, newI < 10, ++newI,
   For[k = 0, k < 10, ++k,
    AppendTo[minions, 
     path[i, j, 10 k + newI] <> "c" <> path[newI, 10 k + newI, newI] <>
       safetyCheck[i, 10 k + newI]]
    ]
   ]
  ];
StringRiffle[minions, "\n"]

I actually wrote all those safetyCheck lines by hand. But the first line of that Mathematica code is actually about 28,000 characters long and was itself generated by the following CJam code:

'{o
q~]{-1:W;
2b200Te[W%2/{W):W;~\{
  "{"W+","W)++",\">\"}"+
  "{"W)+","W++",\"<\"}"+
  @
}*{
  "{"W+","WA+++",\"v\"}"+
  "{"WA++","W++",\"^\"}"+
}*}%", "*"Labeled[DirectedEdge[#,#2],#3]&@@@{ }"S/\*

]o',oNoNo}/'}

(Which takes as input the 10 layouts hardcoded into the interpreter. You can run the code online.)

Code-generation-ception!

Explanation

For a start, have a look at this CJam script to see what the mazes look like.

My solution is based on one important observation: as long as we pick up items along a single column, we won't change between layouts, regardless of whether the cells are filled or not. In particular, as long as we move along the left-most column we'll remain in layout 0. As long as we move along the next column, we'll remain in layout 1.

The tricky bit is how to ensure that we've changed between layouts, because we don't know which cells in column 1 have items on them (if any!).

So here's the algorithm (starting on cell 0 in layout 0):

  1. Collect all items along the current column, ending up on the bottom row. This minion will never die.
  2. Now for each cell to the right of the current column (trying them in column-major order), try moving there in the current layout, pick up an item there, then move to the top row in that new column using the new layout.

    If the attempted cell contained an item, the layout will have changed and we will successfully reach the new column and layout. Because the new (safe) position is at the top row, but all the attempts of finding the next column include 10 net upward moves, all other attempts will fail, so we can ignore them.

    If the attempted cell did not contain an item, in most cases, the minion will die during the attempt to reach the top row using the wrong layout, hence discarding this attempt. However, this is not always the case. For instance, the attempted cell might already be on the top row, so no moves were made on the new layout. Likewise, in some cases, the path from the attempted cell to the top row is short enough to be valid on both layouts. I've collected all the cases where this is an issue by hand, and determined a set of moves which is only valid on the new layout (but which moves the minion back to the target cell, so it's effectively a no-op on the new layout). After each attempt where this can be an issue, I perform this set of moves to kill off any minions which didn't collect an item on the attempted cell.

  3. We've now successfully moved to the top of the next column which contains at least one item. Go back to step 1.

You may notice that the structure of solution is as follows:

Line with 10 "c"s
90 lines with 1 "c"
Line with 10 "c"s
80 lines with 1 "c"
Line with 10 "c"s
70 lines with 1 "c"
Line with 10 "c"s
60 lines with 1 "c"
...
Line with 10 "c"s
10 lines with 1 "c"
Line with 10 "c"s

As for the Mathematica code, the safetyCheck strings are those hand-picked moves which ensure that we've reached the new layout. The first parameter to the lookup is the layout we're starting from and the second one is the cell we've attempted. Any combinations which aren't mentioned explicitly just give an empty safety check (because none is necessary).

In addition to that, I'm simply setting up the 10 mazes as Graph objects, where there are two directed edges between any adjacent (and connected) cells, where each edge is annotated with move required to traverse the edge. With that in place, I can simply find the paths using FindShortestPath and then extract the corresponding edge labels with PropertyValue[..., EdgeLabels].

The rest of the code just makes use of that to implement the above algorithm fairly directly.

The actual graph data is stored in layouts and was generated with the CJam script, which decodes the numbers as described in the cop post and turns them into a Mathematica list, which can easily be transformed into a graph.

\$\endgroup\$
  • 11
    \$\begingroup\$ What​​​​​​​​​​​ \$\endgroup\$ – Alex A. Oct 29 '15 at 21:12
  • \$\begingroup\$ ... \$\endgroup\$ – Sanchises Oct 29 '15 at 21:15
  • \$\begingroup\$ Thanks for that last CJam script - it's actually the first time I've ever seen the mazes I created! \$\endgroup\$ – Sam Cappleman-Lynes Oct 29 '15 at 21:46
  • \$\begingroup\$ Martin taking the lead, I see. \$\endgroup\$ – seequ Oct 29 '15 at 22:13
14
\$\begingroup\$

HPR, by Zgarb

The code:

#(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))#(#(!(-)(#(-)()))())(*!(-)(#(-)()))#(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))#(#(!(-)(#(-)()))())(*!(-)(#(-)()))#(*#(!(-)(#(-)()))()!(-)(-)#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(#(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))!(-)(#(-)()))#(!(-)(#(-)()))())(!(#(!(-)(#(-)())*#(!(-)(#(-)()))())(!(-)(#(-)()))!(-)(#(-)()))(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(-)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))()))))#(!(-)(#(-)()))())#(!(-)(#(-)()))())))#(!(-)(#(-)()))())!(-)(#(-)()))#(#(!(-)(#(-)()))())(*!(-)(#(-)())))(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)()))!($)(!(!(-)(#(-)())#(!(-)(#(-)()))())(!(!(-)(#(-)())#(!(-)(#(-)()))())(#(*)()#(!(-)(#(-)()))())))!(#(*#(!(-)(#(-)()))())(!(-)(#(-)()))-)(#(#(*#(!(-)(#(-)()))())(!(-)(#(-)()))-)())#(!(-)(#(-)()))()

First of all ... the code was generated, not hand written (or typed).

Facts about the language:

  • It is not Turing Complete.
  • You can't compare integers found in the environment.
  • You can compare integers in lists with integers in the environment.
  • You can't add elements to lists or change elements in lists.

The program uses the following psuedocode:

global item
global list = input()

biggest()
remove()
biggest()
remove()
biggest()
print()

def remove():
    while item != list[0]:
        rotate_list
    list.remove(0)
def print():
    rotate_list until item == list[0]
    do until no change:
        list.pop()
        subtract
    removeList()
def biggest():
    item = 0
    while hasListWithElements():
        if item < list1[0]:
            item = list1[0]
        list.remove(0)
    restore list

The environment almost always contains only 1 list and 1 integer.

In order to solve this, I created a small macro engine for this language. It also allows comments. Here is the macro engine:

import sys

code = {}


filename = sys.argv[1]
f = open(filename, 'r')
prog = f.read()
f.close()

def c(prog):
    for n in prog.splitlines():
        if n.startswith('def'):
            parts = n[4:].split(' ', 2)
            code[parts[0]] = int(parts[1]) ,parts[2]
            prog = prog.replace(n, '', 1)
        elif n.strip().startswith('//'):
            prog = prog.replace(n, '', 1)
    return compile(prog)

def compile(prog):
    ret = ''
    while prog:
        n = prog[0]
        if n == '<':
            name = prog[1:prog.find('>')]
            args_count, formatter = code[name]
            if args_count == 0:
                prog = prog[prog.find('>') + 1:]
                ret += compile(formatter)[0]
                continue;
            prog = prog[prog.find('>') + 2:]
            args = []
            for n in range(args_count):
                arg, prog = compile(prog)
                if n == args_count - 1:
                    arg = arg[:-1]
                args.append(arg)
            ret += compile(formatter.format(*args))[0]
        elif n == ')':
            return ret + ')', prog[1:]
        elif n == ',':
            return ret, prog[1:]
        elif n == '(':
            c, prog = compile(prog[1:])
            ret += '(' + c
        else:
            ret += n
            prog = prog[1:]
    return ret.replace('\n','').replace(' ',''), prog

print(c(prog)[0]) #Use pipes to put into file.

After I built the macro engine, I slowly built up useful functions for this language. Here is the code that the engine processed to create the program:

//While loop
def w 2 !({1})({0})

//Detects changes
def c 1 #({0})()

//Do while it changes:
def wc 1 <w>(<c>({0}), {0})

//Remove all items:
def rint 0 <wc>(-)

//Contains list:
def clist 0 <rint>

//Remove all lists:
def rlist 0 #(<rint>)()

//Contains item:
def cint 0 <rlist>

//False (empty environment):
def false 0 <rint><rlist>

//Not:
def not 1 !(<false>)({0})

//Bool (if expression does not evaluate to an empty environment,
// restore the environment to its previous state.
def bool 1 <not>(<not>({0}))

//And
def and 2 <bool>({0}){1}

//Or
def or 2 <not>(<and>(<not>({0}), <not>({1})))

//Combine parts (takes the integer parts of first argument and 
//combines them with the list parts of second argument):
def p 2 #({0}<rlist>)({1}<rint>)

//If, executes an expression if condition evalutates to true. Only works in standard environment.
def if 2 <p>(!({1}<rlist>)(<and>({0}, <rint>)),!({1}<rint>)(<and>({0}, <rlist>)))

//equal (compares item to list[0]) for equality:
def eq 0 <not>(#(*)()<rlist>)

//list.remove(0), does not change item:
def listr 0 <p>(, *)

//remove, removes item from list, goes into infinite loop if list does not contain item.
def remove 0 <w>(<not>(<eq>), $)<listr>

//Greater than or equal, item >= list[0]: 
def ge 0 <w>(<and>(<not>(<eq>), <rlist>), -)<rlist>

//Less than, item < list[0]:
def lt 0 <not>(<ge>)

//Zero, sets item to zero:
def zero 0 <p>(*<rlist>!(-)(-), )

//Biggest, puts biggest item in the list into item:
def biggest 0 <zero><p>(<w>(<c>(*), <if>(<lt>, <p>(<rint>*, ))<listr>), )

//print item, item must be somewhere on list.
def print 0 <w>(<not>(<eq>), $)<wc>(<p>(*, )-)<rlist>

//The actual program!!!!
<biggest>
<remove>
<biggest>
<remove>
<biggest>
<print>
\$\endgroup\$
  • \$\begingroup\$ This is great, I like the macro system! \$\endgroup\$ – Zgarb Oct 31 '15 at 19:39
9
\$\begingroup\$

Brian & Chuck by Martin Büttner

The following Python 2.7 program outputs my Brian & Chuck program, by translating a brainfuck program into Brian & Chuck (with the exception that . always prints 1, since that's the only character we need to output).

Control flow works by magic having Brian write out on Chuck's tape commands to send Brian to the correct position in code.

Note that whitespace and []s added to the B&C program are decorative only.

def brainfuck_to_brianchuck(code):
    # find biggest jump needed
    biggest_jump = 0
    idx = 0
    while idx < len(code):
        if code[idx] == '[':
            end = matching_bracket(code,idx)
            jump = sum(c == '[' for c in code[idx:end])
            if jump > biggest_jump:
                biggest_jump = jump
            idx = end
        idx += 1
    block_size = biggest_jump*4 + 4

    fragments = []
    depth = 0
    for idx,c in enumerate(code):
        if c in '<>':
            fragments.append(block_size*c)
        elif c == '[':
            end = matching_bracket(code,idx)
            jump = sum(c == '[' for c in code[idx:end])
            fragments.append('\n' + '  '*depth)
            fragments.append('[ ' + open_while(jump))
            depth += 1
            fragments.append('\n' + '  '*depth)
        elif c == ']':
            start = matching_bracket(code,idx)
            jump = sum(c == '[' for c in code[start:idx])
            depth -= 1
            fragments.append('\n' + '  '*depth)
            fragments.append('] ' + close_while(jump))
            fragments.append('\n' + '  '*depth)
        elif c == '.':
            fragments.append('>' + write('0>.?',True) + '<<<?1<<<' + write('0>.?',False) + '<<<<')
        elif c in ',+-':
            fragments.append(c)
    return ''.join(fragments) + '\n```'


def open_while(jump):
    fragments = []

    right = '0' + '}>}>'*jump + '?'
    fragments.append('>' + write(right,True))
    r = len(right)-1
    fragments.append('<'*r + '?' + '_0')

    left = '{<{<'*jump + '>>?'
    l = len(left)-1
    fragments.append('<'*l)
    fragments.append(write(left,False))
    fragments.append('<'*l + '<')

    return ''.join(fragments)

def close_while(jump):
    fragments = []

    right = '0' + '}>}>'*jump + '?'
    fragments.append('>' + write(right,True))
    r = len(right)-1
    fragments.append('_0' + '<'*r)
    fragments.append(write(right,False))
    fragments.append('<'*r)

    left = '{<{<'*jump + '>>?'
    l = len(left)-1
    fragments.append(write(left,True))
    fragments.append('<'*l + '<' + '?>')
    fragments.append(write(left,False))
    fragments.append('<'*l + '<')

    return ''.join(fragments)

# returns the code to write s, or erase it if increment is False
def write(s,increment):
    c = '+' if increment else '-'
    return '>'.join(c*ord(a) for a in s)

def matching_bracket(code, idx):
    bracket = code[idx]
    other_bracket = ']' if bracket == '[' else '['
    direction = 1 if bracket == '[' else -1
    idx += direction
    while code[idx] != other_bracket:
        if code[idx] == bracket:
            idx = matching_bracket(code, idx)
        idx += direction
    return idx

print brainfuck_to_brianchuck('''
-
>,------------------------------------------------[
    ,------------------------------------------------[
        ->+>>>[>+<<<<->>>-]<[>+<<<->>-]<[>+<<->-]>>>[<+>-]<<<<[>+<-]
        >>>>>,------------------------------------------------
    ]
    <+[-<<<<<<+]-
    >,------------------------------------------------
]
>>>>[.>>>>>>].
''')
\$\endgroup\$
  • \$\begingroup\$ Nice job. Thanks for proving B&C Turing-complete. ;) (Well I guess we'd need a formal proof of correctness of your translation, but the generated program seems to be working nicely.) \$\endgroup\$ – Martin Ender Nov 9 '15 at 9:43
8
\$\begingroup\$

Firetype, by kirbyfan64sos

Working, commented code:

_ Beginning of the loop where one iteration reads one unary number.
- Decrement to cancel the next +, which is part of the loop.
+ Increment... this is executed once for each 1 we read.
, Read a character.
^ "eval"
# Negate.
* Double three times to get -8 if we read a 1 and 0 otherwise.
*
*
% If we read a 1, jump back to the +. Otherwise, continue.
# Negate the resulting number to reverse the sort order later.
` Duplicate...
~ Logical NOT twice, to turn non-zero results into 1 (zeroes remain zeroes).
~
* Double, double, square, double, negate, to get -32 if the last number
* we read was non-zero. The double-0 at the end of the input leads to a
| zero being read as a unary number, which we use as the termination
* condition. When this is the case, the current cell will be 0 instead  
# of -32. The next lines are padding to get the jump right...












% So... if the unary number was not 0, jump back to the _.
\ Sort the list... the sort is descending, but we negated all the values...
< That means the largest value next to the pointer now, just with a minus
< sign. We move to the left three times to find the place where the third
< largest value is.
# Negate to get its positive value again.
` Duplicate to ensure we've got a cell to the left of the result.
< Move left to the other copy.
~ Logical NOT twice, to turn it into a 1.
~
> Move right to the result.
! This moves the pointer to the left (onto the 1) and executes "." (print)
. "result" times, printing the result in unary. Yay!

This relies on the interpreter as currently provided in the cop's answer, which slightly contradicts the documentation regarding % and !.

The main challenge here was parsing the input, since the \ makes finding the third-largest value fairly simply.

\$\endgroup\$
  • 1
    \$\begingroup\$ This is actually shorter than my intended solution! \$\endgroup\$ – kirbyfan64sos Oct 28 '15 at 17:22
6
\$\begingroup\$

Acc!, by DLosc

This langauge has terrible comparison support.

Count b while 0 {
}
Count c while 0 {
}
Count a while N-48 {
    Count q while N-48 {
    }
    Count a while _ {
        _ - 1
    }
    a - (q + 1)
    Count z while (z-(10^6+1)) * (_ - z) {
    }
    Count x while (_ - z) {
       b
       Count c while _ {
           _ - 1
       }
       a
       Count b while _ {
           _ - 1
       }
       q
       Count a while _ {
           _ - 1
       }
       z
    }
    z-((10^6)+1)
    Count x while _ {
        b - (q + 1)
        Count f while (f-(10^6+1)) * (_ - f) {
        }
        Count x while (_ - f) {
            b
            Count c while _ {
                _ - 1
            }
            q
            Count b while _ {
                _ - 1
            }
            f
        }
        f-((10^6)+1)
        Count x while _ {
            c - (q + 1)
            Count k while (k-(10^6+1)) * (_ - k) {
            }
            Count x while (_ - k) {
                q
                Count c while _ {
                    _ - 1
                }
                k
            }
            0
        }
        0
    }
    0
    Count j while (a - _) {
        _ + 1
    }
}
c
Write 49
Count h while _ {
    Write 49
    _ - 1
}

The count [varname] while 0 statements at the beginning are to declare the variable holding the largest number, the second largest number, the third largest number, and so on. The comparisons are accomplished by subtracting the two numbers then checking if the result is negative by checking if it is a number less that 10^6.

\$\endgroup\$
  • \$\begingroup\$ Ack! Good work, though this is very different from what I was going for. I was afraid someone might find a loophole. Back to the drawing board for Acc++! \$\endgroup\$ – DLosc Nov 1 '15 at 3:34
  • \$\begingroup\$ Acc!! has been posted ;) \$\endgroup\$ – DLosc Nov 1 '15 at 5:58
5
\$\begingroup\$

Zinc, by kirbyfan64sos

This was not that hard, once I understood how the language works. The difficult part was to get though parser errors, but adding some superfluous parentheses seemed to fix that. Here's the solution:

let
+=cut
in {d:{c:({b:{a:S^((#S)-_)-1}^_})+0$#c}^_=2}

Explanation

In the first and second rows, I define + to be the cut operation. The rest is set comprehensions. Let's take the input 101011101100 as an example, and start from the innermost one:

{a:S^((#S)-_)-1}

This takes those elements a from the input set S = {1,0,1,0,1,1,1,0,1,1,0,0} whose index is not len(S)-1, so all but the last one. I noticed that this also reverses the set, so the result is A = {0,1,1,0,1,1,1,0,1,0,1}. Next, the comprehension

{b:A^_}

takes all elements of A except the first and reverses it again, resulting in B = {1,0,1,0,1,1,1,0,1,1}. Then, we split B at the 0s (this results in {1,1,{1,1,1},{1,1}} or its reversal, I didn't check which one), and sort the result by length. Singleton sets are flattened, but they are all 1s so their length is still 1. Here's the code:

{c:(B)+0$#c}

The result of this is C = {{1,1,1},{1,1},1,1}. Finally, we filter out everything except the element at index 2 by

{d:C^_=2}

This results in the set D = {1} on our case. In general, it can have the form {{1,1,..,1}}, but this doesn't matter since only the 1s are printed.

\$\endgroup\$
4
\$\begingroup\$

Compass Soup, by BMac

This was fun.

Edit: this program must be prepended with a new line in order to work on BMac's interpreter. I can't seem to get the new line to appear in the code block.

!p#eXj0sXj0sp#exj#ss
   n Apw   w  n   w
s                  w
     s    w s         w   s    w         s    w           e s
eXj0seXj0sn ep0Yp+yXj0nYp#exj+sneXp exj#seXj+snep+eXj#sxj+nseXp exj#ss
n   w    ej#ns                e n   n   w    e n  n   w         n   w
                          n                                w         
s                                                                    w
             e          s
    y
s                     Yw
eXj+np yjCs       C    n
          ejBs    B pC n
                e A pB n
             ej0n 0 pA n
s                       w
              e s
exj#s X   eXj#nsejCsp1s
n   w     n        w  w
               w
@>
#

The program is divided into 4 execution sections.

The first, at line 1, appends a # to the end of the input by finding 00 and replacing the 2nd 0 with #. It also changes all 1s to As, since I wanted to have as few 1s in the source code as possible.

The second section, at line 5, fetches the second number in the input, and puts it below the first number as a string of +s. For example, if the input is 11011101100, then it will result in the following:

#AA00000AA0#
#+++

The third section, at line 12, combines the string of +s with the first number: each 0 above a + becomes A, A becomes B, B becomes C, and C remains unchanged. Afterwards, we go back to the 2nd section to fetch the next number.

Once all numbers have been combined this way, we reach the final section at line 18. The number of Cs is our desired output, so we change these to 1s, skipping the first C because there is a single 1 in the source code which is printed along with the output.

\$\endgroup\$
  • \$\begingroup\$ I'm glad it was fun! I had hoped that the use of 1s in the code would require you to clean the code out before ending, but I guess you circumvented that by using A instead :D. \$\endgroup\$ – BMac Nov 9 '15 at 21:49
  • 1
    \$\begingroup\$ My solution added. \$\endgroup\$ – BMac Nov 11 '15 at 18:54
  • \$\begingroup\$ @feersum I forgot I had modified the interpreter. Prepending my program with a new line should fix it. \$\endgroup\$ – cardboard_box Nov 12 '15 at 1:25
  • \$\begingroup\$ D'oh, that's a silly error. I'll fix my version of the interpreter. \$\endgroup\$ – BMac Nov 12 '15 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.