# Question
Title: Count the lucky tickets within the given range
In Russia we have something like a tradition: we like to look for lucky tickets.

Here's what a regular ticket looks like:

As you can see, the ticket has a six-digit number.

A six-digit number is considered **lucky** if the sum of the first three digits is equal to the sum of the last three.

The number on the photo is not lucky:

```
038937
038 937
0 + 3 + 8 = 11
9 + 3 + 7 = 19
11 != 19

```

## Challenge

Given the limits of a range (inclusive), return the number of lucky ticket numbers contained within it.

## Parameters

* Input: 2 integers: the first and last integers in the range
* The inputs will be between 0 and 999999 inclusive
* Output: 1 integer: how many lucky numbers are in the range
* You may take the inputs and return the output in any acceptable format
* Assume leading zeros for numbers less than 100000.

## Examples

```
0, 1 => 1
100000, 200000 => 5280
123456, 654321 => 31607
0, 999999 => 55252

```

This is so the shortest answer in bytes in every language wins.

Update: here's the lucky one

# Answer
# 05AB1E, ~~8 (or 10?)~~ 11 (or 13?) bytes

```
Ÿʒ₄n+¦S3ôOË

```

Try it online or verify some more test cases.

NOTE: In 05AB1E strings and integers are interchangeable, so the output numbers doesn't contain leading zeroes. This could however be fixed with 1 additional byte (**12 bytes**):

```
Ÿ₄n+€¦ʒS3ôOË

```

Try it online or verify some more test cases.

+3 bytes to bug-fix numbers with a length of 3 or less (range `[000000, 000999]`).

**Explanation:**

```
Ÿ          # Create an inclusive (on both sides) range from the two inputs
           #  i.e. 038920 and 038910 →
           #   [38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920]
 ʒ         # Filter this list by:
  ₄n+      #  Add 1,000,000 to the number
     |     #  And remove the leading 1
           #   i.e. 38910 → 1038910 → '038910'
  S        #  Transform it to a list of digits
           #   i.e. '038910' → ['0','3','8','9','1','0']
   3ô      #  Split it into chunks of length 3
           #   i.e. ['0','3','8','9','1','0'] → [['0','3','8'],['9','1','0']]
     O     #  Sum the digits in both parts
           #   i.e. [['0','3','8'],['9','1','0']] → [11,10]
      Ë    #  Check if they are equal (if they are, they remain in the filtered list)
           #   i.e. [11,10] → 0

```

---

EDIT: Seems I (and most other answers) slightly misread the challenge and the amount of numbers is being asked instead of the numbers themselves within the range. In that case a trailing `}g` can be added (close the filter; and get the amount of numbers left in the filtered list), so it's **~~10~~ 13 bytes** instead:

```
Ÿʒ₄n+¦S3ôOË}g

```

Try it online or verify some more test cases.
> 10 votes

# Answer
# C# (.NET Core), 93 + 18 = 111 bytes

```
a=>b=>Enumerable.Range(a,b-a+1).Select(e=>$"{e:D6}").Count(e=>e[0]+e[1]+e[2]==e[3]+e[4]+e[5])

```

Try it online!

18 bytes for `using System.Linq;`. I supposed that the input and output formats could be flexible. So I take two integers as input (the range, inclusive).

Some test results:

```
a=1000
b=1100

Lucky numbers = 3 [001001, 001010, 001100]

a=2000
b=2100

Lucky numbers = 3 [002002, 002011, 002020]

a=222000
b=222100

Lucky numbers = 7 [222006, 222015, 222024, 222033, 222042, 222051, 222060]

a=0
b=999999

Lucky numbers = 55252 (that's 5.5% of the total numbers)

```
> 9 votes

# Answer
# JavaScript (ES6), 66 bytes

Takes input in currying syntax `(m)(n)`, where **m** is the ~~exclusive~~ inclusive upper bound and **n** is the inclusive lower bound.

```
m=>g=n=>n<=m&&![...n+=''].reduce((t,d,i)=>t-=n[i+3]?d:-d,0)+g(-~n)

```

Try it online!

### How?

We test each number \\$n\\$ by walking through its digits \\$d\_i\\$ and updating a total \\$t\\$:

* \\$t \gets t - d\_i\\$ if there are at least 3 remaining digits after this one
* \\$t \gets t + d\_i\\$ otherwise

If we have \\$t=0\\$ at the end of the process, then \\$n\\$ is a lucky number.

---

# JavaScript (ES6), 67 bytes

Same input format.

```
m=>g=n=>n<=m&&!eval([...n/1e3+''].join`+`.split`+.`.join`^`)+g(n+1)

```

Try it online!

### How?

For each number \\$n\\$:

* divide it by \\$1000\\$: e.g. `38937 --> 38.937`
* coerce to a string and split: `['3','8','.','9','3','7']`
* join with `+`: `"3+8+.+9+3+7"`
* replace `+.` with `^`: `"3+8^+9+3+7"`
* evaluate as JS code and test whether the result is \\$0\\$: `24` (\\$11\\$ XOR \\$19\\$)

If \\$n \equiv 0 \pmod{1000}\\$, no decimal point is generated and the evaluated expression is just a positive sum (falsy), unless \\$n=0\\$ (truthy). This is the expected result in both cases.
> 8 votes

# Answer
# Ruby, ~~56~~ 54 bytes

```
->a,b{(a..b).count{|i|j=i.digits;j[0,3].sum*2==j.sum}}

```

Try it online!

### Method:

1. For every number, creates an array of digits (which comes out reversed)
2. Compares the sum of the first 3 digits in the array (last 3 in the number) multiplied by 2 to the sum of the entire array
3. Counts the numbers for which the two sums are equal
> 7 votes

# Answer
# Japt, ~~38~~ 15 bytes

```
õV Ëì ò3n)mx r¥

```

*-23 thanks to Shaggy!*

My first Japt submission; thanks to Shaggy for all the help!

Try it online!
> 6 votes

# Answer
# , ~~93~~ 86 bytes

Shorter logic at the end compliments of @Giuseppe/

```
function(a,b){for(i in sprintf("%06d",a:b)){x=utf8ToInt(i);F=F+!sum(x[1:3]-x[4:6])}
F}

```

Try it online!

Integer inputs. Pad them with `0`. Convert to the six ASCII code points. Abuse the `F` builtin.
> 6 votes

# Answer
# Python 3, 117 113 106 135 bytes

This is my first answer ever so I'm sure there's room for improvement.

```
def x(a,b):
    n=0
    for i in range(a,b+1):
        if sum(map(int,str(i//1000)))==sum(map(int,str(i%1000))):n+=1
    print(n)

```
* *-4 bytes thanks to W W*
* *-7 bytes thanks to Asone Tuhid*
* *+29 bytes to create a function*

Gets the first three digits through integer division, and the last three through modulo. The first and last integers in the range are inputted as arguments of the `x` function, as `a` and `b`, respectively. Output is `n`, printed.

Ungolfed:

```
def x(a, b):
    n = 0
    for i in range(a, b + 1):
        if sum(map(int, str(i // 1000))) == sum(map(int, str(i % 1000))):
            n += 1
    print(n)

```
> 6 votes

# Answer
# Husk, 12 bytes

```
#ȯ§¤=Σ↓↑3↔d…

```

Try it online!

## Explanation

```
#(§¤=Σ↓↑3↔d)…  -- example input: 100000 101000
            …  -- inclusive range: [100000,100001..100999,101000]
#(         )   -- count elements where (example with 100010)
          d    -- | digits: [1,0,0,0,1,0]
         ↔     -- | reversed: [0,1,0,0,0,1]
  §     3      -- | fork elements (3 and [0,1,0,0,0,1])
       ↑       -- | | take: [0,1,0]
      ↓        -- | | drop: [0,0,1]
   ¤=          -- | > compare the results by equality of their
     Σ         -- | | sums 1 == 1
               -- | : 1
               -- : 3

```
> 6 votes

# Answer
# Charcoal, 15 bytes

```
ＩＬΦ…·ＮＮ⁼Σι⊗Σ÷ιφ

```

Try it online! Link is to verbose version of code. Edit: I originally thought that it was the list of lucky numbers that was required. This can be done in 14 bytes (by removing the , which takes the length of the list), or in 20 bytes if you want some nice formatting:

```
ＥΦ…·ＮＮ⁼Σι⊗Σ÷ιφ﹪%06dι

```

Try it online! Link is to verbose version of code. Explanation:

```
    ＮＮ                  Input the range endpoints
  …·                    Inclusive range
 Φ                      Filter
        ι               Current value
       Σ                Sum of digits
            ι           Current value
             φ          Predefined variable 1000
           ÷            Integer divide
          Σ             Sum of digits
         ⊗              Doubled
      ⁼                 Equals
Ｅ                       Map over results
                   ι    Current value
               %06d     Literal string
              ﹪         Format value
                        Implicitly print each result on its own line

```
> 5 votes

# Answer
## Perl 5 \+ `-pl -MList::Util+(sum)`, 49 bytes

```
@F=/./g,$\+=sum@F[5,4,3]==sum@F[2,1,0]for$_..<>}{

```

Try it online!

---

## Perl 5 \+ `-nl -MList::Util+(sum) -M5.010`, 50 bytes

To output each ticket instead is +1 byte:

```
@F=/./g,sum@F[5,4,3]-sum(@F[2,1,0])||say for$_..<>

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~89~~ 86 bytes

-2 thanks to Mr. Xcoder.

-3 inspiring from Asone Tuhid answer's.

```
lambda a,b:sum(sum(map(int,str(i)))==2*sum(map(int,str(i)[-3:]))for i in range(a,b+1))

```

Tests results :

```
Example 1 :
a = 0
b = 1
Lucky numbers : 1

Example 2 :
a = 100000
b = 200000
Lucky numbers : 5280

Example 3 :
a = 123456
b = 654321
Lucky numbers : 31607

Example 3 :
a = 0
b = 999999
Lucky numbers : 55252

```

Try it online!
> 3 votes

# Answer
# Kotlin, 152 119 bytes

```
{a:Int,b:Int->(a..b).map{String.format("%06d",it)}.filter{it[0].toInt()+it[1].toInt()+it[2].toInt()==it[3].toInt()+it[4].toInt()+it[5].toInt()}.count()}

```

Try it online!

Taking two integers than convert it into six symbol strings and count.

Optimized it thanks to mazzy and his solution to 119 bytes.

```
{a:Int,b:Int->(a..b).count{val d="%06d".format(it);(d[0]-'0')+(d[1]-'0')+(d[2]-'0')==(d[3]-'0')+(d[4]-'0')+(d[5]-'0')}}

```

Try it online!
> 3 votes

# Answer
# Pascal (FPC), ~~163~~ 153 bytes

```
var a,b:Int32;begin read(a,b);for a:=a to b do if a div$186A0+a div$2710mod$A+a div$3E8mod$A=a div$64mod$A+a div$Amod$A+a mod$Athen b:=b+1;write(b-a)end.

```

Try it online!

## Explanation

Here is some normal-looking code first:

```
var a,b,i,s,c,d:Int32;
begin
  read(a,b);
  s:=0;
  for i:=a to b do begin
    c:=i div 1000;
    d:=i mod 1000;
    if c div 100+(c div 10) mod 10+c mod 10=d div 100+(d div 10) mod 10+d mod 10 then begin s:=s+1; {writeln(i)} end;
  end;
  write('There are ',s,' numbers');
end.

```

Try it online!

Then I abused the behaviour of the for loop:

* the loop values are set beforehand (from `a` to `b`), so `a` can be reused as the loop variable, dropping `i`;
* at the end of the for loop, loop variable is left at the final value (value of `b` before the loop). I used `b` as a container, incrementing it when a lucky number is found and at the end of the loop `b` is away from its old value by amount of lucky numbers, so `b-a` gives the correct result. This dropped `s`.

Replacing `d` with operations directly on `a` shortens the loop. Replacing `c` with operations directly on `a` dose not shorten the loop, but, after dropping `d`, loop's `begin` and `end` are unnecessary and I ended with using only 2 variables :)

`$` starts hexadecimal constants in the golfed code. While they do not save bytes, they eliminate spaces needed before decimal constants.
> 3 votes

# Answer
# Java (OpenJDK 8), 162 bytes

... borrows from the Kotlin example above.

```
import java.util.stream.IntStream;

(a,b)->IntStream.range(a,b+1).mapToObj(i->String.format("%06d",i).getBytes()).filter(c->c[0]+c[1]+c[2]==c[3]+c[4]+c[5]).count();

```

Try it online!

Comparing the sum of the String's bytes is just as good as summing up the actual digits.
> 3 votes

# Answer
# MATL, 24 bytes

```
&:1e3&\,!'%03d'&V2&sw]=s

