# Question
Title: Write program in your favorite language in another language
> The determined Real Programmer can write Fortran programs in any language.

*from Real Programmers Don't Use Pascal*

Your task is to write program in your programming language of choice, but you are allowed to use only another language. That is, throw away all coding conventions from one language and replace them with coding conventions from other language. The more the better. Make your program look as if it was written in another language.

For example, Python fan who hates Java could write following Python program in Java:

```
void my_function()                                                             {
    int i = 9                                                                  ;
    while(i>0)                                                                 {
        System.out.println("Hello!")                                           ;
        i = i - 1                                                              ;}}

```

Pascal enthusiast forced to use C could write this:

```
#define begin {
#define end }
#define then
#define writeln(str) puts(str)

if (i == 10) then
begin
    writeln("I hate C");
end

```

You have to write complete program. The program desn't have to do anything useful.

Good Luck. This is a popularity contest so the code with the most votes wins!

# Answer
# C in C++

```
#include <stdio.h>

int main(int argc, char** argv)
{
        printf("Hello world!\n");
        return 0;
}

```
> 143 votes

# Answer
# x86 assembly in GNU C

No, I didn't just use the `asm` keyword, since the question established this is for *real* programmers... this should run fine on ARM.

(Just to prove the point, I didn't "write" the assembly at all - it's the output produced by ~~GCC~~ Clang (503.0.38) for the commented code at the top, blindly translated into macros.)

This only works in 32-bit mode. That's fine since *real* programmers code to the word size anyway.

```
#include <stdio.h>
#include <stdint.h>
/*
int fac(int x) {
    if (x < 1) return 1; else return x * fac(x - 1);
}

int fib(int x) {
    if (x < 2) return x; else return fib(x - 1) + fib(x - 2);
}

int main(void) {
    int a = fib(10), b = fac(10);
    printf("%d %d\n", a, b);
    return 0;
}
*/

typedef union REG {
    intptr_t i; int _i; void * v; union REG * r;
} REG;

#define LPAREN (
#define RPAREN )
#define MACRO(N) ); N##_MACRO LPAREN

#define push MACRO(PUSH)
#define pop  MACRO(POP)
#define mov  MACRO(MOV)
#define sub  MACRO(SUB)
#define add  MACRO(ADD)
#define imul MACRO(IMUL)
#define cmp  MACRO(CMP)
#define jge  MACRO(JGE)
#define jmp  MACRO(JMP)
#define call MACRO(CALL)
#define ret  MACRO(RET) _
#define label MACRO(LABEL)

#define NO_OP(X)

#define PUSH_MACRO(VAL) *(esp -= 4) = (REG)(VAL)
#define POP_MACRO(DST) (DST) = (typeof(DST))(esp->i); esp += 4
#define MOV_MACRO(VAL, DST) (DST) = (typeof(DST))((REG)VAL).i;
#define SUB_MACRO(VAL, DST) CMP_MACRO(VAL, DST); \
    (DST) = (typeof(DST))(((REG)DST).i - ((REG)VAL).i)
#define ADD_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i + ((REG)VAL).i); \
    ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0
#define IMUL_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i * ((REG)VAL).i); \
    ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0
#define CMP_MACRO(L, R) CMP_MACRO_(((REG)L).i, ((REG)R).i)
#define CMP_MACRO_(L, R) (OF = 0, ZF = L == R, SF = (R - L) < 0)
#define JGE_MACRO(TGT) if (SF == OF) { goto TGT; } else {}
#define JMP_MACRO(TGT) goto TGT;
#define CALL_MACRO(PROC) CALL_MACRO_(PROC, __COUNTER__)
#define CALL_MACRO_(PROC, CTR) PUSH_MACRO(CTR - STARTIP); \
    goto PROC; case CTR - STARTIP:
#define RET_MACRO(_) eip = esp->i; esp += 4; if (eip) { continue; } else { goto *finalreturn; }
#define LABEL_MACRO(NAME) NAME

#define MY_ASM(X) do { const int STARTIP = __COUNTER__; \
    switch(eip) { case 0: MY_ASM_1 X } } while (1);
#define MY_ASM_1(X) MY_ASM_2(NO_OP LPAREN 0 X RPAREN;)
#define MY_ASM_2(X) X

#define CAT(L, R) _CAT(L, R)
#define _CAT(L, R) L##R

#define callASM(F) callASM_(F, CAT(_TMP_, __COUNTER__))
#define callASM_(F, LABEL) (({ PUSH_MACRO(0); stackbase = esp; finalreturn = &&LABEL; \
    goto F; LABEL:; }), (intptr_t)eax)

const int STACKSIZE = 4096;
REG callstack[STACKSIZE], * stackbase;
REG * eax, * ecx, * edx, * ebx, * esi, * edi, * esp, * ebp;
int SF, ZF, OF, eip; void * finalreturn;

int main(void) {
    eax = ecx = edx = ebx = esi = edi = esp = ebp = &callstack[STACKSIZE - 1];
    eip = 0;
    finalreturn = &&TOP; TOP:

    PUSH_MACRO(10);
    int a = callASM(_fac);
    PUSH_MACRO(10);
    int b = callASM(_fib);

    printf("%d %d\n", a, b);
    return 0;

    MY_ASM((
    label _fac:                                   // @fac
        push ebp
        mov esp, ebp
        sub 24, esp
        mov 8[ebp], eax
        mov eax, (-8)[ebp]
        cmp 1, (-8)[ebp]
        jge LBB0_2
        mov 1, (-4)[ebp]
        jmp LBB0_3
    label LBB0_2:
        mov (-8)[ebp], eax
        mov (-8)[ebp], ecx
        sub 1, ecx
        mov ecx, *esp
        mov eax, (-12)[ebp]         // 4-byte Spill
        call _fac
        mov (-12)[ebp], ecx         // 4-byte Reload
        imul eax, ecx
        mov ecx, (-4)[ebp]
    label LBB0_3:
        mov (-4)[ebp], eax
        add 24, esp
        pop ebp
        ret

    label _fib:                                   // @fib
        push ebp
        mov esp, ebp
        sub 24, esp
        mov 8[ebp], eax
        mov eax, (-8)[ebp]
        cmp 2, (-8)[ebp]
        jge LBB1_2
        mov (-8)[ebp], eax
        mov eax, (-4)[ebp]
        jmp LBB1_3
    label LBB1_2:
        mov (-8)[ebp], eax
        sub 1, eax
        mov eax, *esp
        call _fib
        mov (-8)[ebp], ecx
        sub 2, ecx
        mov ecx, *esp
        mov eax, (-12)[ebp]         // 4-byte Spill
        call _fib
        mov (-12)[ebp], ecx         // 4-byte Reload
        add eax, ecx
        mov ecx, (-4)[ebp]
    label LBB1_3:
        mov (-4)[ebp], eax
        add 24, esp
        pop ebp
        ret
    ))
}

```

Just look at all those casts. Casts mean I'm a *realer* programmer than the compiler, right?
> 125 votes

# Answer
# English in C

```
#include <stdio.h>
#define This
#define program     int main() {
#define aims
#define to
#define output      printf(
#define some
#define example
#define text(a)     #a
#define the
#define screen      "\n");
#define it
#define also
#define will
#define calculate   ;int a =
#define result
#define of
#define and
#define print       ; printf("%d\n", a);
#define seriously   return 0; }

This program aims to output some example text (Hello) to the screen;
it also will calculate the result of 3 + 4 and print the result; seriously

```

Any ideas to eliminate the `;`?
> 105 votes

# Answer
I think the brilliant Lennart Augustsson has already won this twice.

First, here's an example of his "weekend hack" implementation of BASIC as a Haskell Monadic DSL, from 2009:

```
import BASIC

main = runBASIC' $ do

    10 LET I =: 1
    20 LET S =: 0
    30 LET S =: S + 1/I
    40 LET I =: I + 1
    50 IF I <> 100000000 THEN 30
    60 PRINT "Almost infinity is"
    70 PRINT S
    80 END

```

It works by overloading the number type. The line numbers are really functions that accept arguments. The rest of the line is arguments to the function. The function returns a representation of the Abstract Syntax Tree for the BASIC interpreter to go to work on.

I also recommend you check out Augustsson's entry to the 2006 International Obfuscated C Contest, in which he managed to squeeze into 4k:

* A bytecode interpreter, written in a subset of C (which he calls Obfuscated C).
* An *Obfuscated C -\> bytecode* compiler, written in bytecode.

They can share the same file because the bytecode is placed inside C comments.

It's a few years since I followed Augustsson's work, so there may well be other brilliant things he's come up with since then....
> 74 votes

# Answer
## Brainfuck in JavaScript

Javascript is a difficult language ! Let us use Brainfuck, a more understandable language :o)

```
eval(

//write your easy code below

"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

//end of easy code

.replace(/\]/g,'}')
.replace(/\[/g,'while(a[i]){')
.replace(/\+/g,'a[i]++;')
.replace(/-/g,'a[i]--;')
.replace(/>/g,'i++;')
.replace(/</g,'i--;')
.replace(/\./g,'o+=String.fromCharCode(a[i]);')
.replace(/,/g,'a[i]=u.charCodeAt(j++);')
.replace(/^/,'var a=new Array(1000).join(\'0\').split(\'\'),i=500,o=\'\',u=prompt(\'Enter input if needed\'),j=0;')
.replace(/$/,'alert(o)')
)

```

I guess I wrote a brainfuck interpreter in javascript.

The example above simply ouputs `Hello World!` and ignore the input (no `,` symbol).
But that works with inputs too ! For example, try `,+>,+>,+>,+<<<.>.>.>.` and type `golf` in the dialog. It will ouputs the next characters in ASCII table : `hpmg`

**EDIT** : Short explanation for people who don't know brainfuck.
Imagine an infinite array of integers `a` initialized to zero everywhere, a pointer on one element of this array `i`, and a user input `u`.
Brainfuck is really easy to learn but difficult to write :

* `+` increments to current value : `a[i]++`
* `-` decrements it : `a[i]--`
* `>` makes to pointer points the next element : `i++`
* `<` the previous : `i--`
* `[` and `]` define a loop which breaks when current value is zero : `while (a[i]) { ... }`
* `.` print the current element : `String.fromCharCode(a[i])`
* `,` sets the current element with user input : `u.charCodeAt(...)`
> 73 votes

# Answer
# PHP and Javascript

This is a polyglot:

You can run this code in both languages:

```
if("\0"=='\0')
{
    function printf(){
        $b=Array();
        $a=$b['slice']['call'](arguments);
        $a=$a['join']('');
        console.log($a);
        return $a.length;
    };

    function strtoupper($s){return $s['toUpperCase']();}

    function count($a){return $a['length'];}
}

printf('this is cool!');

$c=Array('a','b','c','d');

for($i=0,$l=count($c);$i<$l;++$i)printf("\n",strtoupper($c[$i]));

```

The trick here is that Javascript uses escape sequences in strings starting with `'` and `"`.
On the other hand, PHP only uses escape sequences in strings starting with `"` and `<<<`.

Then, we declare the function `printf`, which is similar to `print` but outputs a formated string in PHP.

PHP **requires** that vars start with `$`, while Javascript simply allows.
> 71 votes

# Answer
**Brainfuck in JS**

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

```
> 56 votes

# Answer
This is one of the 2005 IOCCC winners, a C program that, except by that bunch of defines, looks like a java program:

```
/*
 * Sun's Java is often touted as being "portable", even though my code won't
 * suddenly become uber-portable if it's in Java. Truth is, Java's one of
 * the most ugly, slow, and straitjacketed languages ever. It's popular
 * mainly because people hear the word "portable" and go "ewww".
 *
 * This program, then, is dedicated to bringing about the death of Java. We
 * good coders have been oppressed for too long by the lame language
 * decisions of pointy-haired bosses and academics who should know better.
 * It's time we stand up against this junk, and bring back the fun in
 * programming! Viva La Revolution!
 */

