title: Translate Prelude to Befunge

text:
# Question
Title: Translate Prelude to Befunge
This is **Weekly Challenge #2.** Theme: **Translation**

Write a program or function that takes in source code for a program in Prelude and outputs code for an equivalent program in Befunge-93. For the program to be equivalent, it should, for any given input, produce the same output as the Prelude program, and halt if and only if the Prelude program halts.

## Input language: Prelude

Python interpreter:

```
#!/usr/bin/python

import sys

NUMERIC_OUTPUT = True
NUMERIC_INPUT = True

try:
    filename = sys.argv[1]
except:
    print "Usage:", sys.argv[0], "<filename>"
    raise SystemExit

try:
    inFile = file(filename)
except:
    print "Error when opening", filename
    raise SystemExit

# code is kept as a list of voices, each voice a string

code = []
firstLine = True
eof = False
while not eof:
    # read batch of lines
    batch = []
    while 1:
        line = inFile.readline()
        if line == '': eof = True
        if line == '' or line.rstrip() == '*':
            break
        batch.append(line.rstrip())
    maxLen = max([len(b) for b in batch])
    batch = [b + ' '*(maxLen - len(b)) for b in batch]
    if firstLine:
        code = batch
        firstLine = False
    else:
        if len(batch) != len(code):
            print "Error in the program: number of voices changes"
            raise SystemExit
        for i in range(len(batch)):
            code[i] += batch[i]

class Stack:
    def __init__(self):
        self.data = []
    def push(self, value):
        if self.data or value != 0: self.data.append(value)
    def drop(self):
        if self.data: self.data.pop()
    def top(self):
        if self.data: return self.data[-1]
        return 0
    def pop(self):
        value = self.top()
        self.drop()
        return value

numVoices = len(code)
numInstructions = len(code[0])
stacks = [Stack() for x in range(numVoices)]
topValues = [0 for x in range(numVoices)]
# establish loop couplings
loopStack = []
loops = {}
for cp in range(numInstructions):
    curr = [voice[cp] for voice in code]
    if curr.count('(') + curr.count(')') > 1:
        print "Error in the program: More than one bracket; position", cp
        raise SystemExit
    if '(' in curr:
        loopStack.append((cp, curr.index('(')))
    if ')' in curr:
        if not loopStack:
            print "Error in the program: extraneous closing bracket; position", cp
            raise SystemExit
        openingPosition, openingVoice = loopStack.pop()
        loops[openingPosition] = cp
        loops[cp] = openingPosition, openingVoice

if loopStack:
    print "Error in the program: not enough closing brackets"
    raise SystemExit

# now, actually execute the program
cp = 0 # code pointer
while cp < numInstructions:
    # technically we're supposed to shuffle our voices to make sure to perform IO
    # in random order, but screw that for now
    next_cp = cp+1 # can be modified by ( )
    for voice in range(numVoices):
        i = code[voice][cp] # current instruction
        if i == '^':
            stacks[voice].push(topValues[(voice-1) % numVoices])
        elif i == 'v' or i == 'V':
            stacks[voice].push(topValues[(voice+1) % numVoices])
        elif i == '+':
            stacks[voice].push(stacks[voice].pop() + stacks[voice].pop())
        elif i == '-':
            b = stacks[voice].pop()
            a = stacks[voice].pop()
            stacks[voice].push(a-b)
        elif i == '#':
            stacks[voice].drop()
        elif i == '?':
            if NUMERIC_INPUT:
                try: num = int(raw_input())
                except ValueError: num = 0
                stacks[voice].push(num)
            else:
                char = sys.stdin.read(1)
                if not char: char = '\0'
                stacks[voice].push(ord(char))
        elif i == '!':
            if NUMERIC_OUTPUT:
                print stacks[voice].pop()
            else:
                sys.stdout.write(chr(stacks[voice].pop()))
        elif i == '(':
            if stacks[voice].top() == 0:
                next_cp = loops[cp] + 1
        elif i == ')':
            openingPosition, openingVoice = loops[cp]
            if topValues[openingVoice] != 0:
                next_cp = openingPosition + 1
        elif i in '0123456789':
            stacks[voice].push(int(i))
    topValues = [stacks[i].top() for i in range(numVoices)]
    cp = next_cp
```

A Prelude program consists of a number of "voices" which execute instructions simultaneously. The instructions for each voice are on a separate line. Each voice has a separate stack, which is initialized with an infinite amount of zeroes. Execution begins at the leftmost column, and advances one column to the right each tick, except when influenced by `)` or `(` instructions. The program terminates when the last column is reached.

Prelude spec for this challenge:

```
Digits 0-9      Push onto the stack a number from 0 to 9. Only single-digit
                    numeric literals can be used.
^               Push onto the stack the top value of the stack of the above
                    voice.
v               Push onto the stack the top value of the stack of the below
                    voice.
#               Remove the top value from the stack.
+               Pop the top two integers from the stack and push their sum.
-               Pop the top two integers from the stack, subtract the topmost
                    from the second, and push the result.
(               If the top of the stack is 0, jump to the column after the
                    matching `)` after the current column executes.
)               If the top of the stack is not 0, jump to the column after
                    the matching `(` after the current column executes.
?               Read an integer from STDIN.
!               Pop one value from the stack and print it to STDOUT as an
                    integer.
<space>         No-op

```

Notes

* `v` and `^` act cyclically, so the `v` on the bottom voice will copy the stack element of the top voice, and `^` on the top voice will copy from the bottom voice. *Corollary:* Both `v` and `^` duplicate the top of the stack in a single-voice program.
* A `(` and its matching `)` may be located on different lines. *However*, a `)` will always look at the stack of the voice where the corresponding `(` was placed, not the stack where the `)` itself is placed.
* The values produced by the `^` and `v` instructions operate on the values present prior to the completion of any other operations in the same column.
* `?` and `!` operate differently from the specification found on esolangs.org, so be be sure to test with the slightly modified interpreter provided in this post.

Input is guaranteed to have:

* Matching parentheses
* No more than one parenthesis in a column
* Same number of characters on each line
* At least one line
* No column with more than one I/O (`!` or `?`) instruction
* One linefeed character after the instructions for each voice
* No characters other than the ones mentioned above

## Output language: Befunge-93

Befunge is a stack-based language whose program counter (PC; a pointer to the current instruction) moves freely on a two-dimensional grid. It start in the top left corner, moving to the right. The playfield is toroidal, i.e. PC movement wraps around both edges. Befunge also has a stack which is initialised to an infinite number of zeroes. Befunge has the following operations:

```
Digits 0-9      Push onto the stack a number from 0 to 9. Only single-digit
                        numeric literals can be used.
    +               Pop the top two integers from the stack and push their sum.
    -               Pop the top two integers from the stack, subtract the topmost
                        from the second, and push the result.
    *               Pop the top two integers from the stack and push their product.
    /               Pop the top two integers from the stack, divide the second by
                        the topmost, and push the result. Rounds down.
    %               Pop the top two integers from the stack, divide the second by
                        the topmost, and push the remainder.
    !               Pop a value, push 1 if it's zero, push 0 otherwise.
    `               Pop the top two integers from the stack, push 1 if the second
                        is greater than the topmost, push 0 otherwise.
    >               Set PC direction to right.
    <               Set PC direction to left.
    ^               Set PC direction to up.
    v               Set PC direction to down.
    ?               Set PC direction randomly.
    _               Pop a value, if it's 0 set PC direction to right, left otherwise.
    |               Pop a value, if it's 0 set PC direction to down, up otherwise.
    "               Toggle string mode. While in string mode, push each character's
                        ASCII value instead of executing it.
    :               Duplicate top stack element.
    \               Swap top two stack elements.
    $               Pop and discard top stack element.
    .               Pop a value and output it as an integer. Whitespace not included.
    ,               Pop a value and output the corresponding ASCII character.
    #               Jump over the next instruction.
    g               Pop y, pop x, push the character at coordinate (x,y).
    p               Pop y, pop x, pop v, set character at coordinate (x,y) to v.
    &               Read an integer from STDIN and push it.
    ~               Read a character from STDIN and push it ASCII value.
    @               End program.
```

You may assume the following characteristics of the Befunge-93 compiler/interpreter:

* Integers are unlimited-precision.
* It allows grids of any size.
* Grid coordinates (for `g` and `p`) are 0-based.

## Scoring

In order to prevent submissions which simply produce a Prelude interpreter in Befunge and hardcode the Prelude source into it, the goal will be to minimise the size of the resulting Befunge source code.

Below are provided a number of Prelude programs. Your translator will be run on all of these. Your score is the sum of the sizes of the Befunge programs, provided all of them are valid.

Your translator should not be optimised specifically towards these test cases (e.g. by hardcoding handwritten Befunge programs for them). If I suspect any answer of doing so, I reserve the right to change inputs or create additional ones.

## Sample Inputs

Print `n-1` down to `0`:

```
?(1-^!)

```

Logical AND:

```
?  (0)
 ?(0  )
    1  !

```

Logical OR:

```
 ?   (0)
? (0)
   1  1 !

```

Check parity of input (i.e. modulo 2) of nonnegative number:

```
?(1-)
 ^  v
 v1-^^-!

```

Square the input:

```
 ^
  ^+ !
?(1-)

```

Print the *n*th Fibonacci number, where `n = 0` corresponds to 0 and `n = 1` corresponds to 1:

```
0 v+v!
1   ^
?(1-)

```

Signum:

```
  1) v #  - !
 vv (##^v^+)
?(#   ^   ##

```

Division for non-negative inputs:

```
1 (#  1) v #  - 1+)
     vv (##^v^+)
?  v-(0 # ^   #
 ?
   1+              1-!

```

Of course, your program must exhibit the same behavior for all cases, even if the sample program's behavior for negative numbers is not specified.

Finally, your translator should not be unreasonably long:

* It must be contained inside a Stack Exchange post
* It should process the sample inputs in under 10 minutes on a typical desktop computer.

Note that a numeric input for Prelude or Befunge is given as an optional minus sign followed by one or more decimal digits, followed by a newline. Other input is undefined behavior.

You may write your translator in any language. Shortest translated Befunge code wins.

## Leaderboard

* **Sp3000**: 16430 bytes

# Answer
# Python 3, will score later

```
from collections import defaultdict
from functools import lru_cache
import sys

NUMERIC_OUTPUT = True

@lru_cache(maxsize=1024)
def to_befunge_num(n):
    # Convert number to Befunge number, using base 9 encoding (non-optimal,
    # but something simple is good for now)

    assert isinstance(n, int) and n >= 0

    if n == 0:
        return "0"

    digits = []

    while n:
        digits.append(n%9)
        n //= 9

    output = [str(digits.pop())]

    while digits:
        output.append("9*")
        d = digits.pop()

        if d:
            output.append(str(d))
            output.append("+")

    output = "".join(output)

    if output.startswith("19*"):
        return "9" + output[3:]

    return output

def translate(program_str):
    if program_str.count("(") != program_str.count(")"):
        exit("Error: number of opening and closing parentheses do not match")

    program = program_str.splitlines()
    row_len = max(len(row) for row in program)
    program = [row.ljust(row_len) for row in program]
    num_stacks = len(program)

    loop_offset = 3
    stack_len_offset = program_str.count("(")*2 + loop_offset
    stack_offset = stack_len_offset + 1
    output = [[1, ["v"]], [1, [">"]]] # (len, [strings]) for each row
    max_len = 1 # Maximum row length so far

    HEADER_ROW = 0
    MAIN_ROW = 1
    FOOTER_ROW = 2
    # Then stack lengths, then loop rows, then stacks

    # Match closing parens with opening parens
    loop_map = {} # {column: (loop num, stack number to check, is_start)}
    loop_stack = []
    loop_num = 0

    for col in range(row_len):
        col_str = "".join(program[stack][col] for stack in range(num_stacks))

        if col_str.count("(") + col_str.count(")") >= 2:
            exit("Error: more than one parenthesis in a column")

        if "(" in col_str:
            stack_num = col_str.index("(")

            loop_map[col] = (loop_num, stack_num, True)
            loop_stack.append((loop_num, stack_num, False))
            loop_num += 1

        elif ")" in col_str:
            if loop_stack:
                loop_map[col] = loop_stack.pop()

            else:
                exit("Error: mismatched parentheses")

    def pad_max(row):
        nonlocal max_len, output

        while len(output) - 1 < row:
            output.append([0, []])

        if output[row][0] < max_len:
            output[row][1].append(" "*(max_len - output[row][0]))
            output[row][0] = max_len

    def write(string, row):
        nonlocal max_len, output

        output[row][1].append(string)
        output[row][0] += len(string)

        max_len = max(output[row][0], max_len)

    def stack_len(stack, put=False):
        return (to_befunge_num(stack) + # x
                str(stack_len_offset) + # y
                "gp"[put])

    def get(stack, offset=0):
        assert offset in [0, 1] # 1 needed for 2-arity ops

        # Check stack length
        write(stack_len(stack) + "1-"*(offset == 1) + ":0`", MAIN_ROW)

        pad_max(HEADER_ROW)
        pad_max(MAIN_ROW)
        pad_max(FOOTER_ROW)

        write(">" + to_befunge_num(stack + stack_offset) + "g", HEADER_ROW)
        write("|", MAIN_ROW)
        write(">$0", FOOTER_ROW)

        pad_max(HEADER_ROW)
        pad_max(MAIN_ROW)
        pad_max(FOOTER_ROW)

        write("v", HEADER_ROW)
        write(">", MAIN_ROW)
        write("^", FOOTER_ROW)

    def put(stack, value=""):
        put_inst = (value +
                    stack_len(stack) +
                    to_befunge_num(stack + stack_offset) +
                    "p")

        post_insts.append(put_inst)

    def pop(stack):
        put(stack, "0")

    def inc_stack_len(stack):
        post_insts.append(stack_len(stack) + "1+")
        post_insts.append(stack_len(stack, put=True))

    def dec_stack_len(stack):
        post_insts.append(stack_len(stack) + ":0`-") # Ensure nonnegativity
        post_insts.append(stack_len(stack, put=True))

    # Technically not necessary to initialise stack lengths per spec, but it makes it
    # more portable and easier to test against other Befunge interpreters

    for stack in range(num_stacks):
        write("0" + stack_len(stack, put=True), MAIN_ROW)

    for col in range(row_len):
        post_insts_all = []

        loop_start = False
        loop_end = False

        if col in loop_map:
            if loop_map[col][2]:
                loop_start = True
            else:
                loop_end = True

        if loop_start:
            loop_row = loop_offset + 2*loop_map[col][0]
            get(loop_map[col][1])

        elif loop_end:
            get(loop_map[col][1])
            write("!", MAIN_ROW)

        for stack in range(num_stacks-1, -1, -1):
            char = program[stack][col]
            post_insts = [] # Executed after the gets in reverse order, i.e. last added first

            if char in " ()":
                continue

            # Pre-inc, post-dec
            elif char.isdigit():
                inc_stack_len(stack)
                put(stack, char)

            elif char == "?":
                inc_stack_len(stack)
                put(stack, "&")

            elif char == "!":
                get(stack)
                post_insts.append(".91+," if NUMERIC_OUTPUT else ",")
                pop(stack)
                dec_stack_len(stack)

            elif char == "#":
                pop(stack)
                dec_stack_len(stack)

            elif char in "+-":
                get(stack, 1)
                get(stack)
                post_insts.append(char)
                pop(stack) # This one first in case of ! or 1!
                post_insts.append(stack_len(stack) + ":1`-:1\\`+") # Ensure >= 1
                post_insts.append(stack_len(stack, put=True))
                put(stack)

            elif char in "^v":
                offset = -1 if char == "^" else 1

                get((stack + offset) % num_stacks)
                inc_stack_len(stack)
                put(stack)

            else:
                exit("Error: invalid character " + char)

            post_insts_all.append(post_insts)

        while post_insts_all:
            write("".join(post_insts_all.pop()), MAIN_ROW)

        if loop_start or loop_end:
            loop_row = loop_offset + 2*loop_map[col][0]

            pad_max(HEADER_ROW)
            pad_max(MAIN_ROW)
            pad_max(loop_row)
            pad_max(loop_row + 1)

            write(">v", HEADER_ROW)
            write("|>", MAIN_ROW)

            if loop_start:
                write(" ^", loop_row)
                write(">", loop_row + 1)

            else:
                write("<", loop_row)
                write(" ^", loop_row + 1)

    write("@", MAIN_ROW)
    return "\n".join("".join(row) for row_len, row in output)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        exit("Usage: py -3 prefunge.py <input filename> <output filename>")

    with open(sys.argv[1]) as infile:
        with open(sys.argv[2], "w") as outfile:
            outfile.write(translate(infile.read()))

```

Run like `py -3 prefunge.py <input filename> <output filename>`.

It's been a slow week for me, so I was finally bored enough to tackle this six-month old question. I'd ask why nobody else tried, but I'm still feeling the pain from debugging (and there's probably still bugs remaining for all I know).

The question doesn't provide a Befunge-93 interpreter, so I used this one, which is slightly different from the spec. The two key differences are:

* If a char doesn't exist in a given row of the program, then you can't write to that row. This means **you'll need to hit Enter several times to introduce enough newlines at the end**. If you see `NaN`s in the output, this is the most likely cause.
* Grid cells aren't preinitialised to zero - for convenience I've included some preinitialisation in the Befunge outputs, but since it's not necessary I might take it away when I start scoring.

The core layout of the output programs is this:

```
v [header row]
> [main row]
  [footer row]
  ---
   |
   | rows for loops (2 per loop)
   |
  ---
  [stack length row]
  ---
   |
   | rows for stack space (1 per voice)
   |
  ---

```

The stack space is outside the program, hence the newline Enter-spamming comment from earlier.

The core idea is to assign each voice a row which serves as its stack. To maintain these stacks, we also have a special stack length row where the length of each stack is recorded in a cell along the row. The program is then a lot of `g`ets and `p`uts, e.g. for printing the process is:

* Get the cell at `y = stack_row[stack], x = stack_length[stack]`
* Perform `.91+,`, i.e. print as integer then print a newline
* Replace the cell at the above coords with 0 (to simulate popping)
* Decrement `stack_length[stack]`

To perform the simultaneous evaluation of a column, all necessary cells are read and their values are kept on the stack before any cells are written to (e.g. for the printing example, there may be more instructions in between the first and second steps).

```, which is greater than, is employed to make sure the stack lengths never go negative, and for pushing 0s when the stack is empty. This is where the clearly visible branching comes from, but I've got an idea that'll remove the branching, which should remove a great deal of whitespace from the first and third rows.

For the loops, because Prelude loops can jump both ways, we use two rows per loop in a configuration like this:

```
       >v                     >v
(cond) |>  (program)  (cond) !|>

        ^                     <
       >                       ^

```

These loops currently make up the majority of the bytes, but can easily be golfed down by placing them into the codebox with `p`, which I plan to do after I'm happy that the translator is working correctly.

Here's some example output for `?(1-^!)`, i.e. print `n-1` down to `0`:

```
v                        >6gv>v                      >6gv      >6gv                                 >6gv                   >6gv                           >6gv >v
>005p05g1+05p&05g6p05g:0`|  >|>05g1+05p105g6p05g1-:0`|  >05g:0`|  >-005g6p05g:1`-:1\`+05p05g6p05g:0`|  >05g1+05p05g6p05g:0`|  >.91+,005g6p05g:0`-05p05g:0`|  >!|>@
                         >$0^                        >$0^      >$0^                                 >$0^                   >$0^                           >$0^
                              ^                                                                                <
                             >                                                                                ^

```

Square-the-input:

```
v                                >8gv      >8gv             >v      >6gv                                   >8gv      >8gv        >7gv      >7gv                                                            >8gv >v      >7gv
>005p015p025p25g1+25p&25g8p25g:0`|  >25g:0`|  >05g1+05p05g6p|>05g:0`|  >15g1+15p15g7p25g1+25p125g8p25g1-:0`|  >25g:0`|  >15g1-:0`|  >15g:0`|  >+015g7p15g:1`-:1\`+15p15g7p-025g8p25g:1`-:1\`+25p25g8p25g:0`|  >!|>15g:0`|  >.91+,015g7p15g:0`-15p@
                                 >$0^      >$0^                     >$0^                                   >$0^      >$0^        >$0^      >$0^                                                            >$0^         >$0^
                                                             ^                                                                                <
                                                            >                                                                                ^

```

Division (small inputs are recommended):

```
v                                                                          >91+gv>v      >94+gv                                                         >95+gv      >95+gv        >93+gv      >93+gv                                                                    >93+gv      >93+gv               >v      >93+gv                                                     >93+gv >v      >92+gv                  >v      >92+gv                                       >92+gv                                       >91+gv                                       >93+gv                     >91+gv                       >92+gv      >92+gv        >91+gv      >91+gv                                                                                >92+gv >v                        >91+gv      >91+gv                                     >91+gv >v                        >95+gv      >95+gv                                     >95+gv
>009p019p029p039p049p09g1+09p109g91+p29g1+29p&29g93+p39g1+39p&39g94+p09g:0`|    >|>39g:0`|    >009g91+p09g:0`-09p29g1+29p29g93+p49g1+49p149g95+p49g1-:0`|    >49g:0`|    >29g1-:0`|    >29g:0`|    >-029g93+p29g:1`-:1\`+29p29g93+p+049g95+p49g:1`-:1\`+49p49g95+p29g:0`|    >29g:0`|    >19g1+19p19g92+p|>29g:0`|    >09g1+09p109g91+p19g1+19p19g92+p29g1+29p029g93+p29g:0`|    >!|>19g:0`|    >029g93+p29g:0`-29p|>19g:0`|    >09g1+09p09g91+p019g92+p19g:0`-19p19g:0`|    >019g92+p19g:0`-19p29g1+29p29g93+p09g:0`|    >009g91+p09g:0`-09p19g1+19p19g92+p29g:0`|    >19g1+19p19g92+p09g:0`|    >19g1+19p19g92+p19g1-:0`|    >19g:0`|    >09g1-:0`|    >09g:0`|    >-009g91+p09g:1`-:1\`+09p09g91+p+019g92+p19g:1`-:1\`+19p19g92+p029g93+p29g:0`-29p19g:0`|    >!|>09g1+09p109g91+p09g1-:0`|    >09g:0`|    >+009g91+p09g:1`-:1\`+09p09g91+p09g:0`|    >!|>49g1+49p149g95+p49g1-:0`|    >49g:0`|    >-049g95+p49g:1`-:1\`+49p49g95+p49g:0`|    >.91+,049g95+p49g:0`-49p@
                                                                           >$0  ^        >$0  ^                                                         >$0  ^      >$0  ^        >$0  ^      >$0  ^                                                                    >$0  ^      >$0  ^                       >$0  ^                                                     >$0  ^         >$0  ^                          >$0  ^                                       >$0  ^                                       >$0  ^                                       >$0  ^                     >$0  ^                       >$0  ^      >$0  ^        >$0  ^      >$0  ^                                                                                >$0  ^                           >$0  ^      >$0  ^                                     >$0  ^                           >$0  ^      >$0  ^                                     >$0  ^
                                                                                ^                                                                                <
                                                                                >                                                                                ^
                                                                                ^                                                                        <
                                                                                >                                                                          ^
                                                                                ^                                                                                <
                                                                                >                                                                                ^

```

There's also a bunch of other minor optimisations that come to mind, like replacing `07p07g` with `:07p`, but I'm taking this one step at a time :)
> 10 votes

---
Tags: metagolf, stack, befunge, prelude
---


title: Print the Australian Flag!

text:
# Question
Title: Print the Australian Flag!
Here we go again! This is my last flag for now!

I originally wanted to do my national flag but I thought the stars were too hard so I posted Print the British Flag! instead, which itself was inspired by Print the American Flag!. This challenge would be better for 3 September (Australian National Flag Day) or 26 January (Australia Day) but I couldn't wait that long! The Commonwealth Star is a bit messy but I'm pleased with the rest of the design. Once again you need to view it at 90 degrees.

Produce the following design in the fewest bytes!

```
 ________________________________________________
|XXXXXXXXXXXXXXXXXXXXXXXX\  \XXXX  0000  XXXX//0/|
|XXXXXXXXXXXXXXXXXXXXXXXX0\  \XXX  0000  XXX//0/ |
|XXXXXXXXXXXXXXXXXXXXXXXX\0\  \XX  0000  XX//0/  |
|XXXXXXXXXXXXXXXXXXXXXXXX\\0\  \X  0000  X//0/  /|
|XXXXXXXXXXXXXXXXXXXXXXXXX\\0\  \  0000  //0/  /X|
|XXXXXXXXXXXXXXXXXXXXXXXXXX\\0\    0000  /0/  /XX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXX\\0\   0000  0/  /XXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXX\\0\  0000  /  /XXXX|
|XXXXXXXX|\XXXXX-/XXXXXXXXXXXX\\0  0000    /XXXXX|
|XXXXX-XX| \XX- /XXXXXXXXXXXXXX\\  0000   /XXXXXX|
|XXXXX\ -|      --XXXXXXX          0000          |
|XXXXXXX\          -XXXXX000000000000000000000000|
|XXXXXXX/          -XXXXX000000000000000000000000|
|XXXXX/ -|      --XXXXXXX          0000          |
|XXXXX-XX| /XX- \XXXXXXXXXXXXXX/   0000  \\XXXXXX|
|XXXXXXXX|/XXXXX-\XXXXXXXXXXXX/    0000  0\\XXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXX/  /  0000  \0\\XXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXX/  /0  0000   \0\\XXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXX/  /0/  0000    \0\\XX|
|XXXXXXXXXXXXXXXXXXXXXXXXX/  /0//  0000  \  \0\\X|
|XXXXXXXXXXXXXXXXXXXXXXXX/  /0//X  0000  X\  \0\\|
|XXXXXXXXXXXXXXXXXXXXXXXX  /0//XX  0000  XX\  \0\|
|XXXXXXXXXXXXXXXXXXXXXXXX /0//XXX  0000  XXX\  \0|
|XXXXXXXXXXXXXXXXXXXXXXXX/0//XXXX  0000  XXXX\  \|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXX>    >XXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXX|\/|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXX|
|XXXXX>    >XXXXXXXXXXXXXXXXXXXXXXXXXX>    >XXXXX|
|XXXXXX|/\|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXX|
|XXXXXXXXXXXXXXXXXXXXX/|XXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXX>   >XXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXX\|XXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXX>    >XXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|

```

Things to watch out for: there is a space at the end of the first line. No other trailing spaces are allowed. The dimensions are 50 x 49 (48 x 48 plus borders on three sides).The fifth star (5-pointed) in the Southern Cross is slightly smaller and a different design from the others (7-pointed). A trailing newline is allowed but not required.

My code editor has a thumbnail view of the code at the side. This is what this design looks like:

Not bad!

# Answer
# Python 2, 446 Bytes

Just decodes the Base64 and decompresses using zlib.

```
import zlib,base64
print zlib.decompress(base64.b64decode("eNrl1MFtwzAMBdCeMwUXEOgJPIcPBLqIhk8ofkq2QdFQb215iZDkgdSXZfpeLHrVY1JCJPpJtH2KSNfMG9c52WBORAUlRL7MDNJESsT6dGIiG8yNE4gjIzCdmMiJGyMQDwQGXUycSW2ncBS+GScQnZTPUhMtxPc+neAXJ0KlUqtS8Gfq5V2sxmAyvjS0TWoQXiW8PljbPuv25bp97kTkun1dWiJF7sKPEubhKLmdILrA5ETFOEqYlDCeRd++mYyYGIPBJARiXDGYhECcLrKZjJg4vy6ayQYzcXkpqXk4l6j+C6nCdY3s+ljti11Y6q9MbBJPEJ+TWTxBfKNLHE8Q32wvyZQx2bMpZ12k/jTkKMechDk+dQly/FMX+Q3ohQN5"))

```
> 2 votes

# Answer
# dash, 261 bytes

```
0000000: 7a6361743c3c27270a1f8b0801010101010203e5d3c98d04  zcat<<''................
0000018: 410844d1fb58110ea4480bda0e0e48e308bef7fad5cc4a89  A.D..X...H....H.......J.
0000030: db2c717f0944a9f43a8c5ed2bf4948e1d748fb1ac9af31db  .,q..D..:.^..IH..H....1.
0000048: 96df938d8108a186040622444b3010210cd2198810de110c  .........."DK0.!........
0000060: 44889e6020889e602088b724c36f59f6c140847892e59e0a  D..` ..` ..$.oY..@.x....
0000078: f725441908a24868a5ee59cb1f118110be0be89907dadfa4  .%D...Hh..Y.............
0000090: 884d894d17e37c735f0a440d8744d4f924ed81cb20201bd3  .M.M..|s_.D..D..$...  ..
00000a8: 7c4a844114184823360403698541309056d4621848235c10  |J.A..H#6..i.A0.V.b.H#\.
00000c0: c734045104d31044114c431045309049fe0bc9b09c919324  .4.Q...D.LC.E0.I.......$
00000d8: 9d86532cf25736463dc7f541aa9ee3fa20554f5f5f7b8be5  ..S,.W6F=..A.... UO__{..
00000f0: f0fc135b8c1a8be3297d4f03424f13424f7ff847be        ...[....)}O.BO.BO..G.

```

It should be possible to beat this score with manual compression and a terse language, but if your going to use a widely available compressor (and don't think you can get away with calling zcat a non-Turing complete programming language), dash is probably the best option.

I chose zopfli as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz.

Note that zcat will print a warning to STDERR, which is allowed by default per consensus on Meta.

### Testing

This is how I created and tested the program:

```
$ echo "zcat<<''" > flag.sh
$ git clone https://github.com/google/zopfli.git
$ make -C zopfli
$ zopfli/zopfli -c --i100000 flag.txt >> flag.gz
$ head -c 252 flag.gz | tr \\000 \\001 >> flag.sh
$ dash flag.sh 2>&- | md5sum - flag.txt
168400d97bf59ebff194a6d13495cc26  -
168400d97bf59ebff194a6d13495cc26  flag.txt

```

Head strips the last 9 bytes from the gzip file, which aren't required for successful decompression.

Fortunately, the gzip file only contains NUL bytes in its header, which can be replaced with SOH bytes without affecting the output.
> 2 votes

# Answer
# CJam, ~~250~~ ~~246~~ 231 bytes

```
S'_48*S"0H:+-86:0@6CEM00":i~'X*a*["3|\5-/2-2| \2- /3\ -| 0--4\00-"6,_s\'Xf*0S5*ter
sE/_W%{"\/"_W%er}:R%+"X|\/|X>  "_W%+6/___"XX/|X>   >XX\|"5/C,'X6*"//0/  /"+2*f>8f<
_2>\W%2>.{R" 00 ":_@}" 0 0"[A4A24].*+s_W%+24/]{..e&fm>m<}/{N'|@'|}/

```

The linefeeds are purely cosmetic and do not contribute to the byte count.

Try it online in the CJam interpreter.

### Idea

We start by pushing the background of the flag, i.e., 48 strings of 48 **X**'s each.

Now, we generate all 7 foreground images, i.e., the different types of stars and the miniature British flag.

```
"3|\5-/2-2| \2- /3\ -| 0--4\00-"

```

encodes the big star. After replacing each positive number with that many **X**'s, each **0** with a string of 5 spaces and splitting the result into chunks of length 14, we obtain the following:

```
XXX|\XXXXX-/XX
-XX| \XX- /XXX
\ -|      --XX
XX\          -

```

If we repeat these strings, in reversed order, and swap the slashes, we obtain the desired big star:

```
XXX|\XXXXX-/XX
-XX| \XX- /XXX
\ -|      --XX
XX\          -
XX/          -
/ -|      --XX
-XX| /XX- \XXX
XXX|/XXXXX-\XX

```

For the middle star, we simply push the string `"X|\/|X> "`, concatenate it with a reversed copy of itself and chop the result into strings of length 6:

```
X|\/|X
>    >
X|/\|X

```

Now, we push the small star as `"XX/|X> >XX\|"` chopped into strings of length 5:

```
XX/|X
>   >
XX\|

```

(The missing **X** doesn't matter since the background already contains it.)

Finally, we push the small flag, using almost exactly the same approach as in Print the British Flag!

Now that we have all parts, we start to assemble them. By using twofold vectorized logical AND on the background and the big star, we can replace each truthy character of the background (and all are truthy) by the corresponding character of the big star.

We now rotate the array of strings, and the strings themselves as well, so that the first middle star should be in the upper left corner, then repeat the process from the last paragraph to incorporate this star.

In the same fashion, we paint the remaining stars and the small flag over the background.

After assembling all parts, we only have to add the vertical bars, linefeeds and underscores.

### Code

```
S'_48*S  e# Push a space, a string of 48 underscores and another space.

"0H:+-86:0@6CEM00"

:i~      e# Cast each char to int and dump.
         e# This pushes 48 72 58 43 45 56 54 58 48 64 54 67 69 77 48 48.
         e# All but the last two integers are rotation amounts.
'X*      e# Push a string of 48 X's.
a*       e# Wrap 48 copies of that string in an array.
[        e#

  "3|\5-/2-2| \2- /3\ -| 0--4\00-"

  6,_s   e#   Push [0 1 2 3 4 5] and "012345".
  \'Xf*  e#   Replace the array with ["" "X" "XX" ... "XXXXX"].
  0S5*t  e#   Replace "" with "     ".
  er     e#   Perform transliteration.
  sE/    e#   Flatten and chop into chunks of length 14.
  _W%    e#   Copy and reverse the order of the chunks.
  {      e#   Define a function:
    "\/" e#     Push that string.
    _W%  e#     Push a reversed copy.
    er   e#     Perform transliteration.
  }:R%   e#   Save in R and map over the second array of chunks.
  +      e#   Concatenate.

  "X|\/|X>  "

  _W%    e#   Push a reversed copy.
  +6/    e#   Concatenate and chop into chunks of length 6.
  ___    e#   Copy the resulting array three more times.

  "XX/|X>   >XX\|"

  5/     e#   Split into chunks of length 5.

  C,'X6*"//0/  /"+2*f>8f<_2>\W%2>.{R" 00 ":_@}" 0 0"[A4A24].*+s_W%+24/

         e#   https://codegolf.stackexchange.com/a/52662
]

{        e# For each array of strings in the preceding array of arrays:
  ..e&   e#   Perform twofold vectorized logical AND.
  fm>    e#   Pop an integer from the stack and rotate each string that many
         e#   units to the right.
  m<     e#   Pop an integer from the stack and rotate the array of strings
         e#   that many units to the left/strings up.
}/       e#

{        e# For each string in the resulting array:
  N'|    e#   Push a linefeed and a vertical bar.
  @      e#   Rotate the string on top of them.
  '|     e#   Push an additional vertical bar.
}/       e#

```
> 2 votes

# Answer
# Python 2 - 1258 bytes

```
import zlib
v=len
l=zlib.decompress("x\x9c\x95\x94I\x12\x83 \x10E\xaf\xc2\x05,F\xd1l<\x87\x0b\xaar\x11\x0f\x1f\t44\x9fv\xe1\"\xd5\x08y\xbfG\x08\xbb\xfaZ\xa5\xd4\xfd\xbb\\P\xe7m\x93+\xdf)(u\xe6\xf5mM\xb5\xf9[\xdfg\xc6\x16{1\xcep\xd6\x03\xebgV\x01\x9fP\xc3\x81\x86\x03\r\x07\x1aN\xd0\xb0\xa0ae\x8d\x9e\xcb*\xeb@\x1c\x12\x7f6\x8d8j\x84\xd1\xff\xc4:\xcen#\xebGv\xe0<\xe7\xf69n\xee\x93l`\xcc\xde\xd7i-\xeb\xe5\x1f\x9f\xebZ\xa4\x13*\xbf2\x9e\x18\x16\x7f\xeb[\xd5*\xf9\xd6\xde\x90\x96\xaf\xfbq\xd6J\x95\xc9\xec\x15K\xad\x97-\x9f\x99\xc2fK\xccFL\xd9[\xb2\xc6=\x07\x06\xce\xf5\xd3\xf9J\xe7/|>\xe4\xac!\xe7d\xcbLk?\xceM\x8ar\xfd5\xab\x7f\xca\xf5\xaf\xbd\x1az\xefz\x9fZ\xcfa\x8e\xf8\xff\xa9\x7f)\xc0|\xc1\xdc\x1a\xe8K\xe3<\xcc4r\xdcg\x00v\x98\xe9U\xf49\xc5\x8bq\x0fw*\xc8\x1a\xd2\xfd~\xd0\xe2\xef\x04\xc61\xbd3\xa8aA\xc3\x82\x86\xf4\xde\t\x1aC.\xc4J\xef,\xb0\x7f.\xec\xbd\x1eo\xd7\xb5\x07W\xd5+\xef\xddg\xaa\xefQ\xfbxX\x99\xd5-\x9e\xcf;\xffl\xee\x9b\x7f\xb7\xcf{\xc2\x9b\xd0b\xaa3\xd8\xbe\xf9]`\\\x8b\x91\xe9\xb7=\xae\xefl\xeb\x03\xcf\x91r;<\xf9\r\x13\x93\x90\x91r\xb1q\xbaw\xbd\xbe2\xdb\xeb\x1b\xdf\xd5\x97\xd6?\xd9\xaczF")
n=''.join([i[-1]*int(i[:v(i)-1].replace(' ',''))for i in[l[i:i+4]for i in range(0,v(l),4)]])
print''.join(n[i]if(i+2)%50 else n[i]+'\n'for i in range(v(n)))

```

I decided to encode the flag using run length encoding, then compressed it using zlib. In the program, it just decodes all of this and prints it to the console.
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Print the American Flag!

text:
# Question
Title: Print the American Flag!
Special Independence Day (USA) themed challenge for you today. You must write a program that prints this ascii-art representation of The American Flag.

```
0
|---------------------------------------------------------
| *   *   *   *   *   * #################################|
|   *   *   *   *   *                                    |
| *   *   *   *   *   *                                  |
|   *   *   *   *   *   #################################|
| *   *   *   *   *   *                                  |
|   *   *   *   *   *                                    |
| *   *   *   *   *   * #################################|
|   *   *   *   *   *                                    |
| *   *   *   *   *   *                                  |
|########################################################|
|                                                        |
|                                                        |
|########################################################|
|                                                        |
|                                                        |
|########################################################|
|                                                        |
|                                                        |
|########################################################|
|---------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

```

Trailing spaces on each line, as well as one trailing newline, are allowed.

Note that this isn't quite the way the flag should look, but it's the closest I could get with ASCII.

As usual, this is so standard loopholes apply and shortest answer in bytes wins!

# Answer
# CJam, ~~184~~ ~~120~~ ~~109~~ ~~101~~ ~~76~~ ~~74~~ ~~69~~ ~~67~~ ~~64~~ ~~62~~ 58 bytes

```
0'-57*"  #"56f*'|f+7*2>" *  "50*22/W<Sf+..e&~J$]N'|+a37*.+

```

Try it online in the CJam interpreter.

### Idea

The most interesting part of the flag is the stars and stripes pattern.

If we repeat two spaces and a number sign 56 times and append a vertical bar to each, we get

```
                                                         |
                                                         |
#########################################################|

```

Repeating this pattern 7 times and discarding the first two lines, we obtain the stripes:

```
#########################################################|
                                                         |
                                                         |
#########################################################|
                                                         |
                                                         |
#########################################################|
                                                         |
                                                         |
#########################################################|
                                                         |
                                                         |
#########################################################|
                                                         |
                                                         |
#########################################################|
                                                         |
                                                         |
#########################################################|

```

Now, if we repeat the string `" * "` 50 times and split the result into chunks of length 22, we obtain the stars:

```
 *   *   *   *   *   *
   *   *   *   *   *
 *   *   *   *   *   *
   *   *   *   *   *
 *   *   *   *   *   *
   *   *   *   *   *
 *   *   *   *   *   *
   *   *   *   *   *
 *   *   *   *   *   *

```

The whitespace is a little off, but we can fix that by eliminating the last chunk and appending a space to the remaining ones.

Now, if we superimpose stripes and stars, we get

```
 *   *   *   *   *   * #################################|
   *   *   *   *   *                                    |
 *   *   *   *   *   *                                  |
   *   *   *   *   *   #################################|
 *   *   *   *   *   *                                  |
   *   *   *   *   *                                    |
 *   *   *   *   *   * #################################|
   *   *   *   *   *                                    |
 *   *   *   *   *   *                                  |
########################################################|
                                                        |
                                                        |
########################################################|
                                                        |
                                                        |
########################################################|
                                                        |
                                                        |
########################################################|

```

All that's left to do is adding two lines of 57 dashes, adding a column of 37 vertical bars and putting the cherry on top.

### Code

```
0         e# Push a zero.
'-57*     e# Push a string of 57 dashes.
"  #"56f* e# Repeat each character in the string 56 times.
'|f+      e# Append a vertical bar to each resulting string.
7*        e# Repeat the resulting array of strings 7 times.
2>        e# Discard the first two strings.
" *  "50* e# Repeat the string 50 times.
22/       e# Split the result into chunks of length 22.
W<        e# Discard the last, partial chunk.
Sf*       e# Append a space to each chunk.
..e&      e# Twofold vectorized logical AND.
          e# Since all characters in the strings are truthy, this always selects
          e# the second character, painting the stars over the stripes.
~         e# Dump all resulting strings on the stack.
J$        e# Copy the string of dashes.

]         e# Wrap the entire stack in an array.
N'|+a37*  e# Repeat ["\n|"] 37 times.
.+        e# Perform vectorized concatenation.

```
> 21 votes

# Answer
# Python 2, 113 bytes

```
for i in range(38):print i and"|"+["-"*57,(" *  "*7)[i%2*2:][:(i<11)*23].ljust(56,"  #"[i%3])+"|"][1<i<21]*(i<22)

```

String slicing and modulo checks galore.
> 27 votes

# Answer
# Brainf\**k, 3355 3113 1598 1178 782 bytes

What is this language?

Here is the hand optimized version featuring 28 loops. I think I've taken this about as far as it will go.

Here's the run at ideone.com:

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

```

---

## How does this work?

```
 1: +++[>++++<-]>[>+++>+++>+++>++++++++++>+>++++<<<<<<-]>++++++>---->->>>.<--.
 2: <++++.>>---.>+++++++[<........>-]<<.
 3: <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>.
 4: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>.
 5: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>.
 6: <.<<...<<+++++[>.>...<<-]++++[>>>........<<<-]>>>.>.>.
 7: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>.
 8: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>.
 9: <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>.
10: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>.
11: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>.
12: >>>+++[<<<
13: <.>>>+++++++[<<<<........>>>>-]<<<.>.
14: >>++[<<
15: <.<<<<+++++++[>>........<<-]>>>>.>.
16: >>-]<<
17: >>>-]<<<
18: <.>>>+++++++[<<<<........>>>>-]<<<.>.
19: <.>>.>+++++++[<........>-]<<.
20: >>++++++++[<<<.>.<.>.>>-]

```

This program uses 10 memory locations:

```
0: loop counter #1
1: loop counter #2
2: "*"  ASCII 42
3: spc  ASCII 32
4: "#"  ASCII 35
5: "|"  ASCII 124
6: "\n" ASCII 10
7: "0"  ASCII 48, "-"  ASCII 45
8: loop counter #3
9: loop counter #4

```

### Line 1

* This line sets up the ASCII characters in registers 2 through 7 (mostly). Some tweaking is done later.
* This code first puts 3 in register 0, and then loops 3 times incrementing register 1 four times each loop: `+++[>++++<-]`. Then end result is that register 0 is 0, and register 1 is 12.
* The 12 is used as the loop counter for the next loop. For 12 times through the loop, registers 2, 3, and 4 are incremented 3 times, register 5 is incremented 10 times, register 6 is incremented 1 time, and register 7 is incremented 4 times. At the end of this loop, they contain: R2(36), R3(36), R4(36), R5(120), R6(12), R7(48). After the loop register 2 is incremented 6 times, register 3 is decremented 4 times, and register 4 is decremented once. At this point, the values are: R2(42), R3(32), R4(35), R5(120), R6(12), R7(48). All but registers 5 and 6 contain their initial ASCII values.
* Next register 7 is output, the `"0"` at the top of the flag!
* Next register 6 is decremented twice to 10 (ASCII newline) and output. Done with the first line of the flag!

### Line 2

* First it increments register 5 by 4 which makes it `"|"` (ASCII 124) and outputs it.
* Then it decrements register 7 by three changing it from `"0"` (ASCII 48) into `"-"` (ASCII 45) and outputs it.
* Next it puts 7 into loop counter 3 (register 8) and loops 7 times, writing out 8 dashes each time for a total of 7\*8 = 56 dashes.
* Finally it ends by outputting a newline.

### Line 3

* This line contains two loops.
* The first loop writes `" * "` 5 times.
* Then `" * "` is written
* The second loop loops 4 times writing 8 `"#"` for a total of 32.
* Then `"#"`, `"|"`, and `"\n"` are written.

### Lines 4 - 11

* These lines use the same technique as line 3 to write out the stars and stripes of the flag.

### Line 12

* This line starts a loop that runs 3 times.
* The loop ends at line 17.

### Line 13

* Writes a strip that goes across the flag.
* Uses a loop that runs 7 times writing `"#"` 8 times each time through the loop.

### Line 14

* The start of a loop that runs 2 times.

### Line 15

* Writes a strip that goes across the flag.
* Uses a loop that runs 7 times writing `" "` 8 times each time through the loop.

### Line 16

* End of inner loop that started at line 14.

### Line 17

* End of outer loop that started at line 13.

### Line 18

* Draws bottom stripe of flag.

### Line 19

* Draws bottom border of flag.

### Line 20

* Draws the flagpole.
* Loops 8 times, writing `"|"` and newline twice each time through the loop.
> 9 votes

# Answer
# JavaScript (*ES6*), 153 ~~156~~

Using template string, there is 1 newline that is significant and counted

Test running the snippet below (being EcmaScript 6, Firefox only)

```
// TEST - Just for testing purpose,redefine console.log

console.log = (...x) => O.innerHTML += x+'\n'

// SOLUTION

o=[0];for(o[r=1]=o[21]='-'[R='repeat'](57);++r<21;o[r]=" *  "[R](7).substr(r%2*2,r<11&&23)+'  #'[r%3][R](r<11?33:56)+'|')o[37]='';console.log(o.join`
|`)
```

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

To be even more patriotic, here is the EcmaScript 5 version

```
// TEST - Just for testing purpose,redfine console.log

console.log = function(x){ O.innerHTML += x+'\n' }

// SOLUTION - 175 bytes

for(o=(A=Array)(38),o[0]=0,r=2;r<21;r++)o[r]=A(8)[J='join'](" *  ").substr((r&1)*2,r<11?23:0)+A(r<11?34:57)[J]('  #'[r%3])+'|';
o[1]=o[r]=A(58)[J]('-'),console.log(o[J]('\n|'))
```

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

# Answer
# ///: 225 characters

```
/D/ddd//d/--------//H/hhh//h/########//S/sss//s/        //A/aaaaa//a/ *  //b/|HHh|
|SSs|
|SSs|
//p/|
|
|
|
/0
|DDd-
|A * Hh#|
|  A Ss |
|A * Ss |
|  A Hh#|
|A * Ss |
|  A Ss |
|A * Hh#|
|  A Ss |
|A * Ss |
bbb|HHh|
|DDd-
pppp

```
> 7 votes

# Answer
# Ruby, ~~104~~ 102 bytes

Using ideas from ManAtWork's Ruby answer with permission.

```
puts 0,s=?|+?-*57,(0..18).map{|i|?|+("#  "[i%3]*(i>8?56:33)).rjust(56," *   *"[i%2*2,4])+?|},s,'|
'*16

```

# Ruby, ~~127 121~~ 112 bytes

Changed quotes to `?` used array instead of conditional for stripe colour. used conditional instead of formula for stripe length.

```
puts 0,s=?|+?-*57
19.times{|i|puts ?|+("#  "[i%3]*(i>8?56:33)).rjust(56,i%2>0?"   *":" *  ")+?|}
puts s,"|\n"*16

```

The trick here is to draw the stripes (both red/`#` and white/`space`) to the correct length, then right justify them, padding with stars. Ruby's `rjust` allows us to specify the padding string, which alternates between `" * "` and `" *"`.

**Original version, 127 bytes**

```
puts 0,s="|"+"-"*57
19.times{|i|puts("|"+((i%3>0?" ":"#")*((i+1)/10*23+33)).rjust(56,i%2>0?"   *":" *  ")+"|")}
puts s,"|\n"*16

```
> 6 votes

# Answer
# SWI-Prolog, 275 bytes

In a language of French origin, which is *kind of* fitting

```
a:-put(48),nl,b,c(0).
b:-z,w(-,57).
c(I):-nl,I=36;J is I+1,(I=19,b,c(J);I>19,z,c(J);I>8,z,(I mod 3=:=0,w(#,56);tab(56)),z,c(J);z,(I mod 2=:=0,tab(1),w('*   ',5),put(42),tab(1);w('   *',5),tab(3)),(0=:=I mod 3,w(#,33);tab(33)),z,c(J)).
z:-put(124).
w(A,B):-writef('%r',[A,B]).

```

See the result here
> 3 votes

# Answer
# C, 235 211 208 205 203 198 197 186 bytes

```
i;x(){for(puts("0");i<37;i++){char b[58]="";i<21?memset(b,i%20?i%3&1?35:32:45,56),i&&i<10?memcpy(b," *   *   *   *   *   *   "+(i%2?0:2),23):0,b[56]=i%20?124:45:0;printf("|%.57s\n",b);}}

```

edit: added some of Cool Guy's suggestions and made use of ?: to replace some if statements.

edit: removed overflow \0 prevention and used string length limiter in printf instead.

edit: reworked both memset conditionals.

edit: moved puts("0") inside the for header to remove its semicolon.

edit: slight refactoring to get 11 more bytes.
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


# Question
Title: Which Friends characters were really the best friends?
The six main cast members of the American sitcom *Friends* all agreed that they would be paid the same salary throughout the run of the series (after season 2, at least). But that doesn't mean that they all had the same amount of air time or that they all interacted on screen with each other the same amount.

In this challenge, you'll write a program that could help determine which *Friends* friends were *really* the best.

# Setup

Consider watching an episode or scene of *Friends* and noting down exactly who is on screen during each camera shot and for how long.

We'll abbreviate each character's name:

Then for every camera shot (or every time a character enters/exits the shot), we'll list who was on screen. For example:

```
504 CRS
200 J
345 MP
980
2000 CJMPRS

```

This is saying that:

* For 504ms, Chandler, Rachel, and Ross were on screen.
* Then for 200ms, Joey was.
* Then for 345ms, Monica and Phoebe were.
* Then for 980ms, none of the 6 main characters were on screen.
* Then for 2 seconds, all of them were.

(This is not from an actual clip, I made it up.)

Note that the following would be equivalent:

```
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS

```

To analyze which combinations of characters had the most screen time, we look at all 64 possible subsets of the 6 characters and total up the screen time they had. If everyone in a subset appears on screen during a camera shot, **even if there are more characters than just the ones in the subset**, the time for that camera shot is added to that subset's total screen time.

There's an exception for the empty subset - only the scenes with none of the 6 main characters are counted.

So the analysis of the example above would be:

```
980
2504 C
2200 J
2345 M
2345 P
2504 R
2504 S
2000 CJ
2000 CM
2000 CP
2504 CR
2504 CS
2000 JM
2000 JP
2000 JR
2000 JS
2345 MP
2000 MR
2000 MS
2000 PR
2000 PS
2504 RS
2000 CJM
2000 CJP
2000 CJR
2000 CJS
2000 CMP
2000 CMR
2000 CMS
2000 CPR
2000 CPS
2504 CRS
2000 JMP
2000 JMR
2000 JMS
2000 JPR
2000 JPS
2000 JRS
2000 MPR
2000 MPS
2000 MRS
2000 PRS
2000 CJMP
2000 CJMR
2000 CJMS
2000 CJPR
2000 CJPS
2000 CJRS
2000 CMPR
2000 CMPS
2000 CMRS
2000 CPRS
2000 JMPR
2000 JMPS
2000 JMRS
2000 JPRS
2000 MPRS
2000 CJMPR
2000 CJMPS
2000 CJMRS
2000 CJPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS

```

We can see that `J` (just Joey) had 2200ms of screen time because he had 200 by himself and 2000 with everyone.

# Challenge

Write a program that takes in a string or text file such as

```
504 CRS
200 J
345 MP
980
2000 CJMPRS

```

where each line has the form `[time in ms] [characters on screen]`, and outputs the total amount of time that each of the 64 subsets of the 6 characters spent on the screen, where each line has the form `[total time in ms for subset] [characters in subset]` (just as above).

The input can be taken as a string to stdin, the command line, or a function, or it can be the name of a text file that contains the data.

* The milliseconds numbers will always be positive integers.
* The character letters will always be in the order `CJMPRS` (alphabetical).
* You can optionally assume there is a trailing space when there are no characters in the scene (e.g. `980` ).
* You can optionally assume there is a trailing newline.
* The input will have at least 1 line and may have arbitrarily many.

The output should be printed or returned or written to another text file as a 64 line string.

* The lines may be in any order.
* The character letters do not need to be in the `CJMPRS` order.
* Subsets with 0ms total time **do** need to be listed.
* There may optionally be a trailing space after the empty subset total.
* There may optionally be a trailing newline.

(This problem can of course be generalized to more characters, but we'll stick with the 6 `CJMPRS` *Friends* characters.)

**The shortest code in bytes wins.**

*Note that I actually enjoy Friends and don't think some characters are more important than the others. The statistics would be interesting though.* ;)

# Answer
# Pyth, 37 bytes

```
Vy"CJMPRS"++smvhdf?q@eTNNN!eTcR\ .zdN

```

Try it online: Demonstration

### Explanation:

```
  "CJMPRS"                             string with all friends
 y                                     create all subsets
V                                      for loop, N iterates over ^:
                                 .z      all input lines
                             cR\         split each line at spaces
                 f                       filter for lines T, which satisfy:
                  ?      N                 if N != "":
                   q@eTNN                    intersection(T[1],N) == N
                                           else:
                          !eT                T[1] == ""
             m                           map each of the remaining d to:
              vhd                          eval(d[0]) (extract times)
            s                            sum
           +                       d     + " "
          +                         N    + N
                                         implicitly print

```
> 10 votes

# Answer
## Haskell, 187 bytes

```
f=g.(>>=(q.words)).lines
g t=p"CJMPRS">>=(\k->show(sum.map snd$filter((==k).fst)t)++' ':k++"\n")
q[n]=[("",read n)]
q[n,s]=[(k,read n)|k<-tail$p s]
p s=map concat$sequence[[[],[c]]|c<-s]

```

`f` is a function that takes the input, as a single multi-line string, and returns the multi-line output as single string. Probably plenty left to golf here.

```
λ: putStr test1
504 CRS
1 J
199 J
345 MP
980
2000 CJMPRS

λ: putStr $ f test1
980
2504 S
2504 R
2504 RS
2345 P
2000 PS
2000 PR
2000 PRS
2345 M
2000 MS
2000 MR
2000 MRS
2345 MP
2000 MPS
2000 MPR
2000 MPRS
2200 J
2000 JS
2000 JR
2000 JRS
2000 JP
2000 JPS
2000 JPR
2000 JPRS
2000 JM
2000 JMS
2000 JMR
2000 JMRS
2000 JMP
2000 JMPS
2000 JMPR
2000 JMPRS
2504 C
2504 CS
2504 CR
2504 CRS
2000 CP
2000 CPS
2000 CPR
2000 CPRS
2000 CM
2000 CMS
2000 CMR
2000 CMRS
2000 CMP
2000 CMPS
2000 CMPR
2000 CMPRS
2000 CJ
2000 CJS
2000 CJR
2000 CJRS
2000 CJP
2000 CJPS
2000 CJPR
2000 CJPRS
2000 CJM
2000 CJMS
2000 CJMR
2000 CJMRS
2000 CJMP
2000 CJMPS
2000 CJMPR
2000 CJMPRS

```
> 13 votes

# Answer
# SWI-Prolog, 381 bytes

```
s([E|T],[F|N]):-E=F,(N=[];s(T,N));s(T,[F|N]).
a(A):-split_string(A," \n","",B),w(B,[],C),setof(L,s(`CJMPRS`,L),M),x(C,[` `|M]).
w([A,B|T],R,Z):-number_string(N,A),(B="",C=` `;string_codes(B,C)),X=[[N,C]|R],(T=[],Z=X;w(T,X,Z)).
x(A,[M|T]):-y(M,A,0,R),atom_codes(S,M),writef("%t %w\n",[R,S]),(T=[];x(A,T)).
y(_,[],R,R).
y(M,[[A,B]|T],R,Z):-subset(M,B),S is R+A,y(M,T,S,Z);y(M,T,R,Z).

```

This expects to be run as:

```
a("504 CRS
200 J
345 MP
980
2000 CJMPRS").

```

Note that you might need to replace every ``` to `"` and every `"` to `'` if you have an old version of SWI-Prolog.

I could shave off 100+ bytes if I didn't have to use a String as an input.
> 7 votes

# Answer
# Haskell, ~~150~~ 136 bytes

```
import Data.List
f=(subsequences"CJMPRS">>=).g
g l c=show(sum[read x|(x,y)<-map(span(/=' '))$lines l,c\\y==[],c/=[]||c==y])++' ':c++"\n"

```

Usage example:

```
*Main> putStr $ f "504 CRS\n1 J\n199 J\n345 MP\n980\n2000 CJMPRS"
980
2504 C
2200 J
2000 CJ
2345 M
2000 CM
2000 JM
2000 CJM
2345 P
2000 CP
2000 JP
2000 CJP
2345 MP
2000 CMP
2000 JMP
2000 CJMP
2504 R
2504 CR
2000 JR
2000 CJR
2000 MR
2000 CMR
2000 JMR
2000 CJMR
2000 PR
2000 CPR
2000 JPR
2000 CJPR
2000 MPR
2000 CMPR
2000 JMPR
2000 CJMPR
2504 S
2504 CS
2000 JS
2000 CJS
2000 MS
2000 CMS
2000 JMS
2000 CJMS
2000 PS
2000 CPS
2000 JPS
2000 CJPS
2000 MPS
2000 CMPS
2000 JMPS
2000 CJMPS
2504 RS
2504 CRS
2000 JRS
2000 CJRS
2000 MRS
2000 CMRS
2000 JMRS
2000 CJMRS
2000 PRS
2000 CPRS
2000 JPRS
2000 CJPRS
2000 MPRS
2000 CMPRS
2000 JMPRS
2000 CJMPRS

```

Different approach than @MtnViewMark's answer: For all combinations `c` of the characters find the lines of the input string where the difference of `c` and the list from the lines `y` is empty (take care of the special case where no character is on screen (e.g. `980`) -\> `c` must be not empty or `c == y`). Extract the number and sum.
> 7 votes

# Answer
# CJam, ~~67~~ 58 bytes

```
"CJMPRS"6m*_.&:$_&qN/_{_el=},:~1bpf{{1$\-!},Sf/0f=:i1bS\N}

```

Try it online in the CJam interpreter.
> 6 votes

# Answer
# Perl 5 (5.10+), 128 bytes

2 bytes per line of output. `use feature "say"` not included in the byte count.

```
@_=<>;for$i(0..63){@c=qw(C J M P R S)[grep$i&(1<<$_),0..5];
$r=@c?join".*","",@c:'$';$t=0;for(@_){$t+=$1 if/(.*) $r/}say"$t ",@c}

```

Un-golfed:

```
# Read the input into an array of lines.
my @lines = <>;
# For every 6-bit number:
for my $i (0 .. 63) {
    # Select the elements of the list that correspond to 1-bits in $i
    my @indices = grep { $i & (1 << $_) } 0 .. 5;
    my @characters = ('C', 'J', 'M', 'P', 'R', 'S')[@indices];

    # Build a regex that matches a string that contains all of @characters
    # in order... unless @characters is empty, then build a regex that matches
    # end-of-line.
    my $regex = @characters
      ? join ".*", ("", @c)
      : '$';

    my $time = 0;
    # For each line in the input...
    for my $line (@lines) {
        # If it contains the requisite characters...
        if ($line =~ /(.*) $regex/) {
            # Add to the time total
            $time += $1;
        }
    }

    # And print the subset and the total time.
    say "$time ", @characters;
}

```
> 2 votes

# Answer
# K, 95

```
{(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}

```

Takes a string like `"504 CRS\n200 J\n345 MP\n980 \n2000 CJMPRS"`

```
k){(+/'{x[1]@&min'y in/:*x}[|"I \n"0:x]'b)!b:" ",?,/{x{,/y{x,/:y@&y>max x}\:x}[d]/d:"CJMPRS"}["504 CRS\n200 J\n345 MP\n980  \n2000 CJMPRS"]
980 | " "
2504| "C"
2200| "J"
2345| "M"
2345| "P"
2504| "R"
2504| "S"
2000| "CJ"
2000| "CM"
2000| "CP"
2504| "CR"
2504| "CS"
2000| "JM"
2000| "JP"
2000| "JR"
2000| "JS"
2345| "MP"
2000| "MR"
2000| "MS"
2000| "PR"
2000| "PS"
2504| "RS"
2000| "CJM"
2000| "CJP"
2000| "CJR"
2000| "CJS"
2000| "CMP"
2000| "CMR"
2000| "CMS"
2000| "CPR"
2000| "CPS"
2504| "CRS"
2000| "JMP"
2000| "JMR"
2000| "JMS"
2000| "JPR"
2000| "JPS"
2000| "JRS"
2000| "MPR"
2000| "MPS"
2000| "MRS"
2000| "PRS"
2000| "CJMP"
2000| "CJMR"
2000| "CJMS"
2000| "CJPR"
2000| "CJPS"
2000| "CJRS"
2000| "CMPR"
2000| "CMPS"
2000| "CMRS"
2000| "CPRS"
2000| "JMPR"
2000| "JMPS"
2000| "JMRS"
2000| "JPRS"
2000| "MPRS"
2000| "CJMPR"
2000| "CJMPS"
2000| "CJMRS"
2000| "CJPRS"
2000| "CMPRS"
2000| "JMPRS"
2000| "CJMPRS"

```
> 2 votes

---
Tags: code-golf, arithmetic, combinatorics
---


# Question
Title: Format a floating point number exactly as decimal
Any binary floating point can be formatted exactly in decimal. The resulting string might be somewhat long, but it is possible. In my article on floating point I cover the importance of precision, and now I want this function. This challenge is to write a program, or function, that takes a floating point value as input and formats an exact decimal string as output.

To ensure we are working with the correct floating point numbers a precise format must be provided as input to the program. This format will be two integers `Significand Exponent`, where the actual floating point value is `Significand * 2 ^ Exponent`. Note that either value can be negative.

Specifics:

* The range and precision of at least a 32-bit float must be supported (no input will go beyond that)
* The decimal formatted value must be an exact representation (simply close enough to guarantee a correct round-tip back to float is not good enough)
* We don't trust standard library floating point formatting functions to be correct enough nor fast enough (ex: `printf`), and thus they may not be used. *You* must do the formatting. Integral formatting/conversion functions are allowed.
* There may not be any leading or trailing zeros, except for the required one leading zero in front of the `.` if there is no whole number component
* A function, or whole program, is allowed.

Examples:

```
1 -2 => 0.25
17 -3 => 2.125
-123 11 => -251904
17 50 => 19140298416324608
23 -13 => 0.0028076171875
3 120 => 3987683987354747618711421180841033728
3 -50 => 0.00000000000000266453525910037569701671600341796875
-3 -50 => -0.00000000000000266453525910037569701671600341796875
10 -2 => 2.5
-12345 -3 => -1543.125
0 0 => 0
161 -4 => 10.0625
512 -3 => 64

```

Shortest code wins.

# Answer
# CJam, 43

```
r_'-&\ize999rim<s1e3'0e[W%999/(i_L?\+'.*sW%

```

Try it online

**Explanation:**

The program works with exponents up to ±999, close to double precision (64 bit). It separates the minus sign (if present) from the significand, multiplies it by 10999 then does a bit shift with the exponent, which is now an exact calculation. It then pads to the left with zeros if the result has less than 1000 digits, separates the last 999 digits as the fractional part, removes trailing zeros by converting its reverse to integer, adds a decimal point if needed, and puts everything back together.

```
r_         read and duplicate the significand in string form
'-&        keep only the minus sign, if present
\          swap with the other copy of the significand
iz         convert to integer and get absolute value
e999       multiply by 10^999
ri         read the exponent and convert to integer
m<         shift left by it; negative values will shift right
            the result is an exact non-negative integer
s          convert to string
1e3'0e[    pad to the left with zero characters up to length 1000
            longer strings will be left intact
            we need 1 more than 999 for the 0.xxx case
W%         reverse the string
999/       split into slices of length 999
(          take out the first slice (reversed fractional part)
i          convert to integer
            this removes the leading zeros (trailing in reverse)
_L?        if it's zero, replace with an empty string
\+         concatenate back (to the left) with the second slice
'.*        join the with the dot character
            if the fractional part was zero, we only have the second slice
            (reversed integer part) and there is nothing to join
s          convert to string; this is the reversed result without the sign
W%         reverse back

```

At the end, the minus sign (if any) and the final string are automatically printed together.
> 3 votes

# Answer
# CJam, 50 bytes

```
q~A1$z#\_0>K5?\z:E#@_s'-&oz*\md_sE'0e[W%isW%'.\+Q?

```

This is a full program that reads from STDIN. Try it online in the CJam interpreter.

Verify all test cases at once.
> 2 votes

# Answer
# GNU sed + dc, 65

Score includes +1 for sed's `-r` option.

```
y/-/_/
s/.*/dc -e"C8k& 2r^*p"/e
s/\\\n//
s/0+$//
s/^(-?)\./\10./

```

I was tempted to claim this `dc`-only answer `C8k& 2r^*p` for a score of 10, but `dc` has some formatting quirks:

* the -ve sign is `_` instead of `-`
* long lines are broken with backslashes
* trailing zeros must be removed
* leading 0 for `|n| < 1` must be added

So the dc expression is wrapped and evaled by `sed` to take care of the above.

### Test output:

```
$ echo "1 -2
17 -3
-123 11
17 50
23 -13
3 120
3 -50
-3 -50
8388608 127
1 -127" | sed -rf float.sed
0.25
2.125
-251904
19140298416324608
0.0028076171875
3987683987354747618711421180841033728
0.00000000000000266453525910037569701671600341796875
-0.00000000000000266453525910037569701671600341796875
1427247692705959881058285969449495136382746624
0.0000000000000000000000000000000000000058774717541114375398436826861112283890933277838604376075437585313920862972736358642578125
$

```
> 2 votes

---
Tags: code-golf, floating-point
---


# Question
Title: Javascript function challenge add(1,2) and add(1)(2) both should return 3
A friend of mine challenged me to write a function that works with both of these scenarios

```
add(1,2)  // 3
add(1)(2) // 3

```

My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction. This failed.

```
function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

```

So I started reading up on functions that return other functions or return themselves.

http://davidwalsh.name/javascript-functions https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for

I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!

# Answer
> 6 votes
# JavaScript (as asked)

This is a "correct" way to do it but hardly the golfiest way. It's unclear if you're asking for shortest code (the question looks like it will be closed soon anyway.)

```
function add(a, b) {
    if(typeof b === "undefined")
        return function(c) { return a + c }
    return a + b
}

```

# Answer
> 3 votes
# JavaScript ES6, 23 bytes

```
add=(a,b)=>b==+b?a+b:c=>a+c

```

If you are willing to use ES6, you can use fat-arrow functions and conditionals to write the function.

# JavaScript, 55 bytes

```
function add(a,b){return b==+b?a+b:function(c){return a+c}}

```

Here's the same function in regular (current version of) JavaScript.

`b?` will check if b is a non-falsey value

`a+b` if it is, return the sum of a and b

`:c=>a+c` if it's not, return a function with a single argument c which returns the sum of c and a

---
Tags: code-golf, code-challenge, javascript, function
---


title: Balancing Words

text:
# Question
Title: Balancing Words
This challenge was posted on the DailyProgrammer subreddit, and I figured it would be a great candidate for a code golf challenge. Determining if a letter balances is based on its distance from the point of balance, and the letter's value. The value of a letter can be determined by either taking its one-indexed position in the alphabet, or by subtracting 64 from its ASCII value. Furthermore, the value of a letter is multiplied by its distance from the balance point. Let's take a look at an example, `STEAD`:

```
STEAD   -> 19, 20, 5, 1, 4 ASCII values
           This balances at T, and I'll show you why!
S T EAD -> 1*19 = 1*5 + 2*1 + 3*4
           Each set of letters on either side sums to the same value, so
           T is the anchor.

```

However, it should be noted that not all words balance. For example, the word `WRONG` does not balance in any configuration. Also, words must balance on a letter, not between two letters. For example, `SAAS` would balance if there was a letter in the middle of the two `A`s, but since there is none it does not balance.

# The Task

You should create a *program or function* that takes in an **uppercase word** as *input or function arguments*, and then produces one of two outputs:

1. If the word balances, then the word should be printed with the left side, a space, the anchor letter, another space, and the right side.

`function (STEAD) -> S T EAD`
2. If the word does not balance, you should print out the word, followed by `DOES NOT BALANCE`

`function (WRONG) -> WRONG DOES NOT BALANCE`

You may assume that all input will be uppercase and there will only be alpha characters.

# Example I/O

```
function (CONSUBSTANTIATION) -> CONSUBST A NTIATION
function (WRONGHEADED)       -> WRO N GHEADED
function (UNINTELLIGIBILITY) -> UNINTELL I GIBILITY
function (SUPERGLUE)         -> SUPERGLUE DOES NOT BALANCE

```

This is , so the shortest answer in bytes wins.

# Answer
# Pyth, 49 bytes

```
jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE

```

Demonstration.

Explanation:

```
jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE

                                    Implicit: z = input(), d = ' '
         f                Uz        Filter T over range(len(z)).
              m     z               Map the characters in z to
               -Cd64                their ASCII values - 64.
            *V                      Vectorized multiplication by
                     r_Tlz          range(-T, len(z)).
                                    This is equivalent to putting the fulcrum at T.
           s                        Sum the weights.
          !                         Logical not - filter on sum = 0.
        h                           Take the first result.
                                    This throws an error if there were no results.
       J                            Save it to J.
      ,J                    hJ      Form the list [J, J+1].
    cz                              Chop z at those indices,
                                    before and after the fulcrum.
  .x                                If no error was thrown, return the above.
                              ,z".. If an error was thrown, return [z, "DOES N..."]
jd                                  Join the result on spaces and print.

```
> 6 votes

# Answer
# Pure bash (no coreutils or other utilities), 125

Standard center of mass calculation using moments about the origin:

```
for((;i<${#1};w=36#${1:i:1}-9,m+=w,M+=w*++i)){ :;}
((M%m))&&echo $1 DOES NOT BALANCE||echo ${1:0:M/m-1} ${1:M/m-1:1} ${1:M/m}

```

### Test output:

```
$ for t in \
> STEAD \
> CONSUBSTANTIATION \
> WRONGHEADED \
> UNINTELLIGIBILITY \
> SUPERGLUE
> do ./wordbal.sh $t; done
S T EAD
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE
$

```
> 12 votes

# Answer
## Python 3, 124

```
w=input()
i=a=b=0
for c in w:n=ord(c)-64;a+=n;b+=n*i;i+=1
m=b//a
print(*[w[:m],w,w[m],"DOES NOT BALANCE",w[m+1:]][b%a>0::2])

```

This code doesn't test potential fulcrums, but rather finds the "center of mass" and checks if it's an integer. It does so by summing the total mass `a` and the position-weighted mass `b`, to find the center of mass `m=b/a`. It then prints either the string split at position `m`, or the string plus `"DOES NOT BALANCE"`, chosen by the `[_::2]` list-slicing trick.
> 10 votes

# Answer
# CJam, 57 bytes

```
l_,,_f{f-W$'@fm.*:+}0#:I){ISIW$=S++t}" DOES NOT BALANCE"?

```

This can still be golfed a bit.

Try it online here
> 8 votes

# Answer
## JavaScript (ES6), ~~211~~ ~~200~~ 160 bytes

```
f=w=>{for(j=-w.length;j++;)if(![...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}

```

---

Previous attempt, 200 bytes

Thanks to edc56 and nderscore for helping me golf this

```
f=w=>{for(j=0,r=(a,z)=>[...a][z||`reverse`]().reduce((p,v,i)=>p+(parseInt(v,36)-9)*++i,0);j++<w.length;)if(r(a=w[s=`slice`](0,j))==r(b=w[s](j+1),s))return a+` ${w[j]} `+b;return w+` DOES NOT BALANCE`}

```

### Demo

Firefox and Edge only for now, as it is ES6

```
f=w=>{for(j=1-w.length;j++;)if(!([...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0)))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}

// DEMO
console.log = function(a) {
  document.body.innerHTML += a + "<br>";
}

console.log(f('STEAD'));
console.log(f('CONSUBSTANTIATION'));
console.log(f('WRONGHEADED'));
console.log(f('UNINTELLIGIBILITY'));
console.log(f('SUPERGLUE'));
```
> 7 votes

# Answer
# C, ~~236~~ ~~198~~ ~~192~~ ~~188~~ ~~180~~ 173 bytes

```
a,i,j,k,L;f(char*s){L=strlen(s);for(;i<L;i++){for(a=j=0;j<L;j++)a+=(s[j]-64)*(i-j);if(!a)break;}for(;k<L;k++)printf(k-i?"%c":" %c ",s[k]);if(a)printf(" DOES NOT BALANCE");}

```

Expanded with main():

```
#define p printf
a,i,j,k,L;
f(char*s)
{
    L=strlen(s);
    for(;i<L;i++){
        for(a=j=0;j<L;j++)
            a+=(s[j]-64)*(i-j);
        if(!a)
            break;
    }
    for(;k<L;k++)
        printf(k-i?"%c":" %c ",s[k]);
    if(a)
        printf(" DOES NOT BALANCE");
}
// 83 bytes below
int main(int argc, char **argv)
{
    f(argv[1]);
    printf("\n");
}

```

Verification:

```
$ ./a.out CONSUBSTANTIATION
CONSUBST A NTIATION
$ ./a.out WRONGHEADED
WRO N GHEADED
$ ./a.out A
 A
$ ./a.out WRONG
WRONG DOES NOT BALANCE
$ ./a.out SUPERGLUE
SUPERGLUE DOES NOT BALANCE

```
> 6 votes

# Answer
# CJam, 50 bytes

```
r_'@f-_ee::*:+\:+md"X DOES NOT BALANCEX"@?)/()@]S*

```

Using the Java interpreter, this exits with an error to STDERR for non-balancing words.

If you try the code in the CJam interpreter, just ignore everything but the last line of output.

### Idea

My "original idea" turned out to be the same approach @xnor posted several hours before me. Nevertheless, here it goes:

Given a list of values **(v0, … vn)**, we have that **v\_t** is the anchor of the list if and only if any of the following, equivalent conditions holds:

* **tv0 \+ … + 1vt-1 == 1vt+1 \+ … tvn**
* **(0 - t)v0 \+ … + (n - t)vn == 0**
* **0v0 \+ … + nvn == t(v0 \+ … + vn)**
* **t := (0v0 \+ … + nvn)/(v0 \+ … + vn)** is an integer.

### Code

```
r     e# Read a whitespace separated token from STDIN.
_'@f- e# Push a copy and subtract '@' from each char (pushes code point - 64).
_ee   e# Push a copy of the array of values and enumerate them.
::*   e# Multiply each value by its index.
:+    e# Add all results.
\:+   e# Add the unmodified values.
md    e# Perform modular division. Pushes quotient and residue.

"X DOES NOT BALANCEX"

@     e# Rotate the quotient on top of the string.
?     e# If the residue is 0, select the quotient. Otherwise, select the string.

```

At this part, we start having a little fun with overloaded operators.

For the quotient, this happens:

```
)     e# Add 1 to the quotient.
/     e# Split the input string into chunks of that length.
(     e# Shift out the first chunk.
)     e# Pop the last character of the first chunk.
@     e# Rotate the rest of the string on top of the stack.
]S*   e# Wrap all three parts in an array and join them, separating by spaces.

```

For the string, this happens:

```
)     e# Pop out the last char: "X DOES NOT BALANCE" 'X'
/     e# Split the remainder at X's: ["" " DOES NOT BALANCE"]
(     e# Shift out the first chunk: [" DOES NOT BALANCE"] ""
)     e# Pop out the last char.

```

At this point, a runtime error happens, since `""` does not have a last char. The stack gets printed and executing is aborted immediately.
> 6 votes

# Answer
# Julia, 122 bytes

```
s->(v=[int(i)-64for i=s];m=dot(v,1:length(s))/sum(v);m==int(m)?join([s[1:m-1],s[m],s[m+1:end]]," "):s*" DOES NOT BALANCE")

```

This creates an unnamed function that accepts a string as input and returns a string. To call it, give it a name, e.g. `f=s->...`.

We treat the word like a one-dimensional system for which we need to find the center of mass. The center of mass is computed as the dot product of the masses with their locations, divided by the total mass of the system. If the computed center is an integer, it corresponds to one of the letters in the word. Otherwise the word doesn't balance.

Ungolfed + explanation:

```
function f(s)
    # Create a vector of ASCII code points -- these are the "masses"
    v = [int(i)-64 for i in s]

    # Compute the center of mass, taking the locations to be the indices
    m = dot(v, 1:length(s)) / sum(v)

    # Check whether the center corresponds to a letter's position
    if m == int(m)
        join([s[1:m-1], s[m], s[m+1:end]], " ")
    else
        m * " DOES NOT BALANCE"
    end
end

```

Examples:

```
julia> f("WRONG")
"WRONG DOES NOT BALANCE"

julia> f("STEAD")
"S T EAD"

julia> f("CONSUBSTANTIATION")
"CONSUBST A NTIATION"

```
> 5 votes

# Answer
## PHP, ~~249~~ 174 bytes

Takes one command-line argument.

```
<?for($i=-$l=strlen($w=$argv[1]);$i++;){for($k=$q=0;$l>$k;)$q+=($i+$k)*(ord($w[$k++])-64);$q?:exit(substr($w,0,-$i)." {$w[-$i]} ".substr($w,1-$i));}echo"$w DOES NOT BALANCE";

```

---

Initial attempt:

```
<?function r($a){for($i=$q=0;strlen($a)>$i;){$q+=(ord($a[$i])-64)*++$i;}return$q;}for($i=0;$i++<strlen($w=$argv[1]);)(strlen($w)<2?exit($w):(r(strrev($a=substr($w,0,$i)))==r($b=substr($w,$i+1)))?exit("$a {$w[$i++]} $b"):0);echo"$w DOES NOT BALANCE";

```
> 5 votes

# Answer
# Haskell, ~~161~~ 135 bytes

```
a#b=a*(fromEnum b-64)
v=sum.zipWith(#)[1..]
h![]=h++" DOES NOT BALANCE"
h!(x:y)|v(reverse h)==v y=h++' ':x:' ':y|1<2=(h++[x])!y
f=([]!)

```

Usage example:

```
*Main> putStr $ unlines $ map f ["CONSUBSTANTIATION","WRONGHEADED","UNINTELLIGIBILITY","SUPERGLUE"]
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE

```

How it works: `f` calls the helper function `!` which takes two parameters, the left and right part of the word at a given position. It stops if both parts have equal weight (function `v`) or calls itself recursively with the first letter of the right part moved to the left. It ends with the `DOES NOT BALANCE` message if the right part is empty.
> 4 votes

# Answer
# C, 183 134 bytes

```
h,i,a=1;c(char*s){for(;s[i++]&&a;)for(a=h=0;s[h];)a+=(s[h]-64)*(h++-i);printf(a?"%.*s DOES NOT BALANCE":"%.*s %c %s",i,s,s[--i],s+i);}

```

New Version Explained:

Like the other two entries, it makes use of constant addition on one side and subtraction on the other to hopefully reach zero which is the indication of balance. My original output is reused from the first answer, albeit slightly modified.

```
l,h,i,a,b;c(char*s){for(l=strlen(s);h++<l&&(a^b|!a);)for(i=a=b=0;i<l;i++)i==h?a=b,b=0:(b+=(s[i]-64)*abs(i-h));printf(a==b?"%.*s %c %s":"%.*s DOES NOT BALANCE",a==b?h:l,s,s[--h],s+h);}

```

Old Version Explained:

The first loop (h) is the main iterator for the length of the string. The second loop (i) accumulates (b) until h==i. Once that happens, (b) is stored in (a), reset to 0, and then continues until the end of the string is reached where (a) is compared to (b). If there's a match, the main iterator's loop is broken and the output is printed.
> 4 votes

# Answer
# Ruby 175

```
F=->s{v=->s{(0...s.size).map{|i|(i+1)*(s[i].ord-64)}.inject :+}
r="#{s} DOES NOT BALANCE"
(0...s.size).map{|i|b,a=s[0...i],s[i+1..-1]
v[b.reverse]==v[a]&&r=b+" #{s[i]} "+a}
r}

```

Test it online: http://ideone.com/G403Fv

This is a pretty straightforward Ruby implementation. Here's the readable program:

```
F=-> word {
  string_value = -> str {
    (0...str.size).map{|i|(i+1) * (str[i].ord - 64)}.inject :+
  }

  result = "#{word} DOES NOT BALANCE"

  (0...word.size).map {|i|
    prefix, suffix = word[0...i], word[i+1..-1]
    if string_value[prefix.reverse] == string_value[suffix]
      result = prefix + " #{word[i]} " + suffix
    end
  }

  result
}

```
> 3 votes

# Answer
# R, 190 bytes

As an unnamed function. I think I can get a few more, but that'll have to wait.

```
function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}

```

Ungolfed a bit with brief explanation

```
function(A){
D=colSums(  #column sums of the outer function * character values
    B<-(
       as.integer(charToRaw(A))-64)    # character values
       * outer(1:(C=nchar(A)),1:C,'-') # matrix of ranges eg -3:2, -1:4, etc
       )
if(!length(
    E<-which(B[,D==0]==0) # where the colsum = 0, get the index of the zero
    ))
    cat(A,'DOES NOT BALANCE')
else
    cat(substring(A,c(1,E,E+1),c(E-1,E,C)))  #cat the substrings
}

```

It doesn't put a newline at the end.

Test run

```
> f=
+ function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}
>
> f('CONSUBSTANTIATION')
CONSUBST A NTIATION
> f('WRONGHEADED')
WRO N GHEADED
> f('UNINTELLIGIBILITY')
UNINTELL I GIBILITY
> f('SUPERGLUE')
SUPERGLUE DOES NOT BALANCE
>

```
> 3 votes

# Answer
# C, 142 bytes

Credit to **some user** for beating me to it :)

```
i,l=1,j;g(char*v){for(;v[i]&&l;++i)for(j=l=0;v[j];++j)l+=(i-j)*(v[j]-64);printf(l?"%.*s DOES NOT BALANCE":"%.*s %c %s",l?i:--i,v,v[i],v+i+1);}

```
> 2 votes

# Answer
## Java, 240 bytes

```
String b(String s){for(int i=-1,a=s.length(),l=0,r,m;++i<a;){for(r=i;--r>=0;l+=(s.charAt(r)-64));for(m=r=0;++m+i<a;r+=(s.charAt(m+i)-64)*m);if(l==r)return s.substring(0,i)+" "+s.charAt(i)+" "+s.substring(i+1);}return s+" DOES NOT BALANCE";}

```
> 1 votes

---
Tags: code-golf
---


# Question
Title: Go south, east and north, come to the same place
There is that famous riddle:

> A bear walks 1 km south, 1 km east and 1 km north, and comes to the place it started from. What color is the bear?

This one is very old, so I'll generalize it:

> A bear walks `x` km south, `y` km east and `x` km north, and comes to the place it started from. This bear thinks that the North Pole is boring, so it never goes there. Which latitude did it start and end at?

Assume that the bear is an idealized point, and the Earth is a perfect sphere with 10000 km distance from the pole to the equator (however, you can use a more accurate model if it's easier for some reason).

Write a program or a subroutine that receives the two numbers `x` and `y`, and prints or returns the latitude.

Fine points:

* Input with at least 3 decimal places of precision should be supported
* Input is in the range (0...99999), bounds not inclusive
* If the situation is physically impossible, print an empty string or a message, or return an impossible value (like 91 or `NaN` \- or, in fact, 90 - since 90 is an impossible value)
* You should print the most northern (maximal) latitude that satisfies the conditions, except the North Pole. If the North Pole is the only solution, see above.
* Output precision should be like IEEE single precison or better (24 bits or 7 decimal digits of precision).
* If the output is printed, use decimal notation (e.g. -89.99 for a point near the South Pole) . If the output is returned, use floating-point or fixed-point notation.

Shortest code in bytes wins.

# Answer
## CJam, 62 chars

```
{4e4/:Y\9e-3*:X90-P180/:Q*mc/XY2$m](/mCQ/+_90<\@XY@m[)/mCQ/-?}

```

This is a block (subroutine) which takes `x y` on the stack and leaves the solution on the stack.

Online demo

I'm interpreting the spec to allow returning 90 as an "impossible value" if there is no other solution. If that interpretation is disallowed, I think the best fix would be

```
{4e4/:Y\9e-3*:X90-P180/:Q*mc/[XY2$m](/mCQ/+\XY@m[)/mCQ/--91]{90<}=}

```
> 5 votes

---
Tags: code-golf, math, geometry
---