```

Try it online!

*(-2 bytes thanks to Luis Mendo.)*

`&:` \- Make an inclusive range between the two given numbers

`1e3&\` \- 'divrem' - divide by 1000 and get the reminders and floored quotients in two arrays.

`,` \- do twice

`!'03d'&V` \- transpose and convert each value to a zero-padded three-width string

`&s` \- sum each row's values

`w` \- switch to bring the reminder array out and do this again on that

`]` \- end loop

`=` \- check for equality (returns 1s in places where the arrays are equal)

`s` \- sum those to get the count (implicit output)
> 3 votes

# Answer
# dc, 44 bytes

```
sb[d]sD[dA00~[rA~rA~++rx]dx=D1+dlb!<L]dsLxkz

```

Takes two arguments from an otherwise empty stack, outputs to top of stack.

Try it online!

The clever bit here is the use of an unnamed (i.e., unstored) macro that's duplicated before execution in order to run a copy of itself on the other three-digit part.

# Explanation

The inner macro `[rA~rA~++rx]` has the effect "calculate the digit sum of the three digit number that is second-to-top on the stack, then execute the original top of the stack as a macro".

Main program:

```
sb             Saves the upper bound as b so we'll know when to quit
[d]sD          Defines the macro D, which contextually is "increment stack depth"
[              Start the main loop - the next number to test is on top
  d              Make a copy to increment later for loop purposes
  A00            The literal "1000"
  ~              Quotient and remainder, so "123456" is now "123 456"
  [rA~rA~++rx]d  Stack is now "123 456 M M", where M is the anonymous macro
  x              Run M on the stack "123 456 M", which (see definition
                 above) ends up running M on the stack "123 15", which
                 leaves "15 6" (and executes the 6, which is a no-op)
  =D             If the two sums were equal, increment the stack depth
  1+             Increment the current test number
  dlb!<L         Loop unless the test number is now larger than b
]dsLx          Name and start the loop
kz             Current depth is 1+answer, so throw away top and return

```
> 3 votes

# Answer
# Perl 6, ~~51~~ 49 bytes

```
{+grep {[==] .flip.comb[^3,3..*]>>.sum},$^a..$^b}

```

Try it online!

Anonymous code block that takes a two numbers and returns the number of lucky ones. Times out for larger inputs
> 2 votes

# Answer
# PHP, 131 bytes

```
<?$f='array_sum(str_split(str_split(sprintf("%06d",$i),3)[';for($i=$argv[1]-1;$i++<$argv[2];)eval("\$a+=$f 0]))==$f 1]));");echo$a;

```

To run it:

```
php -n <filename> <from> <to>

```

Example:

```
php -n lucky_tickets.php 100 100000

```

Or Try it online!
> 2 votes

# Answer
# Jelly,  ~~9~~  8 bytes

-1 thanks to Dennis (`rµ...E)S` -\> `r...E€S` since everything vectorises.)

```
rdȷD§E€S

```

A dyadic Link accepting the two endpoints of the range (either way around) which yields the count of lucky tickets.

**Try it online!** Or see a test-suite

### How?

Note that for any non-negative integer less than \\$1000000\\$, \\$N\\$, we can get two numbers with digits that sum to the required values to check using integer division by \\$1000\\$
(yielding, say, \\$X=\lfloor\frac{N}{1000}\rfloor\\$)
and its remainder
(say \\$Y=N\mod{1000}\\$)
...that is, \\$N=1000\times X+Y\\$

Now we want to compare the sums of the digits of \\$X\\$ and \\$Y\\$ for each \\$N\\$ in a range and count those that are equal.

```
rdȷD§E€S - Link: integer a; integer b
r        - inclusive range [a,b] (either [a,a+1,a+2,...,b] or [a,a-1,a-2,...,b])
         -                              e.g.: 0       or 78        or 7241
  ȷ      - literal 1000
 d       - divmod (vectorises)                [0,0]      [0,78]       [7,241]
   D     - to decimal lists (vectorises)      [[0],[0]]  [[0],[7,8]]  [[7],[2,4,1]]
    §    - sum each (vectorises)              [0,0]      [0,15]       [7,7]
     E€  - for €ach: all equal?               1          0            1
       S - sum (counts the 1s in the resulting list)

```
> 2 votes

# Answer
# Powershell, 85 bytes

```
($args[0]..$args[1]|%{'{0:D6}'-f$_}|?{+$_[0]+$_[1]+$_[2]-eq+$_[3]+$_[4]+$_[5]}).count

```

Test script:

```
$f = {

($args[0]..$args[1]|%{'{0:D6}'-f$_}|?{+$_[0]+$_[1]+$_[2]-eq+$_[3]+$_[4]+$_[5]}).count

}

@(
    ,((0,1), 1)
    ,((1000,2000), 3)
    ,((2000,3000), 6)
    ,((10000, 20000), 282)
    ,((101000, 102000), 6)
    ,((201000, 202000), 10)
    ,((901000, 902000), 63)
    ,((100000, 200000), 5280)
    ,((123456, 654321), 31607)
    #,((0, 999999), 55252)
) | % {
    $c, $e = $_
    "      $c"
    $r = &$f $c[0] $c[1]
    "$($e-eq$r): actual=$r expected=$e"
}

```

Output:

```
      0 1
True: actual=1 expected=1
      1000 2000
True: actual=3 expected=3
      2000 3000
True: actual=6 expected=6
      10000 20000
True: actual=282 expected=282
      101000 102000
True: actual=6 expected=6
      201000 202000
True: actual=10 expected=10
      901000 902000
True: actual=63 expected=63
      100000 200000
True: actual=5280 expected=5280
      123456 654321
True: actual=31607 expected=31607

```
> 2 votes

# Answer
# Kotlin, 95 bytes

```
{a:Int,b:Int->(a..b).count{val d="%06d".format(it);d.chars().sum()==2*d.take(3).chars().sum()}}

```

`.kt` for test:

```
var  f = {a:Int,b:Int->(a..b).count{val d="%06d".format(it);d.chars().sum()==2*d.take(3).chars().sum()}}

fun main(args: Array<String>) {
    println(f(0,1))             // 1
    println(f(1000,2000))       // 3
    println(f(2000,3000))       // 6
    println(f(101000, 102000))  // 6
    println(f(201000, 202000))  // 10
    println(f(901000, 902000))  // 63
    println(f(10000, 20000))    // 282
    println(f(100000, 200000))  // 5280
    println(f(123456, 654321))  // 31607
    println(f(0, 999999))       // 55252
}

```

# Explanation

Count numbers from range where sum of all number digits is equal to double sum of first 3 digits.
> 2 votes

# Answer
# Stax, 14 bytes

```
ît║l`Yµß╖vYü╢^

```

Run and debug it, but be patient!
> 1 votes

# Answer
# Python 2,  ~~83~~  80 bytes

-3 by using Asone Tuhid's observation - go give credit!

```
lambda a,b:sum(sum(map(int,`v/1000`))*2==sum(map(int,`v`))for v in range(a,b+1))

```

**Try it online!**

Much like my Jelly answer (but the inputs must be sorted here i.e. `a<=b`)

---

**75 bytes** for input `a, b+1` (i.e. range excludes the right bound):

```
lambda*r:sum(sum(map(int,`v/1000`))*2==sum(map(int,`v`))for v in range(*r))

```

Try this one
> 1 votes

# Answer
## Clojure, 102 bytes

```
#(count(for[i(range %(inc %2)):when(=(let[d(map int(format"%06d"i))](apply +(map -(drop 3 d)d)))0)]i))

```

Mixing strings and math isn't too fun.
> 1 votes

# Answer
# Java 8, ~~101~~ 99 bytes

```
u->l->{int n=0,d=10;for(;l<=u;)if(l++%d+l/d%d+l/100%d==l/1000%d+l/10000%d+l/100000%d)++n;return n;}

```

A different approach than the other Java answer. Instead of using streams and Strings, this uses a loop and evaluates the numbers directly. Try it online here.

Thanks to ceilingcat for golfing two bytes.

Ungolfed:

```
u -> l -> { // lambda taking two integer arguments in currying syntax and returning an integer
    int n = 0, // the counter
        d = 10; // auxiliary constant, we will be using the number 10 rather a lot
    for(; l <=u ; ) // loop over all ticket numbers in the range
        if(l++ %d + l/d %d + l/100 %d // if the digit sum of the second half of the number ...
           == l/1000 %d + l/10000 %d + l/100000 %d) // ... is the same as the digit sum of the first half ...
            ++n; // ... it's a lucky ticket, add 1 to the counter
    return n; // return the count
}

```
> 1 votes

# Answer
# C (gcc), ~~90~~ 88 bytes

```
l=10;u(c,k,y){for(y=0;c<=k;)c++%l+c/l%l+c/100%l-c/1000%l-c/10000%l-c/100000%l?:++y;c=y;}

```

Port of my Java answer. Try it online here. Thanks to ceilingcat for golfing two bytes.

Ungolfed:

```
l=10; // constant, we will be using the number 10 rather a lot
u(c, k, // function returning an integer and taking two integer arguments: lower and upper bound
  y) { // abusing the argument list to declare a variable of type integer: the number of lucky tickets found in the range
    for(y = 0; c <= k; ) // set count to 0 and loop through the range
        c++ %l + c/l %l + c/100 %l // if the digit sum of the second half of the ticket number ...
        - c/1000 %l - c/10000 %l - c/100000 %l // ... is the same as the digit sum of the first half ...
        ?: ++y; // ... it's a lucky ticket: increment the count
    c = y; // return the count
}

```
> 1 votes

# Answer
# , 35 bytes

```
[:+/(6#10)([:=/_3+/\])@#:[+i.@>:@-~

```

Try it online!
> 1 votes

# Answer
# VBA (Excel), 159 bytes

Using Immediate Window and Cells `[A1]` `[A2]` as input.

```
c=[A1]-[A2]:d=IIf(c<0,[A1],[A2]):For x=d To d+Abs(c):e=String(6-Len(x),"0")&x:For y=1To 3:i=i+Mid(e,y,1):j=j+Mid(e,7-y,1):Next:z=IIf(i=j,z+1,z):i=0:j=0:Next:?z

```
> 1 votes

# Answer
## F#, 110 bytes

```
let t=string>>Seq.sumBy(int>>(-)48)
let r s e=Seq.where(fun n->t(n/1000)=t(n-(n/1000)*1000)){s..e}|>Seq.length

```

Try it online!

`t` converts the string into numbers and sums them up. `r` takes the range of numbers from `s` to `e`, and filters out the numbers that are unlucky. The first three digits are collected by `n/1000`. The second three digits are computed by `n-(n/1000)*1000`.
> 1 votes

---
Tags: code-golf, math, number
---


title: Print a string with vertical words

text:
# Question
Title: Print a string with vertical words
Your task is to take an input string of ascii characters and output the string as a series of vertical words separated by spaces. An example is shown below:

Given the string:

```
Hello, World! My name is Foo.

```

the output should be:

```
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !

```

10 bonus points will be awarded if your program correctly handles strings which need to wrap-around the terminal, which we'll set at 80 characters.

50 points if your program can also do the reverse!

# Answer
## J, 15

```
|:>'\S+| 'rxall

```

Usage:

```
   |:>'\S+| 'rxall 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !

```
> 10 votes

# Answer
# Javascript - ~~228~~ ~~172~~ ~~145~~ 126

```
A=prompt().split(" "),B="",N=A;for(y=0;y<N.length;y++){for(i=0;i<N.length;i++){if(A[i][y]){B+=A[i][y];}else{B+=" ";}}B+="\n";}

```

My first code golf :)
> 5 votes

# Answer
# APL, 22

```
{⍉⊃⍵⊂⍨1+0,+\2≠/⍵=' '}

```

**Explanation**

```
{              ⍵=' '}   A. check which chars are spaces
            2≠/         B. of that vector, which consecutive pairs are different
          +\            C. compute the partial sums
      1+0,              D. insert 0 at the front and add 1 to every item
   ⍵⊂⍨                     use this vector to split the original string
 ⍉⊃                        disclose into a matrix and transpose

    'W o w   S u c h   D o g e'
A.   0 0 0 1 0 0 0 0 1 0 0 0 0
B.    0 0 1 1 0 0 0 1 1 0 0 0
C.    0 0 1 2 2 2 2 3 4 4 4 4
D.  1 1 1 2 3 3 3 3 4 5 5 5 5

```

**Example**

```
      {⍉⊃⍵⊂⍨1+0,+\2≠/⍵=' '} 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !

```
> 5 votes

# Answer
## Javascript ~~184~~ ~~149~~ 123

```
var a=s.split(" "),b="",c;for(c in a)b+="<div style='float:left'>"+a[c].split("").join("<br>")+"</div>";document.write(b);

```

With the example string defined:

```
var s = "Hello, World! My name is Foo.";
var a=s.split(" "),b="",c;for(c in a)b+="<div style='float:left'>"+a[c].split("").join("<br>")+"</div>";document.write(b);

```