#define aSet c
#define BufferedReader(x)1
#define byte Y[I][_^1]?do(:):_&1?do(.):do(`):8;++y;}
#define class int N=0,_,O=328,l=192,y=4,Y[80][64]={0},I;struct
#define do(c)a(#c "\b")
#define err c,c
#define getAllStrings(x));q()
#define if(x)b(#x)
#define IOException
#define line c
#define main(a)b(char*x){write(1,"\033[",2),null}main()
#define new
#define null a(x);}a(char*x){write(1,x,strlen(x));try;try;try;try;
#define out c,c
#define println(x)c
#define private int d(int
#define public short c;}c;typedef int BufferedReader;char*F="JF>:>FB;;BII";
#define return {return
#define static f(x){N=(N+x)%6,y--?f(0),f(1),f(4),f(1):++Y[(I=O+N[F]-66)
#define String
#define System c
#define this if(D):1,O=I,I/=16,l<_/32?if(B):l>_/32?if(A):2,l=_,_/=16,byte
#define throws
#define toArray(x)c
#define try for(;--c.c;)
#define void /16][(_=l+N[6+F]-66)/16]?O/=16,l/=32,O<I/16?if(C):O>I/16?this
#define while(k)if(2J),if(7;21H),f(0),f(4),f(4),if(H),/*

import java.io.*;
import java.util.*;

/**
 * A lame Java program.
 * @author  J. Random Worker
 */
class LameJavaApp
{

    /** The infamous Long-Winded Signature From Hell. */
    public static void main(String[] args)
        throws IOException
    {
        /* Don't get me started on this. */
        BufferedReader reader =
            new BufferedReader(new FileReader(args[0]));

        /* What, this long incantation just to print a string? */
        System.err.println("Hello world!");

        /* At least this is sane. */
        String line;
        while ((line = reader.readLine()) != null)
            System.out.println(line.length());
    }

    /**
     * Method with a needlessly long name.
     * @param   aSet        a set (!)
     */
    private String[] getAllStrings(Set<String> aSet)
    {
        /*
         * This dance is needed even in J2SE 5, which has type
         * templates. It was worse before that.
         */
        return aSet.toArray(new String[0]);
    }

}

```
> 53 votes

# Answer
# C++ in C

OK, so you are a C++ programmer, but are forced to use C? No problem, you just have to write some supplementary headers missing in C. For example, here's a valid Hello World program in C:

In the supplementary header file `iostream`, write:

```
#include <stdio.h>

#define using volatile int
#define namespace message
#define std = 0
#define message(x) printf("%s\n",x)
#define cout 0
#define endl 0

```

In file `string`, write

```
#define string

```

In file `helloworld.c` (your actual C code), write

```
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string message("Hello world");
  cout << message << endl;
  return 0;
}

```

And when compiling `helloworld.c` with a C compiler, instruct the compiler to also look for `<...>` header files wherever you stored the files `iostream` and `string`, for example, if you are compiling with gcc and put the files `iostream` and `string` in the current directory, compile with

```
gcc helloworld.c -o helloworld -I.

```

Note: The `volatile` in header `iostream` is there to enable a warning-free compile even at maximum warning level (a read from a volatile variable is considered to have an effect).
> 38 votes

# Answer
## CQL - Caffeinated Query Language

(or "SQL on Caffeine")

This may have been somewhat overly ambitious. Here is an attempt to write SQL(ish) declarative code in **CoffeeScript**. This requires the ECMAScript 6 Proxy feature. You can test it in node with `--harmony-proxies`.

Let's set up a template for defining proxies. (Taken from Benvie's comment on this issue)

```
forward = (->
  _slice  = Array.prototype.slice
  _bind   = Function.prototype.bind
  _apply  = Function.prototype.apply
  _hasOwn = Object.prototype.hasOwnProperty

  Forwarder = (target) ->
    @target = target
    this

  Forwarder.prototype =
    getOwnPropertyNames: -> Object.getOwnPropertyNames(@target)
    keys: -> Object.keys(@target)
    enumerate: ->
      i = 0
      keys = []
      for value of @target
        keys[i++] = value
      keys
    getPropertyDescriptor: (key) ->
      o = @target;
      while o
        desc = Object.getOwnPropertyDescriptor o, key
        if desc
          desc.configurable = true;
          return desc;

        o = Object.getPrototypeOf o
    getOwnPropertyDescriptor: (key) ->
      desc = Object.getOwnPropertyDescriptor @target, key
      if desc
        desc.configurable = true
      desc
    defineProperty: (key, desc) -> Object.defineProperty @target, key, desc
    get: (receiver, key) -> @target[key]
    set: (receiver, key, value) ->
      @target[key] = value;
      true
    has: (key) -> key of @target
    hasOwn: (key) -> _hasOwn.call @target, key
    delete: (key) ->
      delete @target[key]
      true
    apply: (receiver, args) -> _apply.call @target, receiver, args
    construct: (args) -> new (_bind.apply @target, [null].concat args);

  forward = (target, overrides) ->
    handler = new Forwarder target;
    for k of Object overrides
      handler[k] = overrides[k]

    if typeof target is 'function'
      return Proxy.createFunction handler,
                                  -> handler.apply this, _slice.call arguments,
                                  -> handler.construct _slice.call arguments
    else
      return Proxy.create handler, Object.getPrototypeOf Object target

  forward
)();

```

Now define a proxy object and some suspicious global variables and functions:

```
sql = forward {
  tables: {}

  finalize: ->
    if typeof @activeRows isnt 'function'
      @result = []
      for row in @activeRows
        @result.push (val for val, i in row when @activeTable.columns[i] in @activeColumns)
    delete @activeRows
    delete @activeColumns
    delete @activeTable

  run: (q) ->
    q.call(this)
    @finalize()
    result = @result
    delete @result
    if typeof result isnt 'function' then console.log result
    return result
}, {
  get: (o,name) ->
    if name of @target
      return @target[name];
    (args...) -> {
      name
      args
    }
}

int = Number
varchar = (l) -> String

TABLE = (x) -> x
INTO = (x) -> x
CREATE = (tableData) ->
  name = tableData.name
  table =
    columns: []
  column = tableData.args[0]
  table[column.name] = []
  table.columns.push(column.name)
  while column = column.args[1]
    table[column.name] = []
    table.columns.push(column.name)

  sql.tables[name] = table

  sql.result = "Created table '#{name}'"

INSERT = (table) -> sql.activeTable = sql.tables[table().name]
VALUES = (rows...) ->
  for row in rows
    for val, i in row
      column = sql.activeTable.columns[i]
      sql.activeTable[column].push val

  sql.result = "Inserted #{rows.length} rows"

FROM = (table) ->
  sql.activeTable = sql.tables[table().name]
SELECT = (columns...) ->
  sql.activeColumns = []
  for col in columns
    if typeof col is 'function'
      col = col()

    sql.activeColumns.push col.name

  sql.activeRows = []
  for val in sql.activeTable[sql.activeTable.columns[0]]
    sql.activeRows.push []

  for col in sql.activeTable.columns
    for val, i in sql.activeTable[col]
      sql.activeRows[i].push val

IN = (list) -> { op: 'in', list }
WHERE = (column) ->
  i = sql.activeTable.columns.indexOf(column.name)
  if column.args[0].op is 'in'
    list = column.args[0].list
    sql.activeRows = (row for row in sql.activeRows when row[i] in list)
  else
    console.log 'Not supported!'

ASC = 'asc'
DESC = 'desc'
BY = (x) -> x
ORDER = (column) ->
  i = sql.activeTable.columns.indexOf(column.name)
  order = if column.args[0] is sql.ASC then 1 else -1
  sql.activeRows.sort (a,b) ->
    if a[i] < b[i]
      return -order
    else if a[i] > b[i]
      return order
    else
      return 0

```

Well that was quite a lot of setup! But now we can do the following (input/output in a console style):

```
> sql.run ->
    CREATE TABLE @books(
      @title varchar(255),
      @author varchar(255),
      @year int
    );

Create Table 'books'

> sql.run ->
    INSERT INTO @books
    VALUES ['The C++ Programming Language', 'Bjarne Stroustrup', 1985],
           ['Effective C++', 'Scott Meyers', 1992],
           ['Exceptional C++', 'Herb Sutter', 2000],
           ['Effective STL', 'Scott Meyers', 2001];

Inserted 4 rows

> sql.run ->
    SELECT @title, @year FROM @books
    WHERE @author IN ['Bjarne Stroustrup', 'Scott Meyers']
    ORDER BY @year DESC;

[ [ 'Effective STL', 2001 ],
  [ 'Effective C++', 1992 ],
  [ 'The C++ Programming Language', 1985 ] ]

```

It's not an actual polyglot, but that's not really the point. I know that `@` is used for variables in SQL, but I need all the `@`s for column and table names because I haven't found a way to proxy the global object (and I wouldn't be surprised if it's really not possible - and for a good reason).

I also changed some parentheses into brackets (in particular after `VALUES` and `IN`). Unfortunately, what I couldn't figure out at all is a way to allow normal conditionals like `year > 2000`, because they would evaluate to a boolean right away.

Still this looks a lot like SQL and is definitely more declarative than imperative/functional/object-oriented so it should qualify nicely for the question. I'm actually thinking if I polished the code a bit and supported a few more features, this could be a useful CoffeeScript module.

Anyway, this was fun! :)

For those not too familiar with CoffeeScript, the SQL queries compile to the following JavaScript:

```
sql.run(function() {
  return CREATE(
    TABLE(
      this.books(
        this.title(varchar(255),
        this.author(varchar(255),
        this.year(int)))
      )
    )
  );
});

sql.run(function() {
  INSERT(INTO(this.books));
  return VALUES([...], ['Effective C++', 'Scott Meyers', 1992], [...], [...]);
});

sql.run(function() {
  SELECT(this.title, this.year(FROM(this.books)));
  WHERE(this.author(IN(['Bjarne Stroustrup', 'Scott Meyers'])));
  return ORDER(BY(this.year(thisESC)));
});

```
> 35 votes

# Answer
# Visual Basic 6 (in JavaScript)

```
'; Main sub-routine \
'; function Main() { ' \
Sub Main() '
    ' Do not throw any errors... \
    On Error Resume Next '; MsgBox = alert

    ' Show a message box... \
    MsgBox(1 / 0) '

    ' Show errors again... \
    On Error GoTo 0 '

    ' Show another message box... '
    MsgBox("Hello")
    ' ' } ' \
End Sub '

Main()

```

It also works in VBScript.
> 26 votes

# Answer
## F# in C++

Rather unimaginative and nasty abuse of the preprocessor. I thought it'd be fun to alter C++ to look like a completely dissimilar language instead of using a few aliases to make it look like Java or PHP. I'm not really expecting this to garner a ton of upvotes, it's a just-for-fun entry.

```
#define let int
#define args ( int __, char* args[] ) { int ___
#define println printf(
#define exit "\n" ); return 0; }
#include <stdio.h>

let main args =
    println "F# is better than C++"
    exit

```

Try it here.

Sadly writing something to STDOUT is about all it can do, although I'm sure if someone threw enough witchcraft at it they could make it do more.
> 19 votes

# Answer
# Python and... nobody will guess (edit: dc)

Here is some valid python code, but actually the program is written in a very different language:

```
# Initialize systems 1 and 2
# frame 1, divergency speed and divergency latency
f1ds, f1dl, z1 = [2,2,0]
# frame 2, divergency speed and divergency latency
f2ds, f2dl, z2 = [4,4,1]

# Set the most relevant value of ax (detected by low-energy collision)
ax = 42.424242

# Initialize list of successive energy states
s = [17.98167, 21.1621, 34.1217218, 57.917182]

# Most common value for nz parameter
# TODO: check if value from the article of A. Einstein is better
nz = 10

if z2>nz or ax in s:
  ax += 6
  f1ds = 8
  f2ds = 16
  z1 = 4
  z2 = 9

f1dl += z1
f2dl += z2

# main loop, iterate over all energy states
# Warning: hit Ctrl-C if nuclear explosion occurs and adjust either z or nz
for k in s:
  z = nz + k
  f1dl = f1ds + f2dl * z - z1 + 3.14
  f2dl = f2ds + f1dl * z - z2 + 10
  if k > 10 or z-2 in s:
    nz += 0xac  # hexadecimal coefficient found in famous article by E. Fermi

```

The code runs in both languages with no error.

The combination is very crazy; I would be happy to wait one day or two before telling which is the other language; please leave comments for guessing.

**edit:** The language was the stack-based language from dc. You may see here well-known keywords like `for`, `if`, `or`, `in`, but only the letters matter! The `,` which has no meaning in dc is turned to a register because the first time it appears is after the letter `s` (the same for `:`).
> 19 votes

# Answer
C++ allows you to write lisp-like code, with the InteLib library:

```
(L|DEFUN, ISOMORPHIC, (L|TREE1, TREE2),
   (L|COND,
     (L|(L|ATOM, TREE1), (L|ATOM, TREE2)),
     (L|(L|ATOM, TREE2), NIL),
     (L|T, (L|AND,
       (L|ISOMORPHIC, (L|CAR, TREE1),
                      (L|CAR, TREE2)),
       (L|ISOMORPHIC, (L|CDR, TREE1),
                      (L|CDR, TREE2))
 )))).Evaluate();

```

cf. http://www.informatimago.com/articles/life-saver.html
> 17 votes

# Answer
# C# in Whitespace

Okay, first try at one of these, so let's see how it goes.

```
using System; //very important

namespace ConsoleApplication1  //namespace: name whatever you want
{
 //start
 class  Program  //class name:  also anything
    {
    //main function
    static void Main(string[] args) {
        for(int i=0;i<10;i++)   writeOutput(i);
    } //end main
    static void writeOutput(int i) { Console.WriteLine(i); }    //display output

    } //class ends here

}  //close namespace:   also very important

//yay!

```

And in case the formatting went screwy from having to put four spaces at the front of each line, here it is again with . for space and # for tab:

```
using.System;.//very.important#

namespace.ConsoleApplication1..//namespace:#name.whatever.you.want##
{.
.//start#
.class#Program..//class.name:#also.anything#.
#{
....//main.function#
#static.void.Main(string[].args).{
....#for(int.i=0;i<10;i++)#writeOutput(i);#
#}.//end.main#
#static.void.writeOutput(int#i).{.Console.WriteLine(i);.}#//display.output#

.
.#}.//class.ends.here.##

}..//close.namespace:#also.very.important#.#
.

//yay!

```
> 15 votes

# Answer
# HTML and CSS

Not programming languages, but … this document is valid HTML *and* CSS:

```
<!-- p{color:red} /* -->
<!Doctype html>
<title>This is HTML and CSS</title>
<p>Hi!</p>
<!-- */ -->

```

```
<!-- p{color:red} /* -->
<!Doctype html>
<title>This is HTML and CSS</title>
<p>Hi!</p>
<!-- */ -->

```

This works, because HTML comments are allowed in stylesheets for historical reasons. Oh, and every valid HTML document is a valid PHP program too, so this is also **PHP**. :)
> 12 votes

# Answer
# C in Scala

The bridging layer emulates a more romantic era when strings were still null terminated arrays of bytes.

```
// Scala is a dynamic language
import scala.language.{ dynamics, postfixOps }

val self = this

val argc = args.length
val argv = args.map(_.getBytes)

type char = Array[Byte]
object char extends Dynamic {
  // This program uses expanded memory
  val buffers = new scala.collection.mutable.LinkedHashMap[String, char]

  // Malloc char buffer
  def applyDynamic(name: String)(length: Int) =
    buffers(name) = new Array(length)

  def **(argv: Array[Array[Byte]]) = argv
}

object & extends Dynamic {
  // dereference char pointer
  def selectDynamic(name: String) = char.buffers(name)
}

def printf(format: String, buffers: char*) =
  println(
    (format /: buffers){ case (msg, buffer) =>
      // Read string until \0 terminator
      val value = new String(buffer.takeWhile(0 !=))
      // Replace next %s token
      msg.replaceFirst("%s", value)
    }
  )

def scanf(format: String, buffers: char*) =
  buffers foreach { buffer =>
    val line = Console.readLine()
    // Write string to char* buffer
    line.getBytes(0, line.length, buffer, 0)
    // Remember to always null terminate your strings!
    buffer(line.length) = 0
  }

val PATH_MAX = 4096

implicit class Argumenter(args: Pair[_, _]) {
  def apply[T](f: => T) = f
}

object int {
  // Passthrough
  def main[T](f: => T) = f
  def argc = self.argc
}

// terminates the string after the first character
// investigate switching to "xor eax, eax" instead of having a hardcoded 0
// might save 3 bytes and valuable CPU time with this trick
val initialize = (_: char)(1) = 0

def exit(value: Int) = sys.exit(value)

```

```
// ---HOMEWORK-ASSIGNMENT-START---

int main(int argc, char **argv) {
  if (argc != 0) {
    printf("This program does not take parameters!");
    exit(1);
  }

  // I've copy pasted this code from somewhere
  // Code reuse is essential if we want to be DRY
  char first(PATH_MAX + 1);
  char last(PATH_MAX + 1);

  printf("Enter your first and last name:\n");
  scanf("%s%s", &first, &last);

  // Still learning references, do I need these here?
  // I've performed benchmarks on printf and I think it's faster this way
  printf("Your full name is %s %s", &first, &last);

  initialize(&first);
  printf("Your signature is %s. %s", &first, &last);

  exit(0);
}

```
> 10 votes

# Answer
# sed and APL

My boss wants me to write sed scripts, but I like rather writing APL all the day. Nevertheless, he is very happy with my job because such scripts run perfectly with his version of sed:

```
i ← g ← 42
a ← d ← 10
s/s←2⊤42/s←2⊤43/g
s/s[01]*1/s⊣1/g
g

```

You can try it on my new website with this permalink. It is a compiled to javascript version of GNU APL. Final release will be later with official release of GNU APL, v. 1.3 but you can perfectly use it for your permalinks if you enjoy GNU APL.
> 8 votes

# Answer
# C in Haskell

```
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Array
import Foreign.Ptr
import System.Environment
import System.Exit

-- The meat of the program

cmain :: (CInt, Ptr (Ptr CChar)) -> IO CInt
cmain(argc, argv) = do {
    putStr("hello, world\n");
    return 0;
}

-- Of course, the above function doesn't do anything unless we write a wrapper
-- around it.  This could have been done more simply, using higher-level library
-- functions, but where's the fun in that?

main :: IO ()
main = do {
    args <- getArgs;
    argPtrs <- sequence [do {
        argPtr <- mallocArray0(length(arg)) :: IO (Ptr CChar);
        pokeArray0(0)(argPtr)(map(castCharToCChar)(arg));
        return argPtr;
    } | arg <- args ];
    argv <- mallocArray(length(argPtrs)) :: IO (Ptr (Ptr CChar));
    pokeArray(argv)(argPtrs);

    exitCode <- cmain(fromIntegral(length(args)),argv);

    if (exitCode == 0) then do {
        exitWith(ExitSuccess);
    } else do {
        exitWith(ExitFailure(fromIntegral(exitCode)));
    };
}

```

Of course, since `cmain` doesn't do anything with `argc` or `argv`, the argument-marshaling code has no effect, and since `cmain` always returns 0, the "else" branch of the "if" statement is dead. But the "if" statement doesn't do anything anyway.

All of the braces and semicolons are unnecessary, as are most of the parentheses and some of the `do` keywords. The "if" statement could have been written as `if exitCode == 0 then exitWith ExitSuccess else exitWith (ExitFailure (fromIntegral exitCode))`.
> 7 votes

# Answer
## C++ in Forth

```
: #include ; : <iostream> ; : { ; : } ; : int ; : using ;
: namespace ; : std; ; : main() ; : cout ; : << ;
: "Hello,  ; : world!\n"; S" Hello, world!" type ; : return ; : 0; ;

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, world!\n";
}

```

Not the most flexible solution, but it works if written exactly as shown.
> 7 votes

# Answer
# Haskell in Java

("vanilla" Java 7, not Java 8) (Yes, I know that boxing ruins performance; and even trying to use higher order functions gets crazy verbose :D)

Java has very rigid syntax, so instead of changing syntax I tried to make code semantically more similar to Haskell style.

Edit — added partial function application.

```
import java.util.Iterator;

interface Function1<A, B> {
    A call(B arg);
}

interface Function2<A, B, C> {
    A call(B arg1, C arg2);
}

class Reduce<A> implements Function2<A, Function2<A, A, A>, Iterable<A>> {

    @Override
    public A call(Function2<A, A, A> arg1, Iterable<A> arg2) {
        final Iterator<A> i = arg2.iterator();
        A r = i.next();
        while (i.hasNext())
            r = arg1.call(r, i.next());
        return r;
    }
}

class Range implements Iterable<Integer> {

    private final int min;
    private final int max;

    public Range(int min, int max) {
        this.min = min;
        this.max = max;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = min;

            @Override
            public boolean hasNext() {
                return i <= max;
            }

            @Override
            public Integer next() {
                return i++;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}

public class Main {

    public static <A, B, C> Function1<A, C> applyPartial(final Function2<A, B, C> f, final B arg2) {
        return new Function1<A, C>() {
            @Override
            public A call(C arg) {
                return f.call(arg2, arg);
            }
        };
    }

    public static void main(String[] args) {

        final Function1<Integer, Iterable<Integer>> product = applyPartial(new Reduce<Integer>(), new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer arg1, Integer arg2) {
                return arg1 * arg2;
            }
        });

        final Function1<Integer, Integer> fact = new Function1<Integer, Integer>() {

            @Override
            public Integer call(Integer arg) {
                return product.call(new Range(1, arg));
            }
        };

        final Integer x = fact.call(6);

        System.out.println(x.toString());
    }
}

```

(Yes, all that this madness does is computing `6!`)
> 7 votes

# Answer
**COBOL in AWK**

In the spirit of the quote. Pure, unadulterated AWK, as it may be written by a COBOL programmer.

The task is to count the records on a file. This early development version is counting itself for testing. The correct file will be hard-coded later when released from Unit Testing...

If I could get the syntax highlighting to do phosphorescent-green on black, it would be great...

Even got the column-numbers correct on this one, that's seven blanks at the start of each line (never done that in awk before) and breaking the long print statements at column 72.

```
   BEGIN {
       PERFORM_000_INITIALISATION()
       PERFORM_100_OPEN_FILES()
       PERFORM_200_PROCESS_FILE()
       PERFORM_300_CLOSE_FILES()
       PERFORM_400_SHOW_THE_COUNTS()
       exit
   }
   function PERFORM_000_INITIALISATION() {
       INPUT_FILE_NAME = "COBOL.AWK"
       RECORD_COUNT = 0
   }
   function PERFORM_100_OPEN_FILES() {
   }
   function PERFORM_200_PROCESS_FILE() {
       PERFORM_210_PRIMING_READ()
       PERFORM_220_PROCESS_INPUT_UNTIL_END()
   }
   function PERFORM_300_CLOSE_FILES() {
   }
   function PERFORM_400_SHOW_THE_COUNTS() {
       print "COBOL.AWK: NUMBER OF RECORDS READ IS " RECORD_COUNT
   }
   function PERFORM_210_PRIMING_READ() {
       PERFORM_900_READ_THE_FILE()
       if ( FILE_STATUS < 0 ) {
           print "COBOL.AWK ERR0001: INVALID FILE, HALTING, FILE N" \
                 "AME IS: " INPUT_FILE_NAME
           exit
           }
       if ( FILE_STATUS == 0 ) {
           print "COBOL.AWK ERR0002: NO RECORDS ON INPUT, HALTING," \
                 "FILE NAME IS: " INPUT_FILE_NAME
           exit
           }
   }
   function PERFORM_220_PROCESS_INPUT_UNTIL_END() {
       while ( FILE_STATUS != 0 ) {
           INPUT_RECORD = $0
           RECORD_COUNT = RECORD_COUNT + 1
           PERFORM_900_READ_THE_FILE()
           }
   }
   function PERFORM_900_READ_THE_FILE() {
       FILE_STATUS = getline < INPUT_FILE_NAME
   }

```
> 6 votes

# Answer
## SML in Java

I still have some ancient code around from when I started learning Java and tried to use it in a functional style. Slightly cleaned up:

```
/**
 * Genericised ML-style list.
 */
public class FunctionalList<T>
{
    private final T head;
    private final FunctionalList<T> tail;

    public FunctionalList(T x, FunctionalList<T> xs) {
        this.head = x;
        this.tail = xs;
    }

    public static <T> FunctionalList<T> cons(T x, FunctionalList<T> xs) {
        return new FunctionalList<T>(x, xs);
    }