You can copy the second statement to you browsers console.

Unminified:

```
var res = "Hello, World! My name is Foo.";
var t=res.split(" ");
var s ="";
for (var word in t){
    s+="<div style='float:left'>" + t[word].split("").join("<br />") + "</div>";
}
document.write(s);

```

JsFiddle Link: http://jsfiddle.net/FzMvK/

My first code golf post :P
> 3 votes

# Answer
# Ruby, ~~91~~ 87

```
s=gets.split
puts s.map{|x|x.ljust(s.map(&:size).max,' ').split''}.transpose.map &:join

```

Hooray, I beat Perl! :D

# Ruby, 150 - 50 bonus = 100

```
s=$<.read
n=s.index"
"
s=s.split n ?'
':' '
o=s.map{|x|x.ljust(s.map(&:size).max,' ').split''}.transpose.map &:join
puts n ?o.map(&:strip).join(' '):o

```

It just detects for newlines, and applies special handling if they are detected.

Run it like

```
ruby transposegolf.rb < transposegolfinput.txt

```
> 3 votes

# Answer
# Perl - 92 ~~97~~

```
$_=<>;chop;@x=split$";do{print((substr$_,$q,1or$").$")for@x;$q++,print$/}while/@{['\S'x$q]}/

```

Does the job in a pretty straightforward way.
> 2 votes

# Answer
# K, 33

```
{" "/:',:''x@'/:!max@#:'x:" "\:x}

```

Example input and output:

```
k){" "/:',:''x@'/:!max@#:'x:" "\:x}"Hello, World! My name is Foo."
"H W M n i F"
"e o y a s o"
"l r   m   o"
"l l   e   ."
"o d        "
", !        "

```
> 2 votes

# Answer
# Python 2.7 - 137 112 bytes

```
s=raw_input().split()
for c in range(max(map(len,s))):
 for w in s:
    try:print w[c],
    except:print' ',
 print''

```

Someone else has already done it better, but I might as well throw this up. Adds spaces to each word in the input until it's the same length as the longest one (to avoid index errors for the next part), then prints the `c`th letter of every word while `c` goes from 0 to the length of each string.

I came up with a much better way of doing this and cut out 25 bytes. Rather than padding strings with spaces to avoid the index error, I handle the error directly! Whenever there's nothing to print, I print a single space in its place with `try:print w[c],`, `except:print' ',`. I also remembered that I don't need a space between a print statement and a string literal, which saved one byte.

Note that Python 2 allows you to mix tabs and spaces and considers them separate levels of indentation. SE's Markdown interpreter replaces a tab character with four spaces, but every line of this program except the first has exactly one byte of indentation.

Formatting was pretty easy, since `print 'something',` prints `'something '` rather than `'something\n'`. I did that for each character, and used an empty `print` statement to get the newline where I needed it.
> 2 votes

# Answer
## Python:

One line of code to process the sting:

```
import sys
m = "Hello, World! My name is Foo."

map(lambda y: sys.stdout.write(' '.join(y)+'\n'), zip(*map(lambda x: x.ljust(max(map(len,m.split()))), m.split())))

```
> 2 votes

# Answer
# Python 2.7, ~~108~~ 103

I'm sure this can be golfed more, but here's an initial solution in python.

```
w=raw_input().split();m=max(map(len,w));i=0
while i<m:print" ".join(map(lambda x:x.ljust(m)[i],w));i+=1

```

Improvements:

* split(" ") =\> split()
* removed some extra spaces
> 2 votes

# Answer
# F#, 187

```
let o=Console.ReadLine()
let s=o.Split(' ')
let m=s|>Seq.map String.length|>Seq.max
for l=0 to m-1 do
 for w in s|>Seq.map(fun x->x.PadRight(m,' ').[l])do printf"%c "w
 printfn"%s"""

```
> 2 votes

# Answer
# Ruby, 63

```
$F.map(&:size).max.times{|i|puts$F.map{|s|s[i]||' '}.join' '}

```

The algorithm is very straightforward; only golfed. Code is 61 bytes long, plus 2 bytes for the `-na` options that it needs to work. From `ruby -h`:

```
-n   assume 'while gets(); ... end' loop around your script
-a   autosplit mode with -n or -p (splits $_ into $F)

```

Sample run:

```
$ echo 'This sentence is false' | ruby -na cols.rb
T s i f
h e s a
i n   l
s t   s
  e   e
  n
  c
  e

```
> 2 votes

# Answer
## C, 111 110 95 90 bytes

This solution uses VT-100 control codes to move the cursor on the terminal

```
main(int _,char**v){char*s=*++v;printf("^[7");while(*s)' '==*s?(s++,printf("^[8^[[2C^[7")):printf("%c^[[B^H",*s++);}

```

the `^[` sequence is a placeholder for the single ASCII ESC character, that can't be displayed here.

* `^[7` saves the current pointer position
* `^[8` restores the cursor position to the saved position
* `^[[2C` moves 2 steps right
* `^[[B` moves 1 step down

**edit 1:** the `^[[D` (1 step left) VT-100 code has been replaced by a backspace (shown as `^H` here, but is only one ASCII char) ; also forgot the "separated by spaces" instruction, now fixed

**edit 2:**

7 chars saved by using a `for` loop instead of `while`, and `32` instead of `' '`:

```
main(int _,char**v){printf("^[7");for(char*s=*++v;*s;s++)32==*s?printf("^[8^[[2C^[7"):printf("%c^[[B^H",*s);}

```

8 more chars saved by calling one less `printf`: the ternary `?:` operator is now used in the `printf` parameters

```
main(int _,char**v){printf("^[7");for(char*s=*++v;*s;s++)printf(32==*s?"^[8^[[2C^[7":"%c^[[B^H",*s);}

```

**edit 3:**

Got rid of the local variable `s`, working directly with `argv` aka `v`. This is totally hideous. But saved 4 chars. Also replaced `==` with `^` and therefore switched the `?:` operands, to save 1 more char.

```
main(int c,char**v){printf("^[7");for(v++;**v;)printf(32^*(*v)++?"%c^[[B^H":"^[8^[[2C^[7",**v);}

```

## Usage

```
$ gcc transpose.c -o transpose --std=c99
$ ./transpose 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !

```

## Un-golfed version (first version)

```
main (int _,char**v) {
    char*s=*++v; // init s with the address of the first letter
    printf("^[7"); // save the current cursor position
    while(*s)
        ' '==*s ? ( /* if current char is a space */
            s++,printf("^[8^[[2C^[7") /* return to the saved location, move right, save position */
        ) : /* kind of else */
            printf("%c^[[B^H",*s++); /* print the current char, move down, move left */
}

```

## Un-golfed version (last version)

```
main(int c,char**v) {
    printf("^[7");
    for(v++;**v;) /* v++: make v point to argv[1] */
        printf(
            32^*(*v)++? /* test if **v is different from ' ', and make *v point to
                           the next char */
                "%c^[[B^H":
                "^[8^[[2C^[7",
            **v); /* this undefined behaviour (using *v and (*v)++ in the same expression)
                     works as "expected" with gcc 4.7.2 */
}

```
> 2 votes

# Answer
I answered this question a long time ago. It was one of my first contributions to the site, actually. I recently came across it again and was kind of embarrassed. 112 bytes?! Unacceptable. So I gave it another shot:

# Python 3 - 92 bytes

```
s=input().split()
print('\n'.join(map(' '.join,zip(*[a.ljust(max(map(len,s)))for a in s]))))

```

In the 109 days since I posted that first answer, I like to think I've come a long way. Even something like using Python 3 over 2.71 wouldn't have occurred to me. With this code golfed down to under 100 bytes, my soul can finally rest and I can proceed to the afterlife.

**Explanation**

```
s=input().split()

```

This gets a line from `stdin` and creates a list by splitting it at whitespace characters. The only whitespace likely to be in the input is spaces, so this line gets a list of words.

Let's take the second line from the inside out:

```
                                           max(map(len,s))

```

`map` takes a function and an iterable as arguments. It applies the function to each element of the iterable, and returns a new iterable of the results. Here, I create an iterable with the lengths of each input word. `max` gets the maximum value from an iterable. This gets us the longest word in the input.

```
                                  [a.ljust(              )for a in s]

```

A list comprehension is similar to `map`. It does something to every element of an iterable, and returns a list the results. For every word in the input, I do `that_word.ljust(`some code`)`. `ljust` is short for "left justify". It takes an integer as an argument and adds spaces to the string until it's that long.

```
                             zip(*                                    )

```

This is a neat trick. In this context, `*` means "unzip this iterable as multiple arguments". This way, `zip` can be used to transpose a matrix (e.g. `zip(*[(1,2),(3,4)])` -\> `[(1,3),(2,4)]`). The only restriction is that all the rows in the matrix have to be the same length, or elements from all rows but the shortest are cut off to match.

```
                map(' '.join,                                          )

```

We already know what `map` does. The only new thing here is `join`, which takes an iterable of strings and makes it a single string using the delimiter it's attached to. For example, `'a'.join(['I', 'can', 'play', 'the', 'saxophone'])`2 becomes `Iacanaplayatheasaxophone`.

```
print('\n'.join(                                                        ))

```

This `join` takes a bunch of strings and seperates them by newlines. All that's left is to `print` to `stdout` and we're done!

All together now:

```
print('\n'.join(map(' '.join,zip(*[a.ljust(max(map(len,s)))for a in s]))))

```

Find the length of the longest word from the input, append spaces to every word until they're the same length, transpose with the `zip(*`3 trick, use `join` to seperate each character in a row with spaces, `join` again to seperate each row with a newline, and print! Not bad for the only non-input-handling line in a 92 byte program.

---

1. The extra characters spent on `print()`'s parentheses are outweighed by the 4 characters I drop from `raw_input()`-\>`input()`.
2. I can't actually play the saxophone.
3. `)`. You're welcome.
> 2 votes

# Answer
# 05AB1E, score ~~8~~ ~~-20~~ -21 (~~30~~ 29 bytes \- 50 bonus):

```
|Dgi#ζεSðý}»}ë¹ε2ô€¬}ζJεðÜ}ðý

```

Try it online (regular single-line input).
Try it online (multi-line reversed input).

**Explanation:**

```
|                     # Take the input split on newlines:
                      #  i.e. 'This is a test' → ['This is a test']
                      #  i.e. 'T i a t\nh s   e\ni     s\ns     t'
                      #    → ['T i a t','h s   e','i     s','s     t']
 Dg                   #  Duplicate this list, and take the length
                      #   i.e. ['This is a test'] → 1
                      #   i.e. ['T i a t','h s   e','i     s','s     t'] → 4
   i         }        # If the length is exactly 1:
    ¹                 #  Take the input again
     #                #  Split the input-string by spaces
                      #   i.e. 'This is a test' → ['This','is','a','test']
      ζ               #  Zip with space-filler: Swap all rows and columns
                      #   i.e. ['This','is','a','test'] → ['Tiat','hs e','i  s','s  t']
       ε   }          #  For each item:
        S             #   Convert the item to a list of characters
                      #    i.e. 'Tiat' → ['T','i','a','t']
         ðý           #   Join them by a single space
                      #    i.e. ['T','i','a','t'] → 'T i a t'
            »         #  Join the result by newlines (and output implicitly)
    ë                 # Else:
     ε    }           #  For each item:
      2ô              #   Split it into chunks of two characters
                      #    i.e. 'h s   e' → ['h ','s ','  ','e']
        €¬            #   Take the head (first character) of each:
                      #    i.e. ['h ','s ','  ','e'] → ['h','s',' ','e']
           ζ          #  Zip with space-filler: Swap all rows and columns
                      #   i.e. [['T','i','a','t'],['h','s',' ','e'],['i',' ',' ','s'],['s',' ',' ','t']]
                      #     → [['T','h','i','s'],['i','s',' ',' '],['a',' ',' ',' '],['t','e','s','t']]
            J         #  Join each inner list to a single string
                      #   i.e. [['T','h','i','s'],['i','s',' ',' '],['a',' ',' ',' '],['t','e','s','t']]
                      #     → ['This','is  ','a   ','test']
             ε  }     #  For each item:
              ðÜ      #   Remove any trailing spaces
                      #    i.e. 'is  ' → 'is'
                 ðý   #  Join the items by a single space (and output implicitly)

```

---

**Original 8-byte answer:**

```
#ζεSðý}»

```

Try it online.

**Explanation:**

```
#           # Split the input-string by spaces
            #  i.e. 'This is a test' → ['This','is','a','test']
 ζ          # Zip with space-filler: Swap all rows and columns
            #  i.e. ['This','is','a','test'] → ['Tiat','hs e','i  s','s  t']
  ε   }     # For each item:
   S        #  Convert the item to a list of characters
            #   i.e. 'Tiat' → ['T','i','a','t']
    ðý      #  Join them by a single space
            #   i.e. ['T','i','a','t'] → 'T i a t'
       »    # Join the result by newlines (and output implicitly)

```
> 2 votes