    public static <T> T hd(FunctionalList<T> l) {
        return l.head;
    }

    public static <T> FunctionalList<T> tl(FunctionalList<T> l) {
        return l.tail;
    }

    public static int length(FunctionalList<?> l) {
        return len(l, 0);
    }

    private static int len(FunctionalList<?> l, int n) {
        return l == null ? n : len(tl(l), n + 1);
    }

    public static <T> FunctionalList<T> rev(FunctionalList<T> l) {
        return rev(l, null);
    }

    private static <T> FunctionalList<T> rev(FunctionalList<T> a, FunctionalList<T> b) {
        return a == null ? b : rev(tl(a), cons(hd(a), b));
    }

    public static <T> FunctionalList<T> append(FunctionalList<T> a, FunctionalList<T> b) {
        return a == null ? b : cons(hd(a), append(tl(a), b));
    }
}

```
> 5 votes

# Answer
# Java in Perl

May count as rule breaking, but I don't care. Obviously, it's intended to look like Java program. It prints 20 Fibonacci numbers, in case it isn't obvious.

> Requires **Inline::Java** module to be installed.

```
use Inline Java => <<'JAVA';
/**
 * @author  Konrad Borowski <x.fix@o2.pl>
 * @version 0.1.0
 */
class Fibonacci
{
    /**
     * Responsible for storing the number before last generated number.
     */
    private long beforeLastNumber = 0;

    /**
     * Responsible for storing the last generated number.
     */
    private long lastNumber = 1;

    /**
     * Receives the next Fibonacci number.
     *
     * @return long integer that is the next Fibonacci number
      */
    public long next()
    {
        long temponaryLastNumber = lastNumber;
        lastNumber = beforeLastNumber + lastNumber;
        beforeLastNumber = temponaryLastNumber;
        return temponaryLastNumber;
    }

    /**
     * Outputs the Fibonacci number to standard output.
     */
    public void printFibonacci()
    {
        System.out.println(next());
    }

    /**
     * Outputs the Fibonacci number to standard output given number of
     * times.
     *
     * @param times number of times to print fibonacci number
     */
    public void printFibonacciTimes(int times)
    {
        int i;
        for (i = 0; i < times; i++) {
            printFibonacci();
        }
    }

    /**
     * Constructor for Fibonacci object. Does nothing.
     */
    public Fibonacci()
    {
        // Do nothing.
    }
}
JAVA

###
 # The executable class that shows 20 Fibonacci numbers.
 ##
package OutputFibonacci
{
    ###
     # Shows 20 Fibonacci numbers. This method is public,
     # static, and returns void.
     ##
    sub main()
    {
        # In Perl, -> is object method separator, not a dot. This is stupid.
        new Fibonacci()->printFibonacciTimes(20);
    }
}

# Perl doesn't automatically call main method.
OutputFibonacci::main();

```
> 5 votes

# Answer
## Brainfuck (or anything else) in Racket

Racket's flexible module and macro system allows it to implement module support for entirely new languages, both domain-specific and general-purpose. There is out of the box support for both Datalog and Algol 60, so the following are both valid Racket programs:

```
#lang datalog
edge(a, b). edge(b, c). edge(c, d). edge(d, a).
path(X, Y) :- edge(X, Y).
path(X, Y) :- edge(X, Z), path(Z, Y).
path(X, Y)?

#lang algol60
begin
  integer procedure SIGMA(x, i, n);
    value n;
    integer x, i, n;
  begin
    integer sum;
    sum := 0;
    for i := 1 step 1 until n do
      sum := sum + x;
    SIGMA := sum;
  end;
  integer q;
  printnln(SIGMA(q*2-1, q, 7));
end

```

You can also add support for other languages: e.g. see Danny Yoo's description of how to implement support for Brainfuck, which permits Racket programs such as:

```
#lang planet dyoo/bf
++++++[>++++++++++++<-]>.
>++++++++++[>++++++++++<-]>+.
+++++++..+++.>++++[>+++++++++++<-]>.
<+++[>----<-]>.<<<<<+++[>+++++<-]>.
>>.+++.------.--------.>>+.

```

And since the support is added at the compiled module level, it's possible to link modules written in different languages or embed a snippet of one language inside a module written in another.
> 5 votes

# Answer
# J and... nobody will guess (edit: dc)

This is my second entry; here is a piece of valid J code, which returns 1:

```
10 o. 1 r. 2 i. 4 [ ( 0:`1: @. (2&|)) ] 8 #: *:@+: 42

```

I am waiting one or two day before telling which is the other language running the very same piece of code with no error. Just leave comments for trying to guess.

**edit:** The other language is the stack-based language from the very ancient Unix calculator dc.
> 4 votes

# Answer
# dc running a PostScript file

dc can run the following piece of code with no error:

```
10 10 10 10 10 42 32 10 10
stop % first send a stop
0 0 srand rand
le pop pop 3.14 sin
lt 2 3 lt and pop
le 2 10 le xor
pop pop pop 1 0 0
<< /sox 2 >> [ exch begin sox end ] aload
3.14 floor

```
> 4 votes

# Answer
# ML/(Strict) Haskell in Java

This is from an actual real project. It makes use of persistent immutable data structures and uses recursion even when not necessary. Actually, it's more like Kore (the language the project implements) in Java, but the style is basically the same as ML. But the philosophy of Kore is that the author shouldn't format his code, so none of the Java code is formatted either (it's autoformatted by eclipse).

drop n elements from a list:

```
  public static <T> List<T> drop(List<T> l, Integer n) {
    return n == 0 ? l : drop(l.cons().tail, n - 1);
  }

```

In ML/Haskell, where you'd pattern match to extract the head and tail, here you say `list.cons().x` and `list.cons().tail`.

insert an element in a list:

```
  public static <T> List<T> insert(List<T> l, Integer i, T x) {
    if (i == 0)
      return cons(x, l);
    return cons(l.cons().x, insert(l.cons().tail, i - 1, x));
  }

```

List is defined literally how the algebraic datatype would be defined. Here is a version with the eclipse-generated boilerplate removed:

```
public final class List<T> {

  public static final class Nil<T> {
  }

  public static final class Cons<T> {
    public final T x;
    public final List<T> tail;

    public Cons(T x, List<T> tail) {
      if (x == null)
        throw new RuntimeException("null head");
      if (tail == null)
        throw new RuntimeException("null tail");
      this.x = x;
      this.tail = tail;
    }
  }

  private final Nil<T> nil;
  private final Cons<T> cons;

  private List(Nil<T> nil, Cons<T> cons) {
    this.nil = nil;
    this.cons = cons;
  }

  public boolean isEmpty() {
    return nil != null;
  }

  public Nil<T> nil() {
    if (nil == null)
      throw new RuntimeException("not nil");
    return nil;
  }

  public Cons<T> cons() {
    if (cons == null)
      throw new RuntimeException("not cons");
    return cons;
  }

  public static <T> List<T> cons(Cons<T> cons) {
    if (cons == null)
      throw new RuntimeException("constructor received null");
    return new List<T>(null, cons);
  }

  public static <T> List<T> nil(Nil<T> nil) {
    if (nil == null)
      throw new RuntimeException("constructor received null");
    return new List<T>(nil, null);
  }
}

```

Here is a map data structure implemented in terms of a trie:

```
public final class Map<K, V> {
  private final Tree<Character, Optional<Pair<K, V>>> tree;
  // keys are sorted in reverse order so entrySet can use cons instead of append
  private final Comparer<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> comparer =
      new PairLeftComparer<Character, Tree<Character, Optional<Pair<K, V>>>>(
          new ReverseComparer<Character>(new CharacterComparer()));

  private Map(Tree<Character, Optional<Pair<K, V>>> tree) {
    this.tree = tree;
  }

  public static <K, V> Map<K, V> empty() {
    return new Map<K, V>(new Tree<Character, Optional<Pair<K, V>>>(
        OptionalUtils.<Pair<K, V>> nothing(),
        ListUtils
            .<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> nil()));
  }

  public Optional<V> get(K k) {
    Tree<Character, Optional<Pair<K, V>>> t = tree;
    for (char c : k.toString().toCharArray()) {
      Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c);
      if (t2 == null)
        return nothing();
      t = t2;
    }
    if (t.v.isNothing())
      return nothing();
    return some(t.v.some().x.y);
  }

  public Map<K, V> put(K k, V v) {
    return new Map<K, V>(put(tree, k.toString(), v, k));
  }

  private Tree<Character, Optional<Pair<K, V>>> put(
      Tree<Character, Optional<Pair<K, V>>> t, String s, V v, K k) {
    if (s.equals(""))
      return new Tree<Character, Optional<Pair<K, V>>>(some(Pair.pair(k, v)),
          t.edges);
    char c = s.charAt(0);
    Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c);
    if (t2 == null)
      return new Tree<Character, Optional<Pair<K, V>>>(
          t.v,
          sort(
              cons(
                  pair(
                      c,
                      put(new Tree<Character, Optional<Pair<K, V>>>(
                          OptionalUtils.<Pair<K, V>> nothing(),
                          ListUtils
                              .<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> nil()),
                          s.substring(1), v, k)), t.edges), comparer));
    return new Tree<Character, Optional<Pair<K, V>>>(t.v, sort(
        replace(pair(c, put(t2, s.substring(1), v, k)), t.edges), comparer));
  }

  private List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> replace(
      Pair<Character, Tree<Character, Optional<Pair<K, V>>>> edge,
      List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> edges) {
    if (edges.cons().x.x.equals(edge.x))
      return cons(edge, edges.cons().tail);
    return cons(edges.cons().x, replace(edge, edges.cons().tail));
  }

  // I consider this O(1). There are a constant of 2^16 values of
  // char. Either way it's unusual to have a large amount of
  // edges since only ASCII chars are typically used.
  private Tree<Character, Optional<Pair<K, V>>> getEdge(
      Tree<Character, Optional<Pair<K, V>>> t, char c) {
    for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> p : iter(t.edges))
      if (p.x.equals(c))
        return p.y;
    return null;
  }

  public Map<K, V> delete(K k) {
    return new Map<K, V>(delete(tree, k.toString()).x);
  }

  private Pair<Tree<Character, Optional<Pair<K, V>>>, Boolean> delete(
      Tree<Character, Optional<Pair<K, V>>> t, String k) {
    if (k.equals(""))
      return pair(
          new Tree<Character, Optional<Pair<K, V>>>(
              OptionalUtils.<Pair<K, V>> nothing(), t.edges), t.edges.isEmpty());
    char c = k.charAt(0);
    Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c);
    if (t2 == null)
      return pair(t, false);
    Pair<Tree<Character, Optional<Pair<K, V>>>, Boolean> p =
        delete(t2, k.substring(1));
    List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> edges = nil();
    for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> e : iter(t.edges))
      if (!e.x.equals(c))
        edges = cons(e, edges);
    if (!p.y)
      return pair(
          new Tree<Character, Optional<Pair<K, V>>>(t.v, cons(pair(c, p.x),
              edges)), false);
    boolean oneEdge = t.edges.cons().tail.isEmpty();
    return pair(new Tree<Character, Optional<Pair<K, V>>>(t.v, edges), oneEdge
        && t.v.isNothing());

  }

  public static class Entry<K, V> {
    public Entry(K k, V v) {
      this.k = k;
      this.v = v;
    }

    public final K k;
    public final V v;

  }

  public List<Entry<K, V>> entrySet() {
    return entrySet(ListUtils.<Entry<K, V>> nil(), tree);
  }

  private List<Entry<K, V>> entrySet(List<Entry<K, V>> l,
      Tree<Character, Optional<Pair<K, V>>> t) {
    if (!t.v.isNothing()) {
      Pair<K, V> p = t.v.some().x;
      l = cons(new Entry<K, V>(p.x, p.y), l);
    }
    for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> e : iter(t.edges))
      l = entrySet(l, e.y);
    return l;
  }
}

```

The types start to take up as much space as the code. For example, in put, the method has 302 characters of types and 343 characters of code (not counting space/newlines).
> 3 votes

# Answer
# BASIC in Ruby

Implemented this long ago. The source is on GitHub. Inspired by a similar thing in Scala

## Setup

```
#!/usr/bin/env ruby

if caller.empty? && ARGV.length > 0
  $file = ARGV[0]
else
  $file = caller.last.split(':').first
end

require 'pp'

class String
  def %(other)
    self + other.to_s
  end
end

class RBaysick
  @@variables = {}
  @@code = []
  @@line = 0

  def initialize(contents)
    $DONT_RUN = true # To avoid endless loops.

    contents.gsub!(/( |\()'([^\W]+)/, '\1:\2 ')

    contents.gsub!(/(^| |\()(:[^\W]+)/, '\1GET(\2)')

    contents.gsub!(/ IF (.*) THEN (.*)/, ' IF { \1 }.THEN { GOTO \2 }')
    contents.gsub!(/LET *\(([^ ]+) *:= *(.*)\)/, 'LET(\1) { \2 }')
    contents.gsub!(/(LET|INPUT)(\(| )GET\(/, '\1\2(')
    contents.gsub!(/ \(/, '(')

    contents.gsub!(/^(\d+) (.*)$/, 'line(\1) { \2 }')

#    contents.gsub!(/(\)|\}|[A-Z]) ([A-Z]+)/, '\1.\2')

    contents.gsub!(/ END /, ' __END ')
    contents.gsub!(/^RUN/, '__RUN')

    puts contents if $DEBUG
    eval contents
  end

  def __RUN
    while @@line > -1
      puts "#{@@line}: #{@@code[@@line].inspect}" if $DEBUG
      unless @@code[@@line].nil?
        @@increment = true
        @@code[@@line].call
        next unless @@increment
      end
      @@line += 1
    end
  end

  class If < Struct.new(:value)
    def THEN
      yield if value
    end
  end

  def method_missing(name, *args)
    puts "Missing: #{name.to_s}(#{args.map(&:inspect).join(', ')})" if $DEBUG
  end

  def variables
    @@variables
  end

  def line(line, &block)
    @@code[line] = block
  end

  def add(line, cmd, *args)
    puts "DEBUG2: #{cmd.to_s}(#{args.map(&:inspect).join(', ')})" if $DEBUG
    @@code[line] = send(cmd, *args)
  end

  def IF
    ::RBaysick::If.new(yield)
  end

  def PRINT(str)
    puts "PRINT(#{str.inspect})" if $DEBUG
    puts str
    true
  end

  def LET(name, &block)
    puts "LET(#{name.inspect}, #{block.inspect})" if $DEBUG
    @@variables[name] = block.call
  end

  def GET(name)
    puts "GET(#{name.inspect}) #=> #{@@variables[name].inspect}" if $DEBUG
    @@variables[name]
  end

  def INPUT(name)
    puts "INPUT(#{name.inspect})" if $DEBUG
    LET(name) { $stdin.gets.chomp.to_i }
  end

  def ABS(val)
    puts "ABS(#{val.inspect}) #=> #{val.abs.inspect}" if $DEBUG
    val.abs
  end

  def GOTO(line)
    @@increment = false
    @@line = line
  end

  def __END
    exit
  end
end

RBaysick.new(open($file).read) unless $DONT_RUN || ($0 != __FILE__)

```

## BASIC code

```
#!./rbaysick.rb

10 PRINT "Welcome to Baysick Lunar Lander v0.0.1"
20 LET ('dist := 100)
30 LET ('v := 1)
40 LET ('fuel := 1000)
50 LET ('mass := 1000)

60 PRINT "You are a in control of a lunar lander."
70 PRINT "You are drifting towards the surface of the moon."
80 PRINT "Each turn you must decide how much fuel to burn."
90 PRINT "To accelerate enter a positive number, to decelerate a negative"

100 PRINT "Distance " % 'dist % "km, " % "Velocity " % 'v % "km/s, " % "Fuel " % 'fuel
110 INPUT 'burn
120 IF ABS('burn) <= 'fuel THEN 150
130 PRINT "You don't have that much fuel"
140 GOTO 100
150 LET ('v := 'v + 'burn * 10 / ('fuel + 'mass))
160 LET ('fuel := 'fuel - ABS('burn))
170 LET ('dist := 'dist - 'v)
180 IF 'dist > 0 THEN 100
190 PRINT "You have hit the surface"
200 IF 'v < 3 THEN 240
210 PRINT "Hit surface too fast (" % 'v % ")km/s"
220 PRINT "You Crashed!"
230 GOTO 250
240 PRINT "Well done"

250 END

RUN

```
> 3 votes

# Answer
# Haskell in C++ templates

I made this FizzBuzz in C++ templates a few months ago on a lark. It is pretty much an implementation of the following Haskell code, all in C++ templates. In fact, even the integer arithmetic is reimplemented at the type level --- notice that none of the templates use int parameters!

The Haskell code:

```
import Control.Monad

m `divides` n = (n `mod` m == 0)

toFizzBuzz n
    | 15 `divides` n = "FizzBuzz"
    |  5 `divides` n = "Buzz"
    |  3 `divides` n = "Fizz"
    |      otherwise = show n

main = mapM_ putStrLn $ take 100 $ map toFizzBuzz [1..]

```

and the C++ template metaprogramming version:

```
//
//  Lazy compile-time fizzbuzz computed by C++ templates,
//  without conditionals or the use of machine arithmetic.
//
//         -- Matt Noonan (mnoonan@grammatech.com)

#include <iostream>

using namespace std;

//
//  The natural numbers: Nat = Zero | Succ Nat
//

template <typename n>
struct Succ
{
  typedef Succ eval;
  static const unsigned int toInt = 1 + n::toInt;
  static void print(ostream & o) { o << toInt; }
};

struct Zero
{
  typedef Zero eval;
  static const unsigned int toInt = 0;
  static void print(ostream & o) { o << toInt; }
};

//
//  Arithmetic operators
//    Plus Zero n = n
//    Plus Succ(n) m = Plus n Succ(m)
//    Times Zero n = Zero
//    Times Succ(n) m = Plus m (Times n m)
//

template <typename a, typename b>
struct Plus
{
  typedef typename Plus<typename a::eval,
                        typename b::eval>::eval eval;
};

template <typename M>
struct Plus <Zero, M>
{ typedef typename M::eval eval; };

template <typename N, typename M>
struct Plus <Succ<N>, M>
{ typedef typename Plus<N, Succ<M> >::eval eval; };

template <typename a, typename b>
struct Times
{
  typedef typename Times<typename a::eval,
                         typename b::eval>::eval eval;
};

template <typename M>
struct Times <Zero, M>
{ typedef Zero::eval eval; };

template <typename N, typename M>
struct Times <Succ<N>, M>
{ typedef typename Plus<M,
                        typename Times<N,M>::eval
                        >::eval eval; };

//
//  Lists
//

struct Nil
{
  typedef Nil eval;
  static void print(ostream & o) { }
};

template <typename x, typename xs>
struct Cons
{
  typedef Cons eval;
  static void print(ostream & o) {
    x::eval::print(o); o << endl; xs::eval::print(o);
  }
};

//
//  Take the first n elements of a list
//

template <typename, typename> struct Take;

template <typename _> struct Take<Zero,_>
{ typedef Nil eval; };

template <typename n, typename x, typename xs>
struct Take<Succ<n>, Cons<x,xs> >
{
  typedef Cons<x, Take<n, xs> > eval;
};

template <typename a, typename b>
struct Take
{
  typedef typename Take<typename a::eval,
                        typename b::eval>::eval eval;
};

//
//  Iterate f x0 makes the infinite list
//  x0, f(x0), f(f(x0)), ...
//

template <template<typename> class f, typename x0> struct Iterate
{
  typedef Cons<x0, Iterate<f, f<x0> > > eval;
};

//
//  Map a function over a list
//

template <template<typename> class a, typename b> struct Map
{ typedef typename Map<a,
                       typename b::eval>::eval eval;
};

template <template<typename> class f>
struct Map<f, Nil>
{ typedef Nil eval; };

template <template<typename> class f, typename x, typename xs>
struct Map<f, Cons<x,xs> >
{
  typedef Cons<f<x>, Map<f,xs> > eval;
};

//
//  Some useful things for making fizzes and buzzes
//

struct Fizz
{ static void print(ostream & o) { o << "Fizz"; } };

struct Buzz
{ static void print(ostream & o) { o << "Buzz"; } };

struct FizzBuzz
{ static void print(ostream & o) { o << "FizzBuzz"; } };

//
//  Some useful numbers
//

typedef Succ<Zero> One;
typedef Succ<One> Two;
typedef Succ<Two> Three;
typedef Plus<Two, Three> Five;
typedef Times<Two, Five> Ten;
typedef Times<Three, Five> Fifteen;
typedef Times<Ten, Ten> OneHundred;

//
//  Booleans
//

struct True {};
struct False {};

//
//  If/then/else
//

template <typename p, typename t, typename f>
struct If
{
  typedef typename If<typename p::eval, t, f>::eval eval;
  static void print(ostream & o) { eval::print(o); }
};

template <typename t, typename _>
struct If<True, t, _>
{
  typedef t eval;
};

template <typename _, typename f>
struct If<False, _, f>
{ typedef f eval; };

//
//  Testing if x divides y
//

template <typename a, typename b, typename c>
struct _Divides
{
  typedef typename _Divides<typename a::eval,
                            typename b::eval,
                            typename c::eval>::eval eval;
};

template <typename _, typename __>
struct _Divides<_, __, Zero> { typedef False eval; };

template <typename a>
struct _Divides<a, Zero, Zero> { typedef True eval; };

template <typename a, typename b>
struct _Divides<a, Zero, b>
{
  typedef typename _Divides<a, a, b>::eval eval;
};

template <typename _, typename n, typename m>
struct _Divides<_, Succ<n>, Succ<m> >
{
  typedef typename _Divides<_, n, m>::eval eval;
};

template <typename a, typename b>
struct Divides
{
  typedef typename _Divides<a, a, b>::eval eval;
};

//
//  "Otherwise" sugar
//

template <typename a>
struct Otherwise
{
  typedef typename a::eval eval;
  static void print(ostream & o) { a::eval::print(o); }
};

//
//  Convert a number to fizzes, buzzes as appropriate
//

template <typename n>
struct toFizzBuzz
{
  typedef typename
    If< Divides<Fifteen, n>, FizzBuzz,
    If< Divides<   Five, n>,     Buzz,
    If< Divides<  Three, n>,     Fizz,
    Otherwise<                   n
    > > > >::eval eval;
};

int main(void)
{
  // Make all of the natural numbers
  typedef Iterate<Succ, One> Naturals;

  // Apply fizzbuzz rules to every natural number
  typedef Map<toFizzBuzz, Naturals> FizzBuzzedNaturals;

  // Print out the first hundred fizzbuzzed numbers
  Take<OneHundred, FizzBuzzedNaturals>::eval::print(cout);

  return 0;
}

```
> 3 votes

# Answer
# Ruby in JavaScript

```
Number.prototype.times = function(f){
  for (var i=this; --i;) f()
}
end = 0
function do(s) {return new Function(s)}

//;# Ruby starts here:
(5).times(do("alert('hi!'); end"))

```
> 2 votes

# Answer
# Asp in PHP

```
fskdfkz

```

Well I know, not very useful.
> 1 votes

# Answer
# ALGOL in C

Steve Bourne already won this contest by writing the original sh in ALGOL in C.

```
#define IF      if(
#define THEN    ){
#define ELSE    } else {
#define ELIF    } else if (
#define FI      ;}

#define BEGIN   {
#define END     }
#define SWITCH  switch(
#define IN      ){
#define ENDSW   }
#define FOR     for(
#define WHILE   while(
#define DO      ){
#define OD      ;}
#define REP     do{
#define PER     }while(
#define DONE    );
#define LOOP    for(;;){
#define POOL    }

```

and

```
LOCAL VOID      gsort(from,to)
        STRING          from[], to[];
{
        INT             k, m, n;
        REG INT         i, j;

        IF (n=to-from)<=1 THEN return FI

        FOR j=1; j<=n; j*=2 DONE

        FOR m=2*j-1; m/=2;
        DO  k=n-m;
            FOR j=0; j=0; i-=m
                DO  REG STRING *fromi; fromi = &from[i];
                    IF cf(fromi[m],fromi[0])>0
                    THEN break;
                    ELSE STRING s; s=fromi[m]; fromi[m]=fromi[0]; fromi[0]=s;
                    FI
                OD
            OD
        OD
}

```
> 1 votes

# Answer
An operating system where all of the C is also valid Ruby: https://github.com/duckinator/corundum

To run as Ruby: `ruby src/kernel.rb`

To compile and run the operating system: `make qemu`

Output of both is `Hello, world!\n`
> 1 votes

# Answer
## Commodore 64 Basic, BBC Basic etc.

Cheeky entry:

```
10 PRINT "HELLO WORLD"
20 GOTO 10
RUN

```

I did think about including Spectrum since you can type `GOTO`, but it renders `GO TO`, so technically not the same.
> 0 votes

# Answer
HTML in PHP

First thing that came to my mind was apparently stolen by @toscho . But i'm not giving up yet,

```
<?php
echo "<title>This is HTML in PHP</title>";
echo "<p>Now Beat This!!!</p>";
echo "<br>";
?>

```
> -6 votes

---
Tags: popularity-contest
---


# Question
Title: Drawing an Image Based on a Trace of its Hue
# Introduction

Local genius Calvin's Hobbies recently challenged us to trace the hue of an image. It is recommended to read his challenge beforehand, but to highlight the main points:

* The trace of hue in an image can be found by starting at one pixel, finding its hue angle(`hue = atan2(sqrt(3) * (G - B), 2 * R - G - B)`), and moving one pixel's width in that direction. If this process is repeated, and a black pixel is left at each pixel passed, we produce a trace of the image.

Here is a simple example of the trace:

We start at pixel `250, 250`, with RGB color `36, 226, 132`. We observe that the hue of this color is 150. Thus, we begin drawing a black line 150 degrees counterclockwise from the positive x-axis. We run into the square to the left, with RGB color `100, 220, 7` and hue 94. This results in an almost vertical line to the next square. We continue the pattern into every square, and observe the change in slope at each new color. The length of this trace was 300 pixels. If you're wondering why the image is so ugly, it's because I randomly generated 25 colors in 100x100 squares and used my answer to trace it. On a much more complex and beautiful image, we may get a trace like this one:

* Calvin created this wonderful code snippet on the original post that draws a trace over an image, starting at the point provided by the mouse cursor. This is a very useful testing tool!

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>canvas{border:1px solid black;}</style>Load an image: <input type='file' onchange='load(this)'><br><br>Max length <input id='length' type='text' value='300'><br><br><div id='coords'></div><br><canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas><script>function load(t){if(t.files&&t.files[0]){var e=new FileReader;e.onload=setupImage,e.readAsDataURL(t.files[0])}}function setupImage(t){function e(t){t.attr("width",img.width),t.attr("height",img.height);var e=t[0].getContext("2d");return e.drawImage(img,0,0),e}img=$("<img>").attr("src",t.target.result)[0],ctx=e($("#c")),ctxRead=e($("<canvas>"))}function findPos(t){var e=0,a=0;if(t.offsetParent){do e+=t.offsetLeft,a+=t.offsetTop;while(t=t.offsetParent);return{x:e,y:a}}return void 0}$("#c").mousemove(function(t){function e(t,e){var a=ctxRead.getImageData(t,e,1,1).data,i=a[0]/255,r=a[1]/255,o=a[2]/255;return Math.atan2(Math.sqrt(3)*(r-o),2*i-r-o)}if("undefined"!=typeof img){var a=findPos(this),i=t.pageX-a.x,r=t.pageY-a.y;$("#coords").html("x = "+i.toString()+", y = "+r.toString());var o=parseInt($("#length").val());if(isNaN(o))return void alert("Bad max length!");for(var n=[i],f=[r],h=0;n[h]>=0&&n[h]<this.width&&f[h]>=0&&f[h]<this.height&&o>h;)n.push(n[h]+Math.cos(e(n[h],f[h]))),f.push(f[h]-Math.sin(e(n[h],f[h]))),h++;ctx.clearRect(0,0,this.width,this.height),ctx.drawImage(img,0,0);for(var h=0;h<n.length;h++)ctx.fillRect(Math.floor(n[h]),Math.floor(f[h]),1,1)}});</script>
```

<sup> Snippet tested in Google Chrome </sup>

* Answers to that challenge may also serve as appropriate testing tools for this challenge.

*Note: I do not take any credit for Calvin's work, and have received explicit permission to use his ideas in this challenge.*

# The Challenge

In that challenge, we found the trace. Now, I'm asking you to find the image. You will be given a start point, an end point, and a `length`, and your program must output an image whose trace beginning at the start point arrives at the end point in approximately `length` pixels. Moreover, because there are so many options, your program's algorithm must be inherently random in some regard--thus the same input should (more often than not) produce a different output image.

# Input

You will receive seven positive integers as input: `w, h, x1, y1, x2, y2, len` where:

* `x1, x2 < w <= 1920`
* `y1, y2 < h <= 1080`
* `len < 2000`

These guidelines are minimum requirements. Your program may accept higher values.

You may receive input through stdin, a file, or as arguments to a function. You will ONLY receive these 5 integers as input.

# Output

As output, produce an image of width `w` and height `h` with a continuous hue trace from `x1,y1` to `x2, y2` in approximately `len` pixel-width steps.

* Output should be random.
* Output may be in any format--whether it be .bmp, .png, PPM, or an image shown on-screen at runtime makes no difference.
* You may assume it is possible to move from `x1, y1` to `x2, y2` in under `len` pixels.
* Output should NOT show the path of the trace from `x1, y1` to `x2, y2`--though an image showing this path in your answer is appreciated.

# Rules

* This is a popularity-contest! Try to make your output beautiful or interesting. More interesting hue traces than straight lines are also recommended.
* This is **not** code-golf. As such, readable code is appreciated. Still, try to keep size below ~2KB. This rule will not be strictly enforced.
* Values are approximate. If your code's trace reaches its destination within ~5-10% of `len` pixels, this is acceptable. Along this same vein, do not worry about slightly incorrect hue angle values. Some error is reasonable.
* This is graphical-output. **Please** include output images of your solution in your answer.
* Standard Loopholes apply.

*Questions, comments, concerns? Let me know!*

# Answer
All the code is on bitbucket(it is completely unoptimised). The hue path tracing logic is my own so might differ slightly from that in the original question. Instead of trying to work out a function to generate a line and then an image from that, it makes multiple sets of random changes to a starting image and then picks the set where the end of the path is closest to the target end, then repeats.

I think it looks kinda artistic sometimes. The current randomisation method just draws randomly coloured rectangles, if you run the program yourself you can watch it iterating. With 60 generations (and 70 children per generation) it basically always gets within a pixel of the target. I tried swapping individual pixels but that was too slow. Plain rectangles was the best (simple) way of changing the image that I tried which still created interesting output. I might see how well circles work later.
> 7 votes

---
Tags: popularity-contest, graphical-output, random
---


# Question
Title: Generate a random floating point number between 2 limits
This challenge is to generate a random floating-point number between 2 limits. You may use any language so long as it can be called from the command line, and runs on linux. It must also be able to work with negative numbers.

Due to the comment below: You may use fixed point math to come up with a result in-fact fixed point math is preferable in this case.

# Input Requirements

Accept a lower and upper limit, no verification required.

# Output Requirements

* Must be between the 2 specified limits
* Print it out to the console
* or come up with a way to return it to the shell.

## Example

```
$ prog -1 1
-.445

```

The program would not spit out a result that is not between those 2 limits. And it would be inclusive of the 2 limits

# Win Condition

As with all of these challenges the smallest number of bytes wins.

# Answer
> 4 votes
# Cjam, 9 bytes

```
q~1$-dmr+

```

Assumes that the first input number is the lower limit and the second one is the upper limit.

Pretty straight forward code:

```
q~          "Read the input as a string and evaluate it. This puts the two input";
            "integers on stack";
  1$        "Copy the first smaller integer and put it on top of stack";
    -       "Take difference of smaller and larger integer";
     d      "Convert the integer to double";
      mr    "Get a random double float from 0 to the difference of two integers";
        +   "Add the random double to the smaller integer to get random in range";

```

Try it online here

# Answer
> 3 votes
# Ruby, 34 bytes

```
a,b=$*.map &:to_f
$><<a+(b-a)*rand

```

Takes inputs via command-line argument as in the usage example.

# Answer
> 3 votes
# Pyth - 9 bytes

Works the obvious way like all the others.

```
+*-vzQOZQ

```

Pyth's random range function when called with zero as the argument acts as a \[0, 1) floating point generator.

```
+          Add and implicitly print
 *         Times
  -        Difference
   vz      Input 1
   Q       Input 2
  OZ       Float RNG
 Q         Input 2

```

Try it here.

# Answer
> 1 votes
# R, 34

Setup for running from command-line

```
i=scan('stdin');runif(1,i[1],i[2])

```

Takes input from STDIN

Example on windows

```
C:\Program Files\R\R-3.1.3\bin\x64>rscript -e "i=scan('stdin');runif(1,i[1],i[2])"
1
2
^Z
Read 2 items
[1] 1.249665

C:\Program Files\R\R-3.1.3\bin\x64>

```

# Answer
> 0 votes
# C#, ~~142~~ 141 bytes

C# has too much boilerplate...
Anyways, it is the only language I know and am sure can be compiled and run in Linux.

```
using System;class A{static void Main(string[]a){var b=double.Parse(a[0]);Console.Write(new Random().NextDouble()*(double.Parse(a[1])-b)+b);}

```

Ungolfed:

```
using System;
class A
{
    static void Main(string[] a)
    {
        var b = double.Parse(a[0]);
        Console.Write(new Random().NextDouble() * (double.Parse(a[1]) - b) + b);
    }
}

```

Also, I just noticed that every example's input was integral. In that case...

# C#, 135 bytes, integral input

```
using System;class A{static void Main(string[]a){int b=int.Parse(a[0]);Console.Write(new Random().NextDouble()*(int.Parse(a[1])-b)+b);}

```

Ungolfed:

```
using System;
class A
{
    static void Main(string[] a)
    {
        int b = int.Parse(a[0]);
        Console.Write(new Random().NextDouble() * (int.Parse(a[1]) - b) + b);
    }
}

```

---
Tags: code-golf, random
---


# Question
Title: Grid Based Digital Logic (Duodyadic Tiles)
Duodyadic tiles are kinds of square function blocks that take two inputs, one from their top side and one from their left side, and have two outputs, one on their right side and one on their bottom side. Each of their outputs is a separate function of both of their inputs.

For example, if `#` represents a generic tile, the right output `R` is a function `f` of inputs `T` and `L`, and the bottom output `B` is another function `g` of `T` and `L`:

```
 T
L#R         R = f(T, L)
 B          B = g(T, L)

```

(The tiles are termed "duo" since there are two functions, and "dyadic" since both functions have two arguments.)

Tiles can then be composed together on a grid, the outputs of one tile going directly into the inputs of the tiles it neighbors. Here for example, the right output of the left `#` goes into the left input of the right `#`:

```
 AB         D = f(f(A, C), B)
C##D        E = g(A, C)
 EF         F = g(f(A, C), B)

```

You can imagine that given a set of duodyadic tiles, each with specific functionality, complex (and potentially useful) compositions could be made.

In this challenge, we'll only be concerned with the traditional set of ten logic based duodyadic tiles, where all the inputs and outputs are single-bit binary numbers (zeros or ones). We'll use a separate ASCII character to denote each type of tile.

The tile characters and their input-output relations are as follows:
(`T` is for top input, `L` for left input, `R` for right output, `B` for bottom output.)

1. Zero: `0` or  (space) → `R = 0`, `B = 0`
2. One: `1``R = 1`, `B = 1`
3. Cross: `+``R = L`, `B = T`
4. Mirror: `\``R = T`, `B = L`
5. Top only: `U``R = T`, `B = T`
6. Left only: `)``R = L`, `B = L`
7. Not: `!``R = not L`, `B = not T`
8. And: `&``R = L and T`, `B = L and T`
9. Or: `|``R = L or T`, `B = L or T`
10. Xor: `^``R = L xor T`, `B = L xor T`

# Challenge

Write a program or function that takes in a rectangular grid of the characters `0 1+\U)!&|^` that represents a "circuit" made using the ten logic based duodyadic tiles. You also need to take in two strings of `0`'s and `1`'s; one will be the left input column and one will be the top input row. Your program/function needs to print/return the bottom output row and the right output column (also in `0`'s and `1`'s).

For example, in this grid

```
+++
+++

```

all the inputs flow straight across the grid to the outputs

```
 ABC
D+++D
E+++E
 ABC

```

so an input of `010`/`01` would have output `010`/`01`:

```
 010
0+++0
1+++1
 010

```

The exact output of your program would be `[bottom output row]\n[right output column]` or `[bottom output row]/[right output column]`:

```
010
01

```

or

```
010/01

```

If you wrote a function, you could return the two strings in a tuple or list (or still print them).

# Details

* Take the three inputs as strings in any reasonable manner (preferably in the order grid, top row, left column): command line, text file, sdtin, function arg.
* You can assume the input row and column lengths will match the grid dimensions and will only contain `0`'s and `1`'s.
* Your grid must use the proper characters (`0 1+\U)!&|^`). Remember that `0` and  mean the same thing.

# Test Cases

(Read I/O as `top`/`left``bottom`/`right`.)

**Nand:**

```
&!

```

`00`/`0``01`/`1`
`00`/`1``01`/`1`
`10`/`0``01`/`1`
`10`/`1``11`/`0`

**All ones:**

```
1111
1\+\
1+\+
1\+\

```

Any input should result in `1111`/`1111`.

**Xor from Nand:** (note the column of trailing spaces)

```
\)+\
U&!&
+! !
\&!&
   !

```

`00000`/`00000``00000`/`00000`
`00000`/`10000``00010`/`00000`
`10000`/`00000``00010`/`00000`
`10000`/`10000``00000`/`00000`

**Zig zag:**

```
+++\00000000
000\!!!!\000
00000000\+++

```

The first bit of the left input becomes the last bit of the right output. Everything else is `0`.

`000000000000`/`000``000000000000`/`000`
`000000000000`/`100``000000000000`/`001`

**Propagation:**

```
)))
UUU
U+U
U+U
UUU