# Answer
## Mathematica 49

Clearly Mathematica isn't the best for this one:

```
Grid[PadRight@Characters@StringSplit@s^T]/. 0->" "

```

> Note `^T` (transpose) is only one char (I can't find the right char code now)
> 1 votes

# Answer
# Javascript, 141

```
a=prompt().split(' '),c=0,d=a.map(function(a){b=a.length;c=c<b?b:c});for(j=0;j<c;j++){b='';for(i in a)b+=a[i][j]?a[i][j]:' ';console.log(b);}

```

Sample

```
hello, world! this is code golf

hwticg
eohsoo
lri dl
lls ef
od
,!

```
> 1 votes

# Answer
## GolfScript \[41 bytes\]

```
' '%:x{.,x{,}%$-1=-abs' '*+}%zip{' '*}%n*

```

How it works:

```
' '%:x          split text into words and store array in 'x'
{               for each word in the array:
    .,              from word's length
    x{,}%$-1=-      substract the length of the longest word in 'x'
    abs             get absolute value (maybe there is a shorter way?)
    ' '*+           add corresponding number of spaces
}%
zip{' '*}%      transpose array of words and add spaces between letters
n*              join words with a new line character

```

You may see the online demo here.

**P.S.:** This is my first GolfScript code ever, so don't judge me strictly ;)
> 1 votes

# Answer
## R, 116

```
z=t(plyr::rbind.fill.matrix(lapply(strsplit(scan(,""),""),t)));z[is.na(z)]=" ";invisible(apply(cbind(z,"\n"),1,cat))

```
> 1 votes

# Answer
# Bash + coreutils, 54

```
eval paste `printf " <(fold -w1<<<%s)" $@`|expand -t2

```

Output:

```
$ ./transpose.sh Hello, World! My name is Foo.
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !
$

```
> 1 votes

# Answer
## APL: 18

```
⍉↑1↓¨a⊂⍨' '=a←' ',

```

**Explanation:**

a←' ', put a space in front of the string and assign to a

' '= find spaces, produces a boolean

1↓¨a⊂⍨ make substrings starting where the boolean has 1's and drop first element of each (so the space)

⍉↑ Make matrix out of the resulting substrings, and reverse it along the diagonal
> 1 votes

# Answer
# , 81 bytes

Save a byte by storing a newline as `e`, which can be used in both `scan` calls, the compare call and `cat`.

```
w=scan(,e,t=scan(,e<-"
"));while(any((s=substr(w,F<-F+1,F))>e))cat(pmax(" ",s),e)

```

Try it online!
> 1 votes

# Answer
# K (oK), 26 bytes

**Solution:**

```
`0:{" "/'+(|/#:'x)$x}@" "\

```

Try it online!

**Explanation:**

```
`0:{" "/'+(|/#:'x)$x}@" "\ / the solution
                      " "\ / split input on whitespace
   {                }@     / apply (@) lambda
                  $x       / pad ($) input (x)
          (      )         / do this together
             #:'x          / count (#:) each (')
           |/              / max
         +                 / transpose / flip
    " "/'                  / join each with whitespace
`0:                        / print to stdout

```
> 1 votes

# Answer
## Python 2.7 - ~~119~~ 106

Take 1 - 166. The reversing of lists was needed to make pop work in the order I wanted, but this seemed wasteful. And when I tried to combine into a single comprehension for fun, the pop screwed things up.

```
w=raw_input().split(' ');l=max([len(l) for l in w]);
q=[list(p)[::-1]for p in w]+[['\n']*l]
t=[' '+(v.pop() if v else' ')for i in range(l)for v in q]
print ''.join(t)

```

Take 2 - 119. So I changed to simple list indexing. Still seems clunky though, especially the padding of spaces and new lines.

```
w=raw_input().split(' ');l=max([len(l)for l in w]);print''.join([' '+(v+' '*l)[i]for i in range(l)for v in w+['\n'*l]])

```

Take 3 - thanks to @grc

```
w=raw_input().split();l=max(map(len,w));print''.join(' '+(v+' '*l)[i]for i in range(l)for v in w+['\n'*l])

```
> 0 votes

# Answer
## Python 3, 124

```
a=input().split()
l=max(map(len,a))
print("\n".join(" ".join(c[i] for c in [i+" "*(l-len(i)) for i in a]) for i in range(l)))

```
> 0 votes

# Answer
# Haskell, 112

Golfed:

```
import Data.List
r s=unlines$transpose$p$words s
p w=m(\s->s++replicate(maximum(m l w)-l s)' ')w
m=map
l=length

```

Explained:

```
import Data.List

-- Break on spaces, then pad, then transpose, then join with newlines
r s=unlines$transpose$p$words s

-- Pads each String in a list of String to have the same length as the longest String
p w=m(\s->s++replicate(maximum(m l w)-l s)' ')w

-- Aliases to save space
m=map
l=length

```

Example:

```
*Main Data.List> putStrLn $ r "Hello Doge"
HD
eo
lg
le
o

```
> 0 votes

# Answer
# JavaScript, 139 (156 with console.log output)

```
s=" ",b="",a=prompt().split(s),l=0;for(var i in a){m=a[i].length;l=(l<m)?m:l;}for(i=0;i<l;i++){for(var j in a)b+=((x=a[j][i])?x:s)+s;b+="\n"}console.log(b);

```

I think this is as golfed as I can get it. I just split, find the largest word and transpose accordingly, adding spaces if the char doesn't exist in the shorter words. More than the previous submitted JavaScript answer, but that answer doesn't seem to work?
> 0 votes

# Answer
# Japt `-R`, 5 bytes

```
¸y¬m¸

```

Try it

---

## Explanation

```
¸         :Split on spaces
 y        :Transpose
  ¬       :Split columns
   m      :Map rows
    ¸     :  Join with spaces
          :Implicitly join with newlines and output

```
> 0 votes

# Answer
# Pyth, 8 bytes

```
jbjL\ Cc

```

Try it online!

Pretty straightforward. Takes input enclosed in quotes, i.e. `"Hello World"`

```
jbjL\ CcQ
---------
       cQ    Chop the input Q on spaces
      C      Matrix transpose
  jL\        Join each element by spaces,
             i.e. interleave spaces between the characters of each element
jb           Join by newlines

```
> 0 votes

# Answer
# APL(NARS), 79 chars, 158 bytes

```
{m←⌈/↑∘⍴¨z←(' '≠⍵)⊂,⍵⋄v←∊m{⍵\⍨∊(k⍴1)(0⍴⍨⍺-k←↑⍴⍵)}¨z⋄((2×↑⍴z)⍴1 0)\[2]⍉(↑⍴z)m⍴v}

```

test:

```
  f←{m←⌈/↑∘⍴¨z←(' '≠⍵)⊂,⍵⋄v←∊m{⍵\⍨∊(k⍴1)(0⍴⍨⍺-k←↑⍴⍵)}¨z⋄((2×↑⍴z)⍴1 0)\[2]⍉(↑⍴z)m⍴v}
  f 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !

```

The old function have output not perfect:

```
  {⍪¨(' '≠⍵)⊂,⍵}'Hello, World! My name is Foo.'
 H  W  M  n  i  F
 e  o  y  a  s  o
 l  r     m     o
 l  l     e     .
 o  d
 ,  !

```
> 0 votes

# Answer
# Julia - 109 bytes

```
i=split(readline());m=maximum(map(x->length(x),i));for c∈1:m println(join([rpad(w,m)[c] for w∈i]," "))end

```
> 0 votes

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


title: Balance the Brackets

text:
# Question
Title: Balance the Brackets
Your objective: Given a string of brackets, output the minimum Damerau-Levenshtein Distance required to turn the input string into a string where the brackets are balanced.

## Input

The input string will only contain brackets and no other characters. That is, it is a combination of any of the characters in `(){}[]<>`. You may take input as either a string or an array of characters. You may not make any other assumptions about the input string; it may be arbitrarily long (up to the maximum size supported by your language), it may be empty, the brackets may already be balanced, etc.

## Damerau-Levenshtein Distance

The Damerau-Levenshtein Distance between two strings is the minimum number of insertions, deletions, single-character substitutions, and transpositions (swapping) of two adjacent characters.

## Output

The output should be the minimum Damerau-Levenshtein Distance between the input string and a string in which the brackets are matched. Output should be a *number*, not the resulting balanced string.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as

```
()
[]{}

```

Or if every sub-element inside of it is also matched.

```
[()()()()]
{<[]>}
(()())

```

Sub-elements can also be nested several layers deep.

```
[(){<><>[()]}<>()]
<[{((()))}]>

```

(Thanks to @DJMcMayhem for the definition)

## Test Cases

```
Input                   Possible Balanced       Output