```

The first bit of the left input goes to all the outputs.

`000`/`00000``000`/`00000`
`000`/`10000``111`/`11111`

**Here's a pastebin of all 1×1 grid test cases.**

# Scoring

The shortest submission in bytes wins.

Bonus: What cool "circuits" can you make?

P.S. Don't bother Googling "duodyadic tiles". I made them up yesterday ;D
If you want to discuss expanding this idea into a full-fledged programming language, come to this chatroom.

# Answer
# Pyth, 122

Kind of a monster. Uses simply recursion, nothing fancy like dynamic programming.

```
D:NGHR@Cm+d[1HG&GH|GHxGH0),[GH!G)[HG!H)x"+\\!1U)&|^"N#aYw)M:@@YGH?hgGtHHv@eYG?egtGHGv@ePYHjkm+0egtleYklePYjkm+0hgbtlePYleY

```

Online demonstration.

Input is in the following way: First the grid (no escaping, no extra symbols) and then the two lines of input, e.g. (Zig zag)

```
+++\00000000
000\!!!!\000
00000000\+++
000000000000
100

```
> 8 votes

# Answer
# C, ~~332~~ ~~309~~ ~~272~~ ~~270~~ ~~266~~ ~~259~~ ~~247~~ 225 bytes

```
#define C(x)*c-x?
i,k,T,L,m;f(c,t,l)char*c,*t,*l;{while(L=l[i]){for(k=0;T=t[k];c++)L=C(49)C(43)C(92)C(85)C(41)C(33)C(38)C('|')C(94)T=48:(T^=L-48):(T|=L):(T&=L):(T^=1,L^1):(T=L):T:(m=T,T=L,m):L:(T=49),t[k++]=T;c++;l[i++]=L;}}

```

View results online here!

This defines a function `void f(char*, char*, char*)`, which should take the board as its first input, then the top row of input, and then the left row of input.

Here's what I used to test it:

```
#include "stdio.h"
int main() {
    char buf[1024],top[33],left[33];
    /* Copy and paste an example circuit as the first input,
       and put a 'Q' immediately after it.
       Note that the Q is never touched by the function f, and is used
       solely as a delimiter for input. */
    scanf("%[^Q]Q ",buf);
    /* Then enter your top inputs */
    scanf("%[01]%*[^01]", top);
    /* Then your left ones */
    scanf("%[01]", left);
    /* OUTPUT: Bottom\nRight */
    f(buf, top, left);
    return 0;
}

```

Thus, by inputting Sp3000's 2-bit multiplier:

```
UUUU))))
UU++)))&
UUU+)  U
UU++&))U
U++&+)^U
U)&\&)UU
   U+^UU
   \&UUUQ
11110000
00000000

```

We get:

```
00001001
11111111

```

~~On another note, with Sp3000's half adder in mind, I'd like to see a full adder...~~ One of you guys did it! I don't think the system stands on its own as a programming language, but it's been very interesting. This seems like an excellent target for metagolf, though!

# A Short Explanation:

Here's the unraveled, commented code:

```
/* We define the first half of the ?: conditional operator because, well,
   it appears over and over again. */
#define C(x)*c-x?
/* i,k are counting variables
   T,L are *current* top and left inputs */
i,k,T,L,m;
f(c,t,l)char*c,*t,*l;{
    /* The outer loop iterates from top to bottom over l and c */
    while(L=l[i]){
        /* Inner loop iterates from left to right over t and c */
        for(k=0;T=t[k];c++)
            /* This line looks awful, but it's just a bunch of character
            comparisons, and sets T and L to the output of the current c */
            L=C(49)C(43)C(92)C(85)C(41)C(33)C(38)C('|')C(94)T=48:(T^=L-48):(T|=L):(T&=L):(T^=1,L^1):(T=L):T:(m=T,T=L,m):L:(T=49),
            /* Write our output to our input, it will be used for the next row */
            t[k++]=T;
        c++; /*Absorbs the newline at the end of every row */
        /* Keep track of our right-most outputs,
        and store them in the handy string passed to the function. */
        l[i++]=L;
    }
    /* Bottom output is now stored entirely in t, as is right output in l */
}

```

We iterate over `c`, left to right (then top to bottom), rewriting the `t` inputs each time and pushing out a right-most output which is shoved into the `l` string. We can imagine this as replacing the top row of `c` with `1`'s and `0`'s iteratively, and keeping track of the bits that are pushed out at the right.

Here's a more visual sequence, row by row:

```
 111
1&+^  =>  110 ->0  =>     ->0  =>     0 Thus, "01" has been written to l,
1+&+     1+&+         110 ->1         1
                                  110   And "110" is stored currently in t.