Empty                   Empty                   0
[](){}<>                [](){}<>                0
[(){}<>                 [(){}<>]                1
[(])                    []()                    1
[[[[[[[[                [][][][]                4
(](<>}[>(}>><(>(({}]    ()(<>)[(<><>){}]        7
>]{])<                  []{()}                  3
([)}}>[                 (){}<>                  4
{<((<<][{{}>[<)         <>(<<[]>{}>[])          5
{><({((})>}}}{(}}       {<><({()})>}{}{()}      4
(](<)>}[>(}>>{]<<(]]    (<()<><<>()>>[])<()>    9
}})(                    {}()                    2

```

(Thanks to @WheatWizard for solving half of the test cases)

This is , fewest bytes wins!

Your submissions should be testable, meaning it should output a result for each test case in no more than an hour.

# Answer
# Retina, ~~254~~ ~~252~~ ~~264~~ ~~248~~ ~~240~~ ~~232~~ 267 bytes

*Thank you to @AnthonyPham, @officialaimm, and @MistahFiggins for pointing out bugs*

```
T`[]()`:;'"
+`'-*"|:-*;|{-*}|<-*>
-
+`'(\W+)"|:(\W+);|{(\W+)}|<(\W+)>
A$1$2$3$+B
+`'(\D+)"|:(\D+);|{(\D+)}|<(\D+)>
6$1$2$3$+9
(.*)(}{|"'|;:|><)
1$1
-

A6B9|6A9B
1
A6+B9+|A6+.B9+.|A+6.B+9
11
T`':{";}`<<<>
(.*)(<\W|\W>)
1$1
+`<(.*A.*B.*)?\W|\W(.*A.*B.*)?>
1$1$2
\W|6B|1

```

Try it Online!

Non-brute force solution! It works for all test cases, and even found an error in one.

*-2 bytes thanks to @MartinEnder (`${4}` to `$+`)*

*+12 bytes to account for additional swapping cases*

*-16 bytes by making better use of character classes*

*-8 bytes by removing an unnecessary restriction on swapping. This also fixed a bug :)*

*-10 bytes by combining the swapping logic into a single regex*

*+2 bytes to account for consecutive swaps*

*+many for various bug fixes\***

**Explanation:**

`T`[]()`:;'"` is used to replace special bracket types for convenience. First, we recursively replace all matched brackets with `-`, `AB` or `69` depending on whether they are adjacent or not.

Then, useful "swapping " is performed by removing newly matched brackets and adding a `1` to the beginning of the string. We also replace `-` with the empty string, as it was just being used for the above swapping.

Next, we try "replacements" by removing pairs of unmatched brackets that don't overlap already-matched brackets and adding a `1` to the string.

Finally, `\W|6B|1` counts any remaining single brackets plus the number of `1`s.

*\**I'm currently working on a shorter version that uses Retina's line splitting features, though I ran into a considerable problem so it might take quite awhile.*
> 13 votes

# Answer
# Brain-Flak, 1350 bytes

```
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}<>([[]]){([[]({}()<>)]<>)<>{(({}())<<>(({})<(({}(<()>))<>({}))([(())()()]){<>({}())}{}{<>{}<>({}()){(((({}<(({}<>)<{({}()<([(){}])>)}{}>)<>(({}(<>))<{({}()<([(){}])>)}{}<>>)><>({}))(<(((({}({})[()])[()()]<>({}))<>[({})({}){}]({}<>))<>[(({}<>)<>({}<>)<>)])<>>)))[()](<()>)<<>(({})<({}{}()){({}()<({}<>)<>>)}{}<>(({})<<>(({}<>))>)<>(())>){({}[()()]<(<([({[{}]<(({})()<>[({})]<>)>{()(<{}>)}}{}<(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>{()(<{}>)}{}(){[()](<{}>)}<<>{({}<>)<>}{}>)]({}{}))>)<>{({}<>)<>}>)}{}{}<>{}{}{({}<>)<>}{}{}(<>)<>{({}<>)<>}{}{(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}((({}<({}({})({})<{{}<>{}(<>)}{}(((({}<({}<>)>)<>)))<>>)<>>)<><({}<({}<<>(()())>)>)>)<<>({}<{}{({}<>)([()()()]){((({}()()<>))[()]<(({()(<{}>)}{})<>({}<(({}<<>({}[()()](()[({})({})]({[()](<{}>)}{}<>{}<(({})<>)>)<>))>)<>)>)<>)<>({}<({}<({}<({}<>)>)>)>)>)}{}{}<>}<>{}{}{}{}{}{}{}{}>)>)>)}{}({}<({}<{({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>}<>{((({}(()()){([{}](<({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>))([{}()]{})}{})))<>(({}))<>{<>({}[()])}{}({}<<>{}{}{<>}>)<>{}}<>(({}<>){[()](<{}>)}{})(<>)>)>)<>(<({}<>)>)<>}<>{}({}<(({}){({}())}{}{}){({}<({}<>)>(())<>)}{}{}>)<>{{}({}<>)<>}{}>)<>>)}{}<>([[]{}])}{}(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)

```

Try it online!

With constant-speed comparisons and pointer dereferencing, this algorithm is O(n3). Unfortunately, Brain-Flak has neither of these, so this program runs in O(n5) time instead. The longest test case takes about 15 minutes.

## Simplifying results

To see that my algorithm works, we need to show some results that reduce the search space considerably. These results rely on the fact that the target is an entire language instead of just one specific string.

* No insertions are needed. Instead, you can just remove the bracket that the inserted character would eventually match.
* You will never need to remove a bracket, then swap its two neighbors. To see this, assume wlog that the removed bracket is `(`, so we are transforming `a(c` to `ca` in two steps. By changing `c` and inserting a copy, we can reach `ca()` in two steps without a swap. (This insertion can then be removed by the above rule.)
* The same bracket will never need to be swapped twice. This is a standard fact about the Damerau-Levenshtein distance in general.

Another simplifying result that I didn't use, because accounting for them would cost bytes:

* If two brackets are swapped, and they don't match each other, the eventual match to each of those brackets will never be changed or swapped.

## The algorithm

When any string is reduced to a balanced string, one of the following will be true:

* The first bracket is deleted.
* The first bracket stays where it is and matches the bracket at some position `k` (possibly after changing one or both of them).
* The first bracket is swapped with the second, which in turn matches the bracket at position `k`.

In the second case, the bracket at position `k` may have swapped with one of its neighbors. In either of the latter two cases, the string between the (possibly newly) first bracket and the bracket that started in position `k` must be edited to a balanced string, as does the string consisting of everything after `k`.

This means that a dynamic programming approach may be used. Since a swapped bracket need not be swapped again, we only need to consider contiguous substrings, as well as subsequences formed by removing the second character and/or the penultimate character from such a substring. Hence, there are only O(n2) subsequences we need to look at. Each of those has O(n) possible ways to match (or delete) the first bracket, so the algorithm would be O(n3) under the conditions above.

## The data structure

The right stack includes the brackets from the original string, with two bytes per bracket. The first entry determines the entire bracket, and is chosen such that matched brackets have a difference of exactly 1. The second entry only determines whether it is an opening bracket or a closing bracket: this determines how many changes it takes for two brackets to match each other. No implicit zeros below this are ever made explicit, so that we can use `[]` to get the total length of this string.

Each substring under consideration is represented by two numbers in the range 0 to 2n: one for the beginning position, and one for the end. The interpretation is as follows:

* A substring starting at `2k` will start at position `k` (0-indexed), and the second character is not removed.
* A substring starting at `2k+1` will start at position `k`, and the second character is removed due to having been swapped left.
* A substring ending at `2k` will end just before position `k` (i.e., the range is left-inclusive and right-exclusive.)
* A substring ending at `2k-1` will end just before position `k`, and the penultimate character is removed due to having been swapped right.

Some ranges (`k` to `k+1`, `2k+1` to `2k+1`, `2k+1` to `2k+3`, and `2k+1` to `2k+5`) make no physical sense. Some of those show up as intermediate values anyway, because it's easier than adding additional checks to avoid them.

The left stack stores the number of edits needed to convert each substring into a balanced string. The edit distance for the interval `(x,y)` is stored at depth `x + y(y-1)/2`.

During the inner loop, entries are added above the left stack to denote which moves are possible. These entries are 5 bytes long. Counting from the top, the numbers are `d+1`, `y1`, `x1`, `y2`, `x2`, where the move costs `d` edit steps and divides the substring into `(x1,y1)` and `(x2,y2)`.

## The code

Description to come. For now, here's my working copy of the code. Some comments may be inconsistent with terminology.

```
# Determine bracket type for each byte of input
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}

# For every possible interval length:
<>([[]]){

  # Compute actual length
  ([[]({}()<>)]<>)

  # Note: switching stacks in this loop costs only 2 bytes.
  # For each starting position:
  # Update/save position and length
  <>{(({}())<<>(({})<

    # Get endpoints
    (({}(<()>))<>({}))

    # If length more than 3:
    ([(())()()]){<>({}())}{}{

      # Clean up length-3 left over from comparison
      <>{}<>

      # Initialize counter at 2
      # This counter will be 1 in the loop if we're using a swap at the beginning, 0 otherwise
      ({}())

      # For each counter value:
      {

        # Decrement counter and put on third stack
        (((({}<

          # Do mod 2 for end position
          (({}<>)<{({}()<([(){}])>)}{}>)<>

          # Do mod 2 for start position
          (({}(<>))<{({}()<([(){}])>)}{}<>>)

        # Subtract 1 from counter if swap already happened
        ><>({}))(<

          # Compute start position of substrings to consider
          (((({}({})[()])[()()]<>({}))

            # Compute start position of matches to consider
            <>[({})({}){}]({}<>))<>

            # Compute end position of matches to consider
            [(({}<>)<>({}<>)<>)]

          # Push total distance of matches
          )

        # Push counter as base cost of moves
        # Also push additional copy to deal with length 5 intervals starting with an even number
        <>>)))[()](<()>)<

          # With match distance on stack
          <>(({})<

            # Move to location in input data
            ({}{}()){({}()<({}<>)<>>)}{}

            # Make copy of opening bracket to match
            <>(({})<<>(({}<>))>)

          # Mark as first comparison (swap allowed)
          <>(())>)

          # For each bracket to match with:
          {({}[()()]<

            (<([(

              # If swap is allowed in this position:
              {

                # Subtract 1 from cost
                [{}]

                # Add 1 back if swap doesn't perfectly match
                <(({})()<>[({})]<>)>{()(<{}>)}

              }{}

              # Shift copy of first bracket over, while computing differences
              <(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>

              # Add 1 if not perfectly matched
              {()(<{}>)}{}

              # Add 1 if neither bracket faces the other
              # Keep 0 on stack to return here
              (){[()](<{}>)}

              # Return to start of brackets
              <<>{({}<>)<>}{}>

            # Add to base cost and place under base cost
            )]({}{}))>)

            # Return to spot in brackets
            # Zero here means swap not allowed for next bracket
            <>{({}<>)<>}

          >)}

          # Cleanup and move everything to right stack
          {}{}<>{}{}{({}<>)<>}{}

          # Remove one copy of base cost, and move list of costs to right stack
          {}(<>)<>{({}<>)<>}{}

          # If swap at end of substring, remove second-last match
          {(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}

          # Put end of substring on third stack
          ((({}<({}({})({})<

            # If swap at beginning of substring, remove first match
            {{}<>{}(<>)}{}

            # Move start of substring to other stack for safekeeping
            (((({}<({}<>)>)<>)))

          # Create "deletion" record, excluding cost
          <>>)<>>)<>

          # Move data to left stack
          <({}<({}<<>

            # Add cost to deletion record
            (()())

          >)>)>)

          # Put start position on third stack under end position
          <<>({}<

            # For each matching bracket cost:
            {}{

              # Move cost to left stack
              ({}<>)

              # Make three configurations
              ([()()()]){

                # Increment counter
                ((({}()()<>))[()]<

                  # Increment cost in first and third configurations
                  (({()(<{}>)}{})<>({}<

                    # Keep last position constant
                    (({}<

                      # Beginning of second interval: 1, 2, 1 past end of first
                      <>({}[()()]

                        # End of first interval: -3, -1, 1 plus current position
                        (()[({})({})]

                          # Move current position in first and third configurations
                          ({[()](<{}>)}{}<>{}<

                            (({})<>)

                          >)

                        <>)

                      )

                    >)<>)

                  >)<>)

                  # Move data back to left stack
                  <>({}<({}<({}<({}<>)>)>)>)

                >)

              }{}

            {}<>}

            # Eliminate last entry
            # NOTE: This could remove the deletion record if no possible matches.  This is no loss (probably).
            <>{}{}{}{}{}{}{}{}

        # Restore loop variables
        >)>)>)

      }{}

      # With current endpoints on third stack:
      ({}<({}<

        # For all entries
        {

          # Compute locations and move to right stack
          ({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>

        }

        # For all entries (now on right stack):
        <>{

          # Cost of match
          ((({}

            # Do twice:
            (()()){([{}](

              # Add cost of resulting substrings
              <({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>

            # Evaluate as sum of two runs
            ))([{}()]{})}{}

          )))

          # Find smaller of cost and current minimum
          <>(({}))<>{<>({}[()])}{}

          # Push new minimum in place of old minimum
          ({}<<>{}{}{<>}>)

          <>{}

        }

        # Subtract 1 if nonzero
        <>(({}<>){[()](<{}>)}{})(<>)

      >)>)

      <>(<({}<>)>)<>

    # Otherwise (length 3 or less), use 1 from earlier as cost.
    # Note that length 0-1 is impossible here.
    }<>{}

    # With cost on third stack:
    ({}<

      # Find slot number to store cost of interval
      (({}){({}())}{}{})

      # Move to slot
      {({}<({}<>)>(())<>)}{}

    # Store new cost
    {}>)

    # Move other slots back where they should be
    <>{{}({}<>)<>}{}

  Restore length/position for next iteration
  >)<>>)}

  # Clear length/position from inner loop
  {}<>([[]{}])

}{}

(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)

```
> 16 votes

# Answer
# Haskell, 797 bytes

```
import Data.Array;import Data.Function;import Data.List;
e=length;f=fst;o=map;s=listArray;u=minimum;b p=let{m=e p;x=s(1,m)p;
v=s(1,m)(listArray('(','}')[0,0..]:[v!i//[(x!i,i)]|i<-[1..m-1]]);
d q=let{n=e q;y=s(1,n)q;t(a,b)=listArray((a,b),(m,n));
c=t(1,1)[sum[1|x!i/=y!j]|i<-[1..m],j<-[1..n]];
d=t(-1,-1)[if i<0||j<0then m+n else
if i*j<1then(i+j)else u[1+d!(i-1,j),1+d!(i,j-1),c!(i,j)+d!(i-1,j-1),
let{k=v!i!(y!j)-1;l=w!(i,j-1)-1}in-3+i+j-k-l+d!(k,l)]|i<-[-1..m],j<-[-1..n]];
w=t(1,0)[if j>0&&c!(i,j)>0then w!(i,j-1)else j|i<-[1..m],j<-[0..n]]}in d!(m,n);
a=s(0,div m 2)([(m,"")]:[(concat.take 2.groupBy(on(==)f).sort.o(\q->(d q,q)))(
[b:c++[d]|[b,d]<-words"() <> [] {}",(_,c)<-a!(l-1)]++
concat[[b++d,d++b]|k<-[1..div l 2],(_,b)<-a!k,(_,d)<-a!(l-k)])|l<-[1..div m 2]]);
}in u(o(f.head)(elems a))

```

Try it online!
> 3 votes

---
Tags: code-golf, string, balanced-string, brain-flak
---


title: Ternary-if Converter

text:
# Question
Title: Ternary-if Converter
In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.

For example (in Java):

```
// there is a String `s` and an int `i`
if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";

```

Can be shortened with a ternary-if to:

```
s=i<0?"Neg":i>0?"Pos":"Neut";

```

## Challenge:

**Input:** A regular if-else (possible with nesting) that sets a single variable.

**Output:** The converted ternary-if.

## Challenge rules:

* You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).
* You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each `else` (including at `else if`).
* You can assume the variable names used are always a single lowercase letter (`[a-z]`).
* The values given to the variables can be one of:
    + Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. `"Test"`, `"SomeString"`, `"Example_string"`, etc.). You can assume the strings will never contain the substrings `if` or `else`, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character `=`. It can contain the characters `><(){}[];?:!&|`, but will be in the printable ASCII range only (`['!' (33), '~' (126)]`).
    + Integers (i.e. `0`, `123`, `-55`, etc.)
    + Decimals (i.e. `0.0`, `0.123`, `-55.55`, etc.)
* The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.
* The conditions within parenthesis can contain the following characters `=<>!+-/*%&|[]`, `a-z`, `0-9`. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like `if(if<0)`).
* You can assume there won't be any short-cuts like `i*=10` instead of `i=i*10`.
* You won't have to handle dangling `else` cases, so all `if` can be paired up with an `else`. I.e. `if(a)if(b)r=0;else r=1;` isn't a possible input-case. `if(a)if(b)r=0;else r=1;else r=2;` or `if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;` are however.
* I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.
* All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

## General rules:

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

## Test cases:

```
Input:   if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
Output:  s=i<0?"Neg":i>0?"Pos":"Neut";

Input:   if(i%2<1)r=10;else r=20;
Output:  r=i%2<1?10:20;

Input:   if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
Output:  i=n<10?m<0?0:10:m<0?-1:1;

Input:   if(i==1)i=0.0;else i=0.25;
Output:  i=i==1?0.0:0.25;

Input:   if(!a)if(b)r=0;else r=1;else r=2;
Output:  r=!a?b?0:1:2;

Input:   if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
Output:  r=a?b?0:1:c?2:3;

Input:   if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
Output:  r=a&&b?0:a&&!b?1:-1;

Input:   if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
Output:  r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

Input:   if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
Output:  r=i>0?"i":j>0?"j":q>0?"q":"other";

Input:   if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
Output:  x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";

Input:   if(b[0]<=b[1])q=5;else if(b[0]==null)q=0;else q=-10;
Output:  q=b[0]<=b[1]?5:b[0]==null?0:-10;

```

# Answer
# Retina 0.8.2, 32 bytes

```
+r`if.(.*?)\)(.=)
$2$1?
;.{6}=
:

```

Try it online! Explanation:

```
r`if.(.*?)\)(.=)
$2$1?

```

Handle an `if` immediately before an assignment by moving the assignment before the condition and appending a `?`. The stage is matched right-to-left to ensure we get the if closest to the assignment, while the `\)` ensures that we don't match `else` by mistake.

```
+

```

Repeat the stage to take care of nested `if`s.

```
;.{6}=
:

```

Any remaining assignments are `else`s so replace the `;else ?=` with a `:`.
> 6 votes

# Answer
# Python 2, ~~126~~ ~~121~~ ~~120~~ ~~114~~ 100 bytes

```
lambda s:findall(' (.=)',s)[0]+sub('if.(.*?)\)(.=)?',r'\1?',sub('.{5} (.=)?',':',s))
from re import*

```

Try it online!

---

Saved:

* -1 byte, thanks to Kevin Cruijssen
> 7 votes

# Answer
# Perl 5 -p, ~~50~~ ~~49~~ 48 bytes

```
s/if.(.*?)\)(.=)/\2\1?/g;s/.if./?/g;s/;.{6}=/:/g

```

Try it online!

The 48 byte version is inspired by Neil's Retina answer.

### Explanation

```
# Replace "if(e1)if(e2)x=" with "x=e1)if(e2?"
s/if.(.*?)\)(.=)/\2\1?/g;
# Replace ")if(" with "?"
s/.if./?/g;
# Replace ";else x=" with ":"
s/;.{6}=/:/g

```

### Old 49 byte solution

```
s/.{5} (.=)?/:/g;s/if.(.*?)\)(.=)?/\1?/g;$_=$2.$_

```
> 7 votes

# Answer
# Ruby, ~~72~~ 71 bytes

```
->s{$a=$2while s.gsub!(/if.(.*?)\)(.=)?(.*?);\w* (.=)?/,'\1?\3:');$a+s}

```

Try it online!
> 4 votes

# Answer
# Kakoune v2018.09.04, 43 38 37 bytes

```
xs\w=(?!=)<ret>d<a-h>Psif.<ret>df);r?xs;else<space><ret>c:<esc>

```

Explanation:

Kakoune is a multiple selection based, modal editor, inspired by Vim.

1. `x` select the whole line
2. `s` ... `<ret>` filter the selection with the regular expression `\w=(?!=)`, which matches all variable assignments, and doesn't match `==` comparisons
3. `d` delete each selection and put its contents in the default register
4. `<a-h>` extend all selections to the beginning of their line
5. `P` paste the content of the default register before each selection
6. `s` ... `<ret>` filter the selection with the regular expression `if.`
7. `d` delete each selection
8. `f` extend each selection forward to the next `)`
9. `;` reduce each selection to its cursor
10. `r` replace each character of each selection with `?`
11. `x` select the whole line
12. `s` ... `<ret>` filter the selection with `;else<space>`
13. `c` ... `<esc>` clear each selection and replace it with `:`

### animation of the code on a test case:
> 4 votes

# Answer
# Java (JDK), 119 116 bytes

Almost entirely pure regex solution, chopped and changed a bit from a couple of the other answers.

*-3 bytes thanks to some more regex trickery from Kevin*

```
s->s.replaceAll(".*(.=).*","$1$0").replaceAll("if.(.*?)\\)","$1?").replaceAll("([ ?]).=","$1").replace(";else ",":")

```

Try it online!

**Explanation**

```
s->                                         // Lambda function taking a String
   s.replaceAll(".*(.=).*","$1$0")          // Find assigned variable and append to start of String
    .replaceAll("if.(.*?)\\)","$1?")        // Replace any 'if' statements with their condition
                                            // followed by '?'
    .replaceAll("([? ]).=","$1")            // Remove all assignments after a '?' or space
    .replace(";else ",":");                 // Simple replace (no regex) to remove 'else' statements

```
> 4 votes

# Answer
# Clean, ~~386~~ ~~375~~ ~~216~~ ~~196~~ 189 bytes

Look ma, no regex!

```
import StdEnv,Data.List
?[_,'=':b]= $b
?b= $b
$['if(':s]#(h,[_:t])=span((<>)')')s
=h++['?': ?t]
$[';else ':s]=[':': ?s]
$[a:b]|b>[]=[a: $b]=b
@s=hd[[v,e: $s]\\['else ',v,e=:'=':_]<-tails s]

```

Try it online!
> 3 votes

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

```
s=>(p=s.replace(/(?:if.(.*?)\)|;.*? )(.=)?/g,(_,t,v)=>(V=v||V,t)?t+'?':':'),V+p)

```

Try it online!

Thanks to Kevin Cruijssen, 2 bytes saved.
> 2 votes

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


title: Logic Gates Manually

text:
# Question
Title: Logic Gates Manually
Make a program that simulates the basic logic gates.

**Input:** An all-caps word followed by 2 1 digit binary numbers, separated by spaces, such as `OR 1 0`. The gates `OR`, `AND`, `NOR`, `NAND`, `XOR`, and `XNOR` are needed.

**Output:** What the output of the entered logic gate would be given the two numbers: either 1 or 0.

**Examples:**
`AND 1 0` becomes `0`
`XOR 0 1` becomes `1`
`OR 1 1` becomes `1`
`NAND 1 1` becomes `0`

This is codegolf, so the shortest code wins.

# Answer
> 4 votes
# 05AB1E, ~~13~~ ~~12~~ ~~10~~ 8 bytes

```
ÇO₁*Ƶï%É

```

Port of *@mazzy*'s alternative calculation mentioned in the comment on his Powershell answer (`*256%339%2` instead of `*108%143%2`).

Try it online or verify all test cases.

**Explanation:**

```
Ç            # Convert each character in the (implicit) input to a unicode value
 O           # Sum them together
  ₁*         # Multiply it by 256
    Ƶï%      # Then take modulo-339
        É    # And finally check if it's odd (short for %2), and output implicitly

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶï` is `339`.

# Answer
> 31 votes
# Python 2, 38 bytes

```
lambda s:sum(map(ord,s))*3%61%37%9%7%2

```

Try it online!

A good ol' modulo chain applied to the sum of ASCII values of the input string, making for a solution that's just overfitting. The total ASCII value is distinct for each possible input, except that those with `0 1` and `1 0` give the same result, which is works out because all the logic gates used are symmetric.

The `*3` separates out otherwise-adjacent values for inputs that different only in the bits, since these make it hard for the mod chain to split up. The length and size of numbers in the mod chain creates roughly the right amount of entropy to fit 18 binary outputs.

A shorter solution is surely possible using `hash(s)` or `id(s)`, but I avoided these because they are system-dependent.

---

# Python 2, 50 bytes

```
lambda s:'_AX0NRD'.find((s*9)[35])>>s.count('0')&1

```

Try it online!

A slightly more principled solution. Each logic gate gives a different result for each count of zeroes in the input, encodable as a three-bit number from 1 to 6. Each possible logic gate is mapped to the corresponding number by taking `(s*9)[35]`, which are all distinct. For `OR`, this winds up reading one of the bits so the character could be `0` or `1`, but it turns out to work to check if it's `0`, and a `1` will correctly give a `1` result anyway.

# Answer
> 10 votes
# JavaScript (ES6), 39 bytes

```
s=>341139>>parseInt(btoa(s),34)%86%23&1

```

Try it online!

### How?

We can't parse spaces with `parseInt()`, no matter which base we're working with. So we inject a base-64 representation of the input string instead. This may generate `=` padding characters (which can't be parsed with `parseInt()` either), but these ones are guaranteed to be located at the end of the string and can be safely ignored.

We parse as base \\$34\\$ and apply a modulo \\$86\\$, followed by a modulo \\$23\\$, which gives the following results. This includes inaccuracies due to loss of precision. The final result is in \\$\[0..19\]\\$, with the highest truthy index being at \\$18\\$, leading to a 19-bit lookup bitmask.

```
 input      | to base-64     | parsed as base-34 | mod 86 | mod 23 | output
------------+----------------+-------------------+--------+--------+--------
 "AND 0 0"  | "QU5EIDAgMA==" |  1632500708709782 |   26   |    3   |    0
 "AND 0 1"  | "QU5EIDAgMQ==" |  1632500708709798 |   42   |   19   |    0
 "AND 1 0"  | "QU5EIDEgMA==" |  1632500708866998 |   34   |   11   |    0
 "AND 1 1"  | "QU5EIDEgMQ==" |  1632500708867014 |   50   |    4   |    1
 "OR 0 0"   | "T1IgMCAw"     |     1525562056532 |   52   |    6   |    0
 "OR 0 1"   | "T1IgMCAx"     |     1525562056533 |   53   |    7   |    1
 "OR 1 0"   | "T1IgMSAw"     |     1525562075028 |   58   |   12   |    1
 "OR 1 1"   | "T1IgMSAx"     |     1525562075029 |   59   |   13   |    1
 "XOR 0 0"  | "WE9SIDAgMA==" |  1968461683492630 |   48   |    2   |    0
 "XOR 0 1"  | "WE9SIDAgMQ==" |  1968461683492646 |   64   |   18   |    1
 "XOR 1 0"  | "WE9SIDEgMA==" |  1968461683649846 |   56   |   10   |    1
 "XOR 1 1"  | "WE9SIDEgMQ==" |  1968461683649862 |   72   |    3   |    0
 "NAND 0 0" | "TkFORCAwIDA=" | 61109384461626344 |   62   |   16   |    1
 "NAND 0 1" | "TkFORCAwIDE=" | 61109384461626350 |   70   |    1   |    1
 "NAND 1 0" | "TkFORCAxIDA=" | 61109384461665650 |   64   |   18   |    1
 "NAND 1 1" | "TkFORCAxIDE=" | 61109384461665656 |   72   |    3   |    0
 "NOR 0 0"  | "Tk9SIDAgMA==" |  1797025468622614 |   76   |    7   |    1
 "NOR 0 1"  | "Tk9SIDAgMQ==" |  1797025468622630 |    6   |    6   |    0
 "NOR 1 0"  | "Tk9SIDEgMA==" |  1797025468779830 |   84   |   15   |    0
 "NOR 1 1"  | "Tk9SIDEgMQ==" |  1797025468779846 |   14   |   14   |    0
 "XNOR 0 0" | "WE5PUiAwIDA=" | 66920415258533864 |    0   |    0   |    1
 "XNOR 0 1" | "WE5PUiAwIDE=" | 66920415258533870 |    8   |    8   |    0
 "XNOR 1 0" | "WE5PUiAxIDA=" | 66920415258573170 |    2   |    2   |    0
 "XNOR 1 1" | "WE5PUiAxIDE=" | 66920415258573176 |   10   |   10   |    1

```

# Answer
> 6 votes
## CJam (13 bytes)

```
q1bH%86825Yb=

```

Assumes that input is without a trailing newline.

Online test suite

This is just a simple hash which maps the 24 possible inputs into 17 distinct but consistent values and then looks them up in a compressed table.

## Python 2 (36 bytes)

```
lambda s:76165>>sum(map(ord,s))%17&1

```

This is just a port of the CJam answer above. Test suite using xnor's testing framework.

# Answer
> 3 votes
# Perl 6, 20 bytes

```
*.ords.sum*108%143%2

```

Try it online!

A port of maddy's approach. Alternatively, `*256%339%2` also works.

# Perl 6, 24 bytes

```
*.ords.sum*3%61%37%9%7%2

```

Try it online!

A port of xnor's answer. I'll have a go at finding a shorter one, but I think that's probably the best there is.

# Answer
> 3 votes
# Jelly, ~~13~~ 10 bytes

```
OSị“ʋN’BŻ¤

```

Try it online!

Port of Peter Taylor's answer.

# Answer
> 3 votes
# Charcoal, 32 bytes

```
§01÷⌕⪪”＆⌈4Ｙ⍘ＬH⦄vü|⦃³Ｕ}×▷” Ｓ∨⁺ＮＮ⁴

```

Try it online! Link is to verbose version of code. Explanation: The compressed string expands to a list of the supported operations so that the index of the given operation is then shifted right according to the inputs and the bit thus extracted becomes the result.

```
XOR     001
AND     010
OR      011
NOR     100
NAND    101
XNOR    110
inputs  011
        010

```

74-byte version works for all 16 binary operations, which I have arbitrarily named as follows: ZERO AND LESS SECOND GREATER FIRST XOR OR NOR XNOR NFIRST NGREATER NSECOND NLESS NAND NZERO.

```
§10÷÷⌕⪪”＆↖VρＳ´↥cj/v⊗J[Rf↓⪫？9ＫO↘Ｙ⦄;↙W´Ｃ>η=⁴⌕✳AＫＸIＢ｜⊖\`⊖:Ｂ�Ｊ/≧vF@$h⧴” Ｓ∨Ｎ²∨Ｎ⁴

```

Try it online! Link is to verbose version of code.

# Answer
> 3 votes
# , 21 bytes

```
2|7|9|37|61|3*1#.3&u:

```

Try it online!

Port of xnor's Python 2 solution.

---

# , 30 bytes

```
XNOR=:=/
NAND=:*:/
NOR=:+:/
".

```

Try it online!

Some bit of fun with eval `".` and standard library (which already includes correct `AND`, `OR`, `XOR`).

---

# , 41 bytes

```
({7 6 9 8 14 1 b./)~1 i.~' XXNNA'E.~_2&}.

```

Try it online!

More J-style approach.

### How it works

A very general J trick is hidden here. Often, the desired function has the structure "Do F on one input, do H on the other, and then do G on both results." Then it should operate like `(F x) G H y`. In tacit form, it is equivalent to `(G~F)~H`:

```
x ((G~F)~H) y
x (G~F)~ H y
(H y) (G~F) x
(H y) G~ F x
(F x) G H y

```

If `G` is an asymmetric primitive, just swap the left and right arguments of the target function, and we can save a byte.

Now on to the answer above:

```
({7 6 9 8 14 1 b./)~1 i.~' XXNNA'E.~_2&}.

1 i.~' XXNNA'E.~_2&}.  Processing right argument (X): the operation's name
                _2&}.  Drop two chars from the end
1 i.~' XXNNA'E.~       Find the first match's index as substring
                       Resulting mapping is [OR, XOR, XNOR, NOR, NAND, AND]

7 6 9 8 14 1 b./  Processing left argument (Y): all logic operations on the bits
7 6 9 8 14 1 b.   Given two bits as left and right args, compute the six logic functions
               /  Reduce by above

X{Y  Operation on both: Take the value at the index

```

# Answer
> 3 votes
# Mathematica, 55 bytes

```
Symbol[ToCamelCase@#][#2=="1",#3=="1"]&@@StringSplit@#&

```

Pure function. Takes a string as input and returns `True` or `False` as output. Since `Or`, `And`, `Nor`, `Nand`, `Xor`, and `Xnor` are all built-ins, we use `ToCamelCase` to change the operator to Pascal case, convert it to the equivalent symbol, and apply it to the two arguments.

# Answer
> 3 votes
# Powershell, ~~36~~ 34 bytes

Inspired by xnor, but the sequence `*108%143%2` is shorter then original `*3%61%37%9%7%2`

```
$args|% t*y|%{$n+=108*$_};$n%143%2

```

Test script:

```
$f = {

 $args|% t*y|%{$n+=108*$_};$n%143%2
#$args|% t*y|%{$n+=3*$_};$n%61%37%9%7%2   # sequence by xnor

}

@(
    ,("AND 0 0", 0)
    ,("AND 0 1", 0)
    ,("AND 1 0", 0)
    ,("AND 1 1", 1)
    ,("XOR 0 0", 0)
    ,("XOR 0 1", 1)
    ,("XOR 1 0", 1)
    ,("XOR 1 1", 0)
    ,("OR 0 0", 0)
    ,("OR 0 1", 1)
    ,("OR 1 0", 1)
    ,("OR 1 1", 1)
    ,("NAND 0 0", 1)
    ,("NAND 0 1", 1)
    ,("NAND 1 0", 1)
    ,("NAND 1 1", 0)
    ,("NOR 0 0", 1)
    ,("NOR 0 1", 0)
    ,("NOR 1 0", 0)
    ,("NOR 1 1", 0)
    ,("XNOR 0 0", 1)
    ,("XNOR 0 1", 0)
    ,("XNOR 1 0", 0)
    ,("XNOR 1 1", 1)

) | % {
    $s,$e = $_
    $r = &$f $s
    "$($r-eq$e): $s=$r"
}

```

Output:

```
True: AND 0 0=0
True: AND 0 1=0
True: AND 1 0=0
True: AND 1 1=1
True: XOR 0 0=0
True: XOR 0 1=1
True: XOR 1 0=1
True: XOR 1 1=0
True: OR 0 0=0
True: OR 0 1=1
True: OR 1 0=1
True: OR 1 1=1
True: NAND 0 0=1
True: NAND 0 1=1
True: NAND 1 0=1
True: NAND 1 1=0
True: NOR 0 0=1
True: NOR 0 1=0
True: NOR 1 0=0
True: NOR 1 1=0
True: XNOR 0 0=1
True: XNOR 0 1=0
True: XNOR 1 0=0
True: XNOR 1 1=1

```

# Answer
> 3 votes
# Java 10, ~~30~~ 28 bytes

```
s->s.chars().sum()*108%143%2

```

Port of *@mazzy*'s Powershell answer.

Try it online.

# Answer
> 2 votes
# JavaScript (Node.js), ~~106~~ 94 bytes

```
x=>([a,c,d]=x.split` `,g=[c&d,c^d,c|d]["OR".search(a.slice(1+(b=/N[^D]/.test(a))))+1],b?1-g:g)

```

Try it online!

Link to the code and all 24 cases.

+9 for forgotten to map the XNOR case.

# Answer
> 1 votes
# JavaScript (Node.js), 45 bytes

**Just a port of xnor's superb Python 2 answer posted upon consent, please give that answer upvotes instead of this.**

```
x=>Buffer(x).reduce((a,b)=>a+b)*3%61%37%9%7%2

```

Try it online!

# Answer
> 1 votes
# Attache, 55 bytes

```
{Eval!$"${Sum!Id''Downcase!SplitAt!_}${N=>__2}"}@@Split

```

Try it online!

A rather brutish solution. Converts the input to the relevant Attache command and evaluates it. (Attache has built-ins for each of the 6 logic gates.)

# Answer
> 1 votes
# Ruby, 20 bytes

```
->s{76277[s.sum%17]}

```

Try it online!

### How it works:

Basically the same as Peter Taylor's answer, but Ruby makes it easier. The magic number is different but the idea was the same.

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


# Question
Title: Drive a hexadecimal 7-segment display using NAND logic gates
The ubiquitous 7-segment numerical display can unambiguously display all 16 hexadecimal digits as show in this wikipedia .gif

Entries for this challenge will create a circuit diagram using NAND logic gates which transforms the four bits of a hex digit to the inputs for the seven segments. The inputs for the 7 segment display are typically labelled as follows: *(DP (decimal point) is ignored for this challenge)*

Thus your circuit will need to conform to the following truth table:

```
Hex   | Hex Input Bit | Output to Segment line:
digit |  3  2  1  0   |  A  B  C  D  E  F  G
------+---------------+-----------------------
   0  |  0  0  0  0   |  1  1  1  1  1  1  0
   1  |  0  0  0  1   |  0  1  1  0  0  0  0
   2  |  0  0  1  0   |  1  1  0  1  1  0  1
   3  |  0  0  1  1   |  1  1  1  1  0  0  1
   4  |  0  1  0  0   |  0  1  1  0  0  1  1
   5  |  0  1  0  1   |  1  0  1  1  0  1  1
   6  |  0  1  1  0   |  1  0  1  1  1  1  1
   7  |  0  1  1  1   |  1  1  1  0  0  0  0
   8  |  1  0  0  0   |  1  1  1  1  1  1  1
   9  |  1  0  0  1   |  1  1  1  1  0  1  1
   A  |  1  0  1  0   |  1  1  1  0  1  1  1
   b  |  1  0  1  1   |  0  0  1  1  1  1  1
   C  |  1  1  0  0   |  1  0  0  1  1  1  0
   d  |  1  1  0  1   |  0  1  1  1  1  0  1
   E  |  1  1  1  0   |  1  0  0  1  1  1  1
   F  |  1  1  1  1   |  1  0  0  0  1  1  1

```

*I think this table is accurate, but please let me know if you spot any errors.*

Your score is determined by the number of 2-input NAND gates you use (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

* `NOT: 1`
* `AND: 2`
* `OR: 3`
* `XOR: 4`

# Answer
# 30 NANDs

I am quite sure there are no simpler solutions to this problem, except perhaps by changing the symbols on the display, but that would be another and different problem.

Since this is actually something useful to do, for instance when programming an FPGA to show output, I provide Verilog code.

As for the minimalism: Of course it was tricky to make. It is not comprehensible, since a 7-segment display is just a fairly random way that humans show numbers, resulting in a circuit that is fairly random too. And as is typical for these minimal circuits, its logical depth is somewhat higher than for close solutions. I guess this is because serial is simpler than parallel.

Transmission delay is indicated by downward position of each NAND gate on the sheet.

Verilog code:

```
// Hexadecimal 7-segment display driver
// Minimal at 30 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/37648/drive-a-hexadecimal-7-segment-display-using-nand-logic-gates
//
// I am quite sure there are no simpler solutions to this problem,
// except perhaps by changing the symbols on the display,
// but that would be another and different problem.
//
// Since this is actually something useful to do, for instance when
// programming an FPGA to show output, I provide this Verilog code.
//
// As for the minimalism: Of course it was tricky to make.
// It is not comprehensible, since a 7-segment display is
// just a fairly random way of showing numbers, resulting
// in a circuit that is fairly random too.
// And as is typical for these minimal circuits, its logical depth
// is somewhat higher than for close solutions. I guess this is because
// serial is simpler than parallel.
//
// 4 bits of input "in_00?", and 7 bits of output,
// one bit per LED in the segment.
//   A
// F   B
//   G
// E   C
//   D

module display7 ( in_000, in_001, in_002, in_003,  G, F, E, D, C, B, A );
  input in_000, in_001, in_002, in_003;
  output G, F, E, D, C, B, A;
  wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022 ;

  nand gate000 ( wir000, in_000, in_002 );
  nand gate001 ( wir001, in_000, in_000 );
  nand gate002 ( wir002, wir000, in_001 );
  nand gate003 ( wir003, in_001, wir002 );
  nand gate004 ( wir004, wir000, wir002 );
  nand gate005 ( wir005, in_002, wir003 );
  nand gate006 ( wir006, in_003, wir001 );
  nand gate007 ( wir007, wir006, wir004 );
  nand gate008 ( wir008, in_003, wir005 );
  nand gate009 ( wir009, wir005, wir008 );
  nand gate010 ( wir010, in_003, wir008 );
  nand gate011 ( wir011, wir010, wir009 );
  nand gate012 ( wir012, wir010, wir007 );
  nand gate013 ( wir013, wir001, wir011 );
  nand gate014 ( wir014, wir003, wir004 );
  nand gate015 (      G, wir011, wir014 );
  nand gate016 ( wir015, in_003, wir014 );
  nand gate017 ( wir016, wir015, wir013 );
  nand gate018 (      C, wir016, wir012 );
  nand gate019 ( wir017, wir016, wir007 );
  nand gate020 ( wir018, wir003, wir012 );
  nand gate021 ( wir019, wir017, in_003 );
  nand gate022 (      F, wir011, wir017 );
  nand gate023 (      D, wir018, wir017 );
  nand gate024 (      B, wir012,      F );
  nand gate025 ( wir020, wir004, wir018 );
  nand gate026 ( wir021, wir001,      D );
  nand gate027 (      E, wir019, wir021 );
  nand gate028 ( wir022,      D, wir019 );
  nand gate029 (      A, wir020, wir022 );
endmodule

```

Kim Øyhus

---

I (@Digital Trauma) recently reviewed this answer and was so impressed with it, I drew it out in Logic.ly and captured this GIF - it really does work!
> 22 votes

# Answer
# Dominoes - Total Score: 243 NANDs

* ORs used: 61 (3 NANDs each -\> 183 NANDs)
* NOTs used: 60 (1 NANDs each -\> 60 NANDs)

This solution is in dominoes and required a collection of pieces of software I wrote in the course of answering Martin Büttner's two Domino related questions to produce (Golfing for Domino Day and Domino Circuits).

By modifying my Domino Circuit solver, I was able to produce a domino circuit (this file also contains the solver output and circuit skeleton) consisting of ORs, and IFNOTs where the first input is always TRUE (so it's essentially a NOT). Because there isn't much that *will* fit in this answer, I present the OR and NOT solutions to the truth table:

```
A: 1011011111101011
((-1 ifnot (2 or (1 or (-1 ifnot 0)))) or ((-1 ifnot ((-1 ifnot 1) or (-1 ifnot 2))) or ((-1 ifnot (3 or (-1 ifnot (0 or (-1 ifnot 1))))) or (-1 ifnot (0 or ((-1 ifnot 3) or (-1 ifnot (2 or 1))))))))
B: 1111100111100100
((-1 ifnot (3 or 1)) or ((-1 ifnot (3 or (2 or 0))) or (-1 ifnot ((-1 ifnot 3) or ((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot 2))))))))
C: 1101111111110100
((-1 ifnot (2 or (-1 ifnot 3))) or ((-1 ifnot (1 or (-1 ifnot 0))) or (-1 ifnot (0 or (-1 ifnot (3 or (1 or (-1 ifnot 2))))))))
D: 1011011011011110
((-1 ifnot (3 or (1 or 0))) or ((-1 ifnot (2 or ((-1 ifnot (3 or 0)) or (-1 ifnot (1 or 0))))) or (-1 ifnot ((-1 ifnot 2) or ((-1 ifnot (3 or 1)) or (-1 ifnot ((-1 ifnot 1) or (-1 ifnot 3))))))))
E: 1010001010111111
((-1 ifnot (3 or (-1 ifnot (2 or (-1 ifnot 1))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or 1)))))
F: 1000111011111011
((-1 ifnot (3 or (-1 ifnot 1))) or ((-1 ifnot (2 or (0 or (-1 ifnot (1 or (-1 ifnot 3)))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or (-1 ifnot 1)))))))
G: 0011111011110111
((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or ((-1 ifnot (1 or (-1 ifnot (2 or 0)))) or (-1 ifnot ((-1 ifnot (3 or 2)) or (-1 ifnot (0 or (-1 ifnot 3)))))))

```

*Note that the only binary operations used are OR and IFNOT, where I count each IFNOT as a NOT for scoring purposes*

I added a 7-segment display to the end of the circuit and fed it into a domino simulator/gif generator. The resulting gif (which shows 'A' being displayed) took about 2 hours to generate. Because the final circuit is 1141 * 517 in size each "cell" is represented by a single pixel. A black cell is empty, a grey cell has a standing domino in it, and a white cell has a fallen domino in it. This means that you can't really tell what is going on, and it won't help if it's being squashed at all. *Sparr kindly provided a much smaller version of my original gif (650kB), so here it is!*

Below is the last frame of the animation for input 1010 ('A') as above. You can see the inputs on the far left, powerline at the top, the switchboard taking up most of the space, the 7 individual pieces of logic (these are domino representations of the functions above) to the left of the switch board, and to the far right is the 7-segment display itself. When this runs, the individual segments light up roughly at the same time, so you can't be looking at it for too long with some segments lit up waiting for others to light up.

*See the animation in it's full glory here (36MB) or here (650kB, courtesy of Sparr) (the smaller copy is much smaller, but my browser seemed to like skipping frames marring the beauty so I've left the original thusly)*

*The detail of the 7-segment display can be seen here ('1' is shown)*
> 18 votes

# Answer
Using ~ for NOT and N for NAND, a computer search (without sharing terms between outputs) finds a solution with 82 NANDs without sharing. Manually looking for sharing terms reduces it to 54 NANDs, and a computer search that includes sharing further reduces it to 37 NANDs. The minimum might be even lower, as the method is certainly not exhaustive.

Here's the program that recreates the above table. Each line is labeled with the NANDS for that output.

```
#include <stdio.h>

int N(int x, int y) { return 1 & ~(x & y); }

void main(void)
{
    int i0, i1, i2, i3;
    for (i3 = 0; i3 <= 1; i3++) {
    for (i2 = 0; i2 <= 1; i2++) {
    for (i1 = 0; i1 <= 1; i1++) {
    for (i0 = 0; i0 <= 1; i0++) {
            printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
    /* 14 */        N(N(N(i3, N(i2, i1)), N(N(i2, i0), ~i1)), N(N(i2, N(i3, N(i3, i0))), N(i0, N(i3, N(i3, i1))))),
    /* 12 */        N(N(N(i3, i0), N(i2, N(i1, i0))), N(~i1, N(N(i3, i0), N(~i3, N(i2, i0))))),
    /* 10 */        N(N(i0, N(i3, i1)), N(N(i3, i2), N(i1, N(i1, N(~i3, ~i2))))),
    /* 16 */        N(N(N(i2, i1), N(N(i3, i0), N(i2, i0))), N(N(i0, N(i1, ~i2)), N(N(i3, i2), N(N(i3, i1), N(i2, N(i2, i1)))))),
    /*  7 */        N(N(i3, i2), N(N(i2, N(i2, i1)), N(i0, N(i3, i1)))),
    /* 11 */        N(N(i3, N(i2, N(i3, i1))), N(N(i1, N(i2, N(i2, i0))), N(i0, N(i2, ~i3)))),
    /* 12 */        N(N(i3, i0), ~N(N(i1, N(i2, i0)), N(N(i3, i2), N(~i3, N(i2, N(i2, i1)))))) );
    } } } }
}

```

And here's the output:

```
0 0 0 0 : 1 1 1 1 1 1 0
0 0 0 1 : 0 1 1 0 0 0 0
0 0 1 0 : 1 1 0 1 1 0 1
0 0 1 1 : 1 1 1 1 0 0 1
0 1 0 0 : 0 1 1 0 0 1 1
0 1 0 1 : 1 0 1 1 0 1 1
0 1 1 0 : 1 0 1 1 1 1 1
0 1 1 1 : 1 1 1 0 0 0 0
1 0 0 0 : 1 1 1 1 1 1 1
1 0 0 1 : 1 1 1 1 0 1 1
1 0 1 0 : 1 1 1 0 1 1 1
1 0 1 1 : 0 0 1 1 1 1 1
1 1 0 0 : 1 0 0 1 1 1 0
1 1 0 1 : 0 1 1 1 1 0 1
1 1 1 0 : 1 0 0 1 1 1 1
1 1 1 1 : 1 0 0 0 1 1 1

```

And here are the equivalent equations, sharing terms that get it down to 54 NANDs:

```
    /* 1 */ int z1 = 1 - i1;
    /* 1 */ int z2 = 1 - i2;
    /* 1 */ int z3 = 1 - i3;

    /* 1 */ int n_i2_i0 = N(i2, i0);
    /* 1 */ int n_i2_i1 = N(i2, i1);
    /* 1 */ int n_i3_i0 = N(i3, i0);
    /* 1 */ int n_i3_i1 = N(i3, i1);
    /* 1 */ int n_i3_i2 = N(i3, i2);

    /* 1 */ int n_i0_n_i3_i1 = N(i0, n_i3_i1);
    /* 1 */ int n_i2_n_i2_i1 = N(i2, n_i2_i1);

            printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
    /* 9 */ N(N(N(i3, n_i2_i1), N(n_i2_i0, z1)), N(N(i2, N(i3, n_i3_i0)), N(i0, N(i3, n_i3_i1)))),
    /* 7 */ N(N(n_i3_i0, N(i2, N(i1, i0))), N(z1, N(n_i3_i0, N(z3, n_i2_i0)))),
    /* 5 */ N(n_i0_n_i3_i1, N(n_i3_i2, N(i1, N(i1, N(z3, z2))))),
    /* 8 */ N(N(n_i2_i1, N(n_i3_i0, n_i2_i0)), N(N(i0, N(i1, z2)), N(n_i3_i2, N(n_i3_i1, n_i2_n_i2_i1)))),
    /* 2 */ N(n_i3_i2, N(n_i2_n_i2_i1, n_i0_n_i3_i1)),
    /* 8 */ N(N(i3, N(i2, n_i3_i1)), N(N(i1, N(i2, n_i2_i0)), N(i0, N(i2, z3)))),
    /* 6 */ N(n_i3_i0, ~N(N(i1, n_i2_i0), N(n_i3_i2, N(z3, n_i2_n_i2_i1)))) );

```

And here's the 37 NAND solution:

```
    x0fff =  N(i3, i2);
    x33ff =  N(i3, i1);
    x55ff =  N(i3, i0);
    x0f0f =  not(i2);
    x3f3f =  N(i2, i1);
    x5f5f =  N(i2, i0);
    xcfcf =  N(i2, x3f3f);
    xf3f3 =  N(i1, x0f0f);
    x5d5d =  N(i0, xf3f3);
    xaaa0 =  N(x55ff, x5f5f);
    xfc30 =  N(x33ff, xcfcf);
    xd5df =  N(x3f3f, xaaa0);
    xf3cf =  N(x0fff, xfc30);
    xaeb2 =  N(x5d5d, xf3cf);
    x7b6d =  N(xd5df, xaeb2);
    xb7b3 =  N(i1, x7b6d);
    xf55f =  N(x0fff, xaaa0);
    xcea0 =  N(x33ff, xf55f);
    x795f =  N(xb7b3, xcea0);
    xd7ed =  N(xaeb2, x795f);
    xfaf0 =  N(x55ff, x0f0f);
    xae92 =  N(x55ff, x7b6d);
    xdd6d =  N(x33ff, xae92);
    x279f =  N(xfaf0, xdd6d);
    xaf0f =  N(i2, x55ff);
    x50ff =  N(i3, xaf0f);
    xef4c =  N(xb7b3, x50ff);
    x1cb3 =  N(xf3cf, xef4c);
    xef7c =  N(xf3cf, x1cb3);
    xfb73 =  N(i1, x279f);
    x2c9e =  N(xd7ed, xfb73);
    xdf71 =  N(xf3cf, x2c9e);
    xdd55 =  N(i0, x33ff);
    xf08e =  N(x0fff, xdf71);
    x2ffb =  N(xdd55, xf08e);
    x32ba =  N(xcfcf, xdd55);
    xfd45 =  N(x0fff, x32ba);

    printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
            xd7ed, x279f, x2ffb, x7b6d, xfd45, xdf71, xef7c);
    } } } }

```
> 8 votes

# Answer
# 197 NANDs

Since this is my first logic gates challenge. it is not golfed much, and may not be the smallest solution. I'm not using circuit split here.

```
A = OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
B = AND(OR(OR(NOT(c), AND(NOT(d), NOT(XOR(b, a)))), AND(d, a)), NOT(AND(AND(d, b), a)))
C = OR(AND(NOT(c), NOT(AND(AND(NOT(d), b), NOT(a)))), AND(c, OR(NOT(d), AND(AND(d, NOT(b)), a))))
D = AND(OR(OR(OR(a, c), AND(AND(NOT(d), NOT(c)), NOT(a))), AND(AND(d, NOT(c)), NOT(b))), NOT(OR(AND(AND(NOT(d), NOT(b)), XOR(c, a)), AND(AND(c, b), a))))
E = OR(AND(NOT(a), NOT(AND(AND(NOT(d), c), NOT(b)))), AND(d, NOT(AND(AND(NOT(c), NOT(b)), a))))
F = AND(OR(OR(d, c), AND(NOT(b), NOT(a))), NOT(AND(AND(c, a), XOR(d, b))))
G = AND(OR(OR(d, c), b), NOT(OR(AND(AND(NOT(d), c), AND(b, a)), AND(AND(d, c), AND(NOT(b), NOT(a))))))

```
* 36 NOTs used, 36 NANDs
* 41 ANDs used, 84 NANDs
* 19 ORs used, 57 NANDs
* 5 XORs used, 20 NANDs

If I'm right, my score is **197**.

---

During this challenge, I made a simple JavaScript code to test my gate.

```
function NOT(a){return !a}function AND(a,b){return a&b}function OR(a,b){return a|b}function XOR(a,b){return a^b}
for(d=0;d<=1;d++){for(c=0;c<=1;c++){for(b=0;b<=1;b++){for(a=0;a<=1;a++){console.log(""+d+c+b+a,
    // Enter your gate here
    // OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
)}}}}

```

Copy and modify gate, and paste it to your browser's console, or Node.js REPL.
> 4 votes

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