```

This obviously gets more complicated with different symbols and sizes, but the central idea holds. This works only because data never flows up or left.
> 8 votes

# Answer
# Mathematica, ~~331~~ ~~276~~ ~~270~~ ~~267~~ ~~264~~ ~~262~~ ~~252~~ 250 bytes

```
Print@@@{#[[2;;,-1,2]],#[[-1,2;;,1]]}&@MapIndexed[h=Characters;({r@#2,b@#2}=<|##|>&@@Thread[h@"0 1+\\)U!&|^"->{0,0,1,i={##},{#2,#},##,1-i,1##,Max@i,(#-#2)^2}]&[r[#2-{1,0}],b[#2-{0,1}]]@#{1,1})&,Join[h@{"0"<>#3},h@StringSplit[#2<>"
"<>#,"
"]],{2}]&

```

The  is a private-use Unicode character which Mathematica uses as a superscript `T`, i.e. it's the transposition operator.

Here is a more readable version:

```
Print @@@ {#[[2 ;;, -1, 2]], #[[-1, 2 ;;, 1]]} &@
  MapIndexed[h = Characters;
   (
     {r@#2, b@#2} = <|##|> & @@ Thread[
            h@"0 1+\\)U!&|^" -> {
              0,
              0,
              1,
              i = {##},
              {#2, #},
              ##,
              1 - i,
              1 ##,
              Max@i,
              (# - #2)^2
              }] & [
          r[#2 - {1, 0}],
          b[#2 - {0, 1}]
          ] @ # {1, 1}
     ) &,
   Join[
    h@{"0" <> #3},
    h@StringSplit[#2 <> "\n" <> #, "\n"]\[Transpose]
   ],
   {2}] &

```

This is an unnamed function which takes the three strings for grid, top and left inputs and prints the bottom and right outputs.

## Explanation

Let's go through this step by step (I'll try not to assume any Mathematica knowledge). You sort of need to read the code back to front. The basic algorithm just sweeps through the lines computing each function and storing the results in `f` to be accessed by subsequent tiles.

### Input processing

That's this bit:

```
Join[
  h@{"0" <> #3},
  h@StringSplit[#2 <> "\n" <> #, "\n"]\[Transpose]
]

```

This merely splits the grid into a nested list of characters (note that I defined `h` as an alias for `Character` somewhere in the code) and then prepends a row and a column with the inputs. This works, because `1` and `0` are also the names of the constant-function tiles, so actually putting them on the has the same effect as feeding the inputs in manually. Since these are functions they will technically take their input from outside the grid, but since they are constant functions that doesn't matter. The top left corner gets a `0` but this is fairly arbitrary since the results of that tile are never used.

Also note the transposition. Adding columns takes more characters than adding rows, so I transpose the grid after adding the top row. This means that top/bottom and left/right are swapped for the main part of the program, but they're completely exchangeable so it doesn't matter. I just need to make sure to return the results in the correct order.

### Solving the grid

*(This section is slightly outdated. Will fix once I'm really sure I'm done golfing.)*

Next up, we run `MapIndexed` over the inner level of this nested list. This calls the anonymous function provided as the first argument for each character in the grid, *also* giving it a list with the current two coordinates. The grid is traversed in order, so we can safely calculate each cell based on the previous ones.

We use the variables `r`(ight) and `b`(ottom) as lookup tables for the results of each cell. Our anonymous function has the current coordinates in `#2`, so we get the inputs to any cell with

```
r[#2 - {1, 0}],
b[#2 - {0, 1}]

```

Note that in the first row and column this will access undefined values of `r` and `b`. Mathematica doesn't really have a problem with that and will just give you back your coordinates instead, but we discard this result anyway, since all tiles in that row/column are constant functions.

Now this thing:

```
<|##|> & @@ Thread[
  h@"0 1+\\U)!&|^" -> {
     z = {0, 0}, z, o = 1 + z, {##}, ...
  }] &

```

Is a golfed form of

```
<|"0" -> (z = {0, 0}), " " -> z, "1" -> (o = 1 + z), "+" -> {##}, ... |> &

```

Which in turn is a function which, given the two tile inputs, returns an Association (you'd call it a hashmap or a table in other languages), that contains all the possible tile results for these two inputs. To understand, how all the functions are implemented, you need to know that the first argument of such a function can be accessed with `#` and the second with `#2`. Furthermore, `##` gives you a sequence of both arguments which can be used to "splat" the arguments.

* `0`: is straightforward, we just return a constant `{0, 0}` and also assign this to `z` for future use (e.g. in the space tile).
* `1`: is essentially just `{1,1}`, but having `z` this is shortened to `1+z`. We also save this in `o`, because it'll come in handy for all the tiles where both outputs are identical.
* `+`: Here we make use of the sequence. `{##}` is the same as `{#,#2}` and passes both inputs through unchanged.
* `\`: We swap the two arguments, `{#2,#}`.
* `U`: Now we can make use of `o`. `o#2` means `{1,1}*#2` so we just put the top argument into both outputs.
* `)`: Analogously for the left argument: `o#`.
* `!`: Bitwise not is annoying in Mathematica, but since we only ever have `0` and `1`, we can simply subtract both inputs from `1` (thereby inverting them) and pass them on: `1-{##}`.
* `&`: This one is quite nifty. First we notice that bitwise and for `0` and `1` is identical to multiplication. Furthermore, `o##` is the same as `o*#*#2`.
* `|`: Again, we use an equivalent function. Bitwise or is the same as `Max` in this case, so we apply `Max` to the input arguments and multiply the result into `{1,1}`.
* `^`: The shortest I've found for xor is to take the difference and square it (to ensure positivity), so we've got `o(#-#2)^2`.

After this function completes and returns the full association we use the current cell's character to pull out the element we're interested in and store it in `r` and `b`. Note that this is also the return value of the anonymous function used in `MapIndexed`, so the mapping will actually give me a grid of all the results.

### Output processing

`MapIndexed` returns a 3D grid, where the first dimension corresponds to the horizontal grid coordinate (remember the earlier transposition), the second dimension corresponds to the vertical grid coordinate and the third indicates whether we've got a bottom or a left output. Note that this also contains the input row and column which we need to get rid of. So we access the bottom row's bottom output with

```
#[[2;;,-1,2]]

```

and the final column's right output with

```
#[[-1,2;;,1]]

```

Note that `2;;` is a range from the second to the last element.

Lastly, we apply `Print` to both of those (using `@@@` as the syntactic sugar for second-level `Apply`), which just prints all of its arguments back-to-back (and since it's applied to two separate expressions, there will be a newline between bottom and right output).
> 8 votes

# Answer
# Python 2, ~~384~~ ~~338~~ 325 bytes

```
def f(G,T,L):
 def g(x,y):
  if x>-1<y:l=g(x-1,y)[1];t=g(x,y-1)[0];r=l,t,1-l,0,0,1,t,l,l&t,l|t,l^t;i="+\\!0 1U)&|^".index(G[y*-~W+x]);return((t,l,1-t)+r[3:])[i],r[i]
  return(int((y<0)*T[x]or L[y]),)*2
 H=G.count("\n")+1;W=len(G)/H;return eval('"".join(map(str,[g(%s]for _ in range(%s)])),'*2%('_,H-1)[0','W','W-1,_)[1','H'))

```

Seriously CH, if this isn't a toy already you should start ringing up some toy factories.

More golfed and much less efficient now, but still haven't caught up to CarpetPython. Input like `f("1111\n1\\+\\\n1+\\+\n1\\+\\","0101","1010")`, output is a tuple of two strings. Make sure the board doesn't have a trailing newline though, which will break things.

## Test program

```
def f(G,T,L):
 def g(x,y):
  if x>-1<y:l=g(x-1,y)[1];t=g(x,y-1)[0];r=l,t,1-l,0,0,1,t,l,l&t,l|t,l^t;i="+\\!0 1U)&|^".index(G[y*-~W+x]);return((t,l,1-t)+r[3:])[i],r[i]
  return(int((y<0)*T[x]or L[y]),)*2
 H=G.count("\n")+1;W=len(G)/H;return eval('"".join(map(str,[g(%s]for _ in range(%s)])),'*2%('_,H-1)[0','W','W-1,_)[1','H'))

import itertools

G = r"""
+))
U&+
U+^
""".strip("\n")

def test(T, L):
    print f(G, T, L)

def test_all():
    W = len(G[0])
    H = len(G)

    for T in itertools.product([0, 1], repeat=len(G.split("\n")[0])):
        T = "".join(map(str, T))

        for L in itertools.product([0, 1], repeat=len(G.split("\n"))):
            L = "".join(map(str, L))

            print "[T = %s; L = %s]" % (T, L)
            test(T, L)
            print ""

test("000", "000")
test("000", "100")
test("100", "000")
test("100", "100")

```

You can also test all possible cases with `test_all()`.

## Extra test cases

### Half adder

Here's a half adder which adds the top left bits, outputting `<input bit> <carry> <sum>`:

```
+))
U&+
U+^

```

Tests:

```
000 / 000  ->  000 / 000
000 / 100  ->  001 / 101
100 / 000  ->  101 / 001
100 / 100  ->  110 / 110

```

Output should be the same even if the second/third bits of the inputs are changed.

### Right shift

Given `abc / def`, this outputs `fab / cde`:

```
\\\
\++
\++

```

Tests:

```
001 / 110 -> 000 / 111
010 / 101 -> 101 / 010
101 / 100 -> 010 / 110

```

### 3-bit sorter

Sorts the first three bits of top into the last three bits of bottom. Right output is junk.

```
UUU)))
UU)U U
U&UU U
U+|&)U
\UU++|
 \)&UU
  \+|U
   UUU

```

Tests:

```
000000 / 00000000 -> 000000 / 00000000
001000 / 00000000 -> 000001 / 11111111
010000 / 00000000 -> 000001 / 00001111
011000 / 00000000 -> 000011 / 11111111
100000 / 00000000 -> 000001 / 00001111
101000 / 00000000 -> 000011 / 11111111
110000 / 00000000 -> 000011 / 00001111
111000 / 00000000 -> 000111 / 11111111

```

### 2-bit by 2-bit multiplier

Takes the 1st/2nd bits of top as the first number, and the 3rd/4th bits of top as the second number. Outputs to the last four bits of bottom. Right output is junk.

```
UUUU))))
UU++)))&
UUU+)  U
UU++&))U
U++&+)^U
U)&\&)UU
   U+^UU
   \&UUU

```

*Edit: Golfed out a column and two rows.*

Tests:

```
00000000 / 00000000 -> 00000000 / 00000000
00010000 / 00000000 -> 00000000 / 10000000
00100000 / 00000000 -> 00000000 / 00000000
00110000 / 00000000 -> 00000000 / 10000000
01000000 / 00000000 -> 00000000 / 00000000
01010000 / 00000000 -> 00000001 / 11111111
01100000 / 00000000 -> 00000010 / 00000000
01110000 / 00000000 -> 00000011 / 11111111
10000000 / 00000000 -> 00000000 / 00000000
10010000 / 00000000 -> 00000010 / 10000000
10100000 / 00000000 -> 00000100 / 00000000
10110000 / 00000000 -> 00000110 / 10000000
11000000 / 00000000 -> 00000000 / 00000000
11010000 / 00000000 -> 00000011 / 11111111
11100000 / 00000000 -> 00000110 / 00000000
11110000 / 00000000 -> 00001001 / 11111111

```
> 7 votes

# Answer
# Python 2, 316 bytes

This function builds 10 tile lambda functions, then iterates though the grid, updating logic states. The final vertical and horizontal logic states are then printed.

```
def b(d,j,g):
 h=enumerate;e=dict((s[0],eval('lambda T,L:('+s[1:]+')'))for s in' 0,0#00,0#11,1#+L,T#\\T,L#UT,T#)L,L#!1-L,1-T#&T&L,T&L#|T|L,T|L#^T^L,T^L'.split('#'));j=list(j+'\n');g=list(g)
 for y,k in h(d.split('\n')):
  L=g[y]
  for x,c in h(k):T=j[x];L,B=e[c](int(T),int(L));j[x]=`B`
  g[y]=`L`
 print''.join(j+g)

```

The ungolfed code including tests:

```
def logic(grid, top, left):
    loop = enumerate;
    func = dict((s[0], eval('lambda T,L:('+s[1:]+')')) for s in ' 0,0#00,0#11,1#+L,T#\\T,L#UT,T#)L,L#!1-L,1-T#&T&L,T&L#|T|L,T|L#^T^L,T^L'.split('#'));
    top = list(top+'\n');
    left = list(left)
    for y,row in loop(grid.split('\n')):
        L = left[y]
        for x,cell in loop(row) :
            T = top[x];
            L, B = func[cell](int(T), int(L));
            top[x] = `B`
        left[y] = `L`
    print ''.join(top + left)

import re
testset = open('test.txt', 'rt').read().strip()
for test in testset.split('\n\n'):
    if test.endswith(':'):
        print '------------------\n'+test
    elif re.match('^[01/\n]+$', test, re.S):
        for run in test.split():
            top, left = run.split('/')
            print 'test', top, left
            logic(grid, top, left)
    else:
        grid = test

```

The `test.txt` file (including 2 other tests by Sp3000):

```
Nand:

&!

00/0
00/1
10/0
10/1

All ones:

1111
1\+\
1+\+
1\+\

1001/1100

Xor from Nand (note the column of trailing spaces):

\)+\
U&!&
+! !
\&!&
   !

00000/00000
00000/10000
10000/00000
10000/10000

Half adder:

+))
U&+
U+^

000/000
000/100
100/000
100/100

Right shift:

\\\
\++
\++

001/110
010/101
101/100

```

The test output:

```
------------------
Nand:
test 00 0
01
1
test 00 1
01
1
test 10 0
01
1
test 10 1
11
0
------------------
All ones:
test 1001 1100
1111
1111
------------------
Xor from Nand (note the column of trailing spaces):
test 00000 00000
00000
00000
test 00000 10000
00010
00000
test 10000 00000
00010
00000
test 10000 10000
00000
00000
------------------
Half adder:
test 000 000
000
000
test 000 100
001
101
test 100 000
101
001
test 100 100
110
110
------------------
Right shift:
test 001 110
000
111
test 010 101
101
010
test 101 100
010
110

```
> 7 votes

# Answer
# R, ~~524~~ 517

Probably lots of room to reduce this at the moment, but this has been really interesting to do. There are two functions. Function d is the worker and f is the comparer.

The function d is called with 3 strings, Gates, Top and Left. The Gates are put into a matrix determined by the width.

```
I=strtoi;S=strsplit;m=matrix;f=function(L,T,G){O=I(c(0,1,L,T,!L,!T,L&T,L|T,xor(L,T)));X=which(S(' 01+\\U)!&|^','')[[1]]==G);M=m(c(1,1,1,2,1,1,3,2,2,4,3,4,5,4,3,6,4,4,7,3,3,8,5,6,9,7,7,10,8,8,11,9,9),nrow=3);return(c(O[M[2,X]],O[M[3,X]]))};d=function(G,U,L){W=nchar(U);H=nchar(L);U=c(list(I(S(U,'')[[1]])),rep(NA,H));L=c(list(I(S(L,'')[[1]])),rep(NA,W));G=m((S(G,'')[[1]]),nrow=W);for(i in 1:H)for(n in 1:W){X=f(L[[n]][i],U[[i]][n],G[n,i]);L[[n+1]][i]=X[1];U[[i+1]][n]=X[2]};cat(U[[H+1]],' / ',L[[W+1]],sep='',fill=T)}

```

Formatted a bit

```
I=strtoi;S=strsplit;m=matrix;
f=function(L,T,G){
    O=I(c(0,1,L,T,!L,!T,L&T,L|T,xor(L,T)));
    X=which(S(' 01+\\U)!&|^','')[[1]]==G);
    M=m(c(1,1,1,2,1,1,3,2,2,4,3,4,5,4,3,6,4,4,7,3,3,8,5,6,9,7,7,10,8,8,11,9,9),nrow=3);
    return(c(O[M[2,X]],O[M[3,X]]))
};
d=function(G,U,L){
    W=nchar(U);H=nchar(L);
    U=c(list(I(S(U,'')[[1]])),rep(NA,H));
    L=c(list(I(S(L,'')[[1]])),rep(NA,W));
    G=m((S(G,'')[[1]]),nrow=W);
    for(i in 1:H)
        for(n in 1:W){
            X=f(L[[n]][i],U[[i]][n],G[n,i]);
            L[[n+1]][i]=X[1];
            U[[i+1]][n]=X[2]
        };
    cat(U[[H+1]],' / ',L[[W+1]],sep='',fill=T)
}

```

Some tests

```
> d('&!','00','0')
01 / 1
> d('&!','00','1')
01 / 1
> d('&!','10','0')
01 / 1
> d('&!','10','1')
11 / 0
> d('\\)+\\ U&!& +! ! \\&!&    ! ','00000','00000')
00000 / 00000
> d('\\)+\\ U&!& +! ! \\&!&    ! ','00000','10000')
00010 / 00000
> d('\\)+\\ U&!& +! ! \\&!&    ! ','10000','00000')
00010 / 00000
> d('\\)+\\ U&!& +! ! \\&!&    ! ','10000','10000')
00000 / 00000
> d('+++\\00000000000\\!!!!\\00000000000\\+++','000000000000','100')
000000000000 / 001
> d('+++\\00000000000\\!!!!\\00000000000\\+++','000000000000','000')
000000000000 / 000
> d('+))U&+U+^','000','000')
000 / 000
> d('+))U&+U+^','000','100')
001 / 101
> d('+))U&+U+^','100','000')
101 / 001
> d('+))U&+U+^','100','100')
110 / 110

```
> 1 votes

---
Tags: code-golf, grid, logic-gates
---