# Question
Title: Words within words within words within words . . .
In this pixelated font of uppercase letters of the alphabet, all the characters are 5 units wide and 5 tall.

```
 ███  ████   ███  ████  █████ █████  ████ █   █ █████     █ █   █ █     █   █
█   █ █   █ █   █ █   █ █     █     █     █   █   █       █ █  █  █     ██ ██
█████ ████  █     █   █ ████  ████  █  ██ █████   █       █ ███   █     █ █ █
█   █ █   █ █   █ █   █ █     █     █   █ █   █   █   █   █ █  █  █     █   █
█   █ ████   ███  ████  █████ █      ████ █   █ █████  ███  █   █ █████ █   █

█   █  ███  ████   ███  ████   ████ █████ █   █ █   █ █   █ █   █ █   █ █████
██  █ █   █ █   █ █   █ █   █ █       █   █   █ █   █ █   █  █ █   █ █     █
█ █ █ █   █ ████  █   █ ████   ███    █   █   █  █ █  █ █ █   █     █     █
█  ██ █   █ █     █  ██ █  █      █   █   █   █  █ █  █ █ █  █ █    █    █
█   █  ███  █      ████ █   █ ████    █    ███    █    █ █  █   █   █   █████

```

There is also 1 unit of space between letters and between lines, as can be seen. So each letter can take up to 6×6 units of space.

Suppose that instead of using the full block character () to directly form the shapes of the letters, we wanted to use *other letters in the same font*. This involves increasing the dimensions of the text 6-fold so that letters made of full-blocks can be used as full-block replacements in the larger text.

If that didn't make sense hopefully this example will. Here is an A made of B's using the pixelated font:

```
      ████  ████  ████
      █   █ █   █ █   █
      ████  ████  ████
      █   █ █   █ █   █
      ████  ████  ████

████                    ████
█   █                   █   █
████                    ████
█   █                   █   █
████                    ████

████  ████  ████  ████  ████
█   █ █   █ █   █ █   █ █   █
████  ████  ████  ████  ████
█   █ █   █ █   █ █   █ █   █
████  ████  ████  ████  ████

████                    ████
█   █                   █   █
████                    ████
█   █                   █   █
████                    ████

████                    ████
█   █                   █   █
████                    ████
█   █                   █   █
████                    ████

```

The B's are made of full blocks and the A is made of B's. Notice that the B's still have one unit between them horizontally and vertically.

We can extend this idea by using words instead of just letters. Here is "WATER" made of "FIRE":

```
█████                   █████             ████  █████ █████             █████ ████  █████ █████ █████       ████  █████ █████ █████ ████        █████ █████ █████ ████
█                         █               █   █ █     █                   █   █   █ █     █       █         █   █ █     █       █   █   █       █     █       █   █   █
████                      █               ████  ████  ████                █   ████  ████  ████    █         ████  ████  ████    █   ████        ████  ████    █   ████
█                         █               █  █  █     █                   █   █  █  █     █       █         █  █  █     █       █   █  █        █     █       █   █  █
█                       █████             █   █ █████ █                 █████ █   █ █████ █     █████       █   █ █████ █     █████ █   █       █████ █     █████ █   █

█████                   █████       ████                    █████                   █████                   █████                               ████                    █████
█                         █         █   █                   █                       █                         █                                 █   █                   █
████                      █         ████                    ████                    ████                      █                                 ████                    ████
█                         █         █  █                    █                       █                         █                                 █  █                    █
█                       █████       █   █                   █████                   █                       █████                               █   █                   █████

█████       █████       ████        █████ █████ █████ ████  █████                   █████                   █████ ████  █████ █████             █████ ████  █████ █████
█             █         █   █       █     █       █   █   █ █                       █                         █   █   █ █     █                   █   █   █ █     █
████          █         ████        ████  ████    █   ████  ████                    ████                      █   ████  ████  ████                █   ████  ████  ████
█             █         █  █        █     █       █   █  █  █                       █                         █   █  █  █     █                   █   █  █  █     █
█           █████       █   █       █████ █     █████ █   █ █████                   █                       █████ █   █ █████ █                 █████ █   █ █████ █

█████       █████       ████        █████                   █████                   █████                   ████                                █████             █████
█             █         █   █       █                       █                         █                     █   █                               █                 █
████          █         ████        ████                    ████                      █                     ████                                ████              ████
█             █         █  █        █                       █                         █                     █  █                                █                 █
█           █████       █   █       █████                   █                       █████                   █   █                               █████             █

      █████       █████             ████                    █████                   █████                   █████ ████  █████ █████ █████       ████                    █████
      █             █               █   █                   █                       █                         █   █   █ █     █       █         █   █                   █
      ████          █               ████                    ████                    ████                      █   ████  ████  ████    █         ████                    ████
      █             █               █  █                    █                       █                         █   █  █  █     █       █         █  █                    █
      █           █████             █   █                   █████                   █                       █████ █   █ █████ █     █████       █   █                   █████

```

Notice how "FIRE" appears repeatedly on each line, and always in order, no matter how much space is between the letters. Three of the rightmost instances of "FIRE" were cut off early because of how "WATER"'s letters are shaped.

This idea can be expanded even further, by using these *words made of words* to make *words made of words made of words*, or even *words made of words made of words made of words*. There is no limit theoretically.

Another example would put this post over the 30k character limit, but you can see what is meant by "words made of words made of words" by running this nifty Stack Snippet. Just leave the parameters at their defaults and press "Go!". You should see the word "DOG" made of the word "CAT" made of the word "MOUSE".

```
alphabet = {A:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],C:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,0,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],B:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],E:[[1,1,1,1,1,0],[1,0,0,0,0,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],D:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],G:[[0,1,1,1,1,0],[1,0,0,0,0,0],[1,0,0,1,1,0],[1,0,0,0,1,0],[0,1,1,1,1,0],[0,0,0,0,0,0]],F:[[1,1,1,1,1,0],[1,0,0,0,0,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[0,0,0,0,0,0]],I:[[1,1,1,1,1,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],H:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,1,1,1,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],K:[[1,0,0,0,1,0],[1,0,0,1,0,0],[1,1,1,0,0,0],[1,0,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],J:[[0,0,0,0,1,0],[0,0,0,0,1,0],[0,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],M:[[1,0,0,0,1,0],[1,1,0,1,1,0],[1,0,1,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],L:[[1,0,0,0,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]],O:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],N:[[1,0,0,0,1,0],[1,1,0,0,1,0],[1,0,1,0,1,0],[1,0,0,1,1,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],Q:[[0,1,1,1,0,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,1,1,0],[0,1,1,1,1,0],[0,0,0,0,0,0]],P:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,0,0,0],[1,0,0,0,0,0],[0,0,0,0,0,0]],S:[[0,1,1,1,1,0],[1,0,0,0,0,0],[0,1,1,1,0,0],[0,0,0,0,1,0],[1,1,1,1,0,0],[0,0,0,0,0,0]],R:[[1,1,1,1,0,0],[1,0,0,0,1,0],[1,1,1,1,0,0],[1,0,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],U:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,1,1,0,0],[0,0,0,0,0,0]],T:[[1,1,1,1,1,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],W:[[1,0,0,0,1,0],[1,0,0,0,1,0],[1,0,1,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,0,0,0,0]],V:[[1,0,0,0,1,0],[1,0,0,0,1,0],[0,1,0,1,0,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],Y:[[1,0,0,0,1,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,1,0,0,0],[0,0,0,0,0,0]],X:[[1,0,0,0,1,0],[0,1,0,1,0,0],[0,0,1,0,0,0],[0,1,0,1,0,0],[1,0,0,0,1,0],[0,0,0,0,0,0]],Z:[[1,1,1,1,1,0],[0,0,0,1,0,0],[0,0,1,0,0,0],[0,1,0,0,0,0],[1,1,1,1,1,0],[0,0,0,0,0,0]]}

empty = ['\xA0', '.']
full = ['\u2588', 'X']
w = 6
h = 6

function makeGrid(height, width) {
    var grid = new Array(height)
    for(var y = 0; y < height; y++) {
        grid[y] = new Array(width)
    }
    return grid
}

function unfoldGrid(grid) {
    var newGrid = makeGrid(h * grid.length, w * grid[0].length)
    for (var y = 0; y < newGrid.length; y++) {
        for (var x = 0; x < newGrid[0].length; x++) {
            var yf = Math.floor(y / h), xf = Math.floor(x / w)
            if (grid[yf][xf] != 0) {
                newGrid[y][x] = grid[yf][xf][y % h][x % w]
            } else {
                newGrid[y][x] = 0
            }
        }
    }
    return newGrid
}

function makeWords(words, empty, full) {
    var grid = makeGrid(1, words[0].length)
    for (var i = 0; i < words[0].length; i++) {
        grid[0][i] = alphabet[words[0][i]]
    }
    console.log(grid.length)
        console.log(grid[0].length)
    grid = unfoldGrid(grid)

        console.log(grid.length)
        console.log(grid[0].length)
    for(var i = 1; i < words.length; i++) {
        for (var y = 0; y < grid.length; y++) {
            var offset = 0
            for (var x = 0; x < grid[0].length; x++) {
                if (grid[y][x]) {
                    grid[y][x] = alphabet[words[i][offset++ % words[i].length]]
                }
            }
        }
        grid = unfoldGrid(grid)
    }

    var output = ''

    var height = Math.pow(h, words.length) - (Math.pow(h, words.length) - 1) / (h - 1)
    var width = words[0].length * Math.pow(w, words.length) - (Math.pow(w, words.length) - 1) / (w - 1)

    for (var y = 0; y < height; y++) {
        for (var x = 0; x < width; x++) {
            output += grid[y][x] ? full : empty
        }
        if (y + 1 != height) {
            output += '\r\n'
        }
    }

    return output
}

function go() {
    plain = document.getElementById('plain').checked ? 1 : 0
    document.getElementById('canvas').value = makeWords(document.getElementById('words').value.split(' '), empty[plain], full[plain])
    resize()
}

function resize() {
    document.getElementById('canvas').style.fontSize = document.getElementById('size').value
}

function zoom(magnify) {
    canvas = document.getElementById('canvas')
    match = canvas.style.fontSize.match(/^(\d+(?:\.\d+)?)(.*)$/)
    if (match !== null) {
        number = parseFloat(match[1])
        unit = match[2]
        canvas.style.fontSize = document.getElementById('size').value = (number + (magnify ? 0.1 : -0.1)) + unit
    }
}
```

```
#canvas {
    font-family: Consolas, "Courier New", sans-serif;
    white-space: nowrap; overflow: auto;
    width: 6in;
    height: 3in;
}
```

```
<p>Words: <input type='text' id='words' value='DOG CAT MOUSE'> <button type='button' onclick='go()'>Go!</button> Plain ASCII <input type='checkbox' id='plain'></p>
<p>Font Size: <input type='text' id='size' value='0.4mm'> <button type='button' onclick='resize()'>Resize</button> <button type='button' onclick='zoom(1)'>+</button> <button type='button' onclick='zoom(0)'>-</button> (use any unit: in, cm, mm, em, pt, px)</p>
<textarea id='canvas'></textarea>
```

Typing any space separated list of words **containing only capital letters** in the textbox will produce the first word made of the second word made of the third, made of the fourth, made of ... etc.

**WARNING: Entering more than 4 or even 3 words will produce A LOT of text and take a LONG time. It may crash your browser/computer/car.**

# Challenge

The goal of this challenge is to mirror what the Stack Snippet does in the fewest number of characters.

You must write a program that takes in a space separated string of words containing only capital letters, and outputs the first word "made of" the second "made of" the third and so on, using the pixelated font given above.

The "Plain ASCII" checkbox and the font size features of the snippet do not need to be supported in your program. Mirroring the transformation from lists of words to words made of words is the main point and only requirement.

# Details

* Input should come from stdin, the command line, or you may just write a function that takes a string.
* You may assume the input is always valid, i.e. a string of words made of capital letters, separated by exactly one space, with no leading or trailing spaces.
* Output should go to stdout (or similar alternative) or to a file with the name of your choice.
* The output should consist entirely of *empty-space characters*, *full-space characters*, and newlines.

+ The *empty/full-space characters* should either be space and full block (, ) respectively, or period and X (`.`, `X`) respectively.
* The output should not contain any leading columns containing only *empty-space characters*, though any combination of trailing *empty-space characters* on any lines is allowed.

+ So this is allowed:

    ```
    X...X.XXXXX..
    X...X.X
    X.X.X.XXXX....
    X.X.X.X..
    .X.X..XXXXX..

    ```
    + But this isn't:

    ```
    .X...X.XXXXX..
    .X...X.X
    .X.X.X.XXXX....
    .X.X.X.X..
    ..X.X..XXXXX..

    ```
* There should be no leading or trailing rows containing only *empty-space characters*. A single trailing newline is optionally allowed.

Here is a more string-friendly version of the font:

```
.XXX.
X...X
XXXXX
X...X
X...X

XXXX.
X...X
XXXX.
X...X
XXXX.

.XXX.
X...X
X....
X...X
.XXX.

XXXX.
X...X
X...X
X...X
XXXX.

XXXXX
X....
XXXX.
X....
XXXXX

XXXXX
X....
XXXX.
X....
X....

.XXXX
X....
X..XX
X...X
.XXXX

X...X
X...X
XXXXX
X...X
X...X

XXXXX
..X..
..X..
..X..
XXXXX

....X
....X
....X
X...X
.XXX.

X...X
X..X.
XXX..
X..X.
X...X

X....
X....
X....
X....
XXXXX

X...X
XX.XX
X.X.X
X...X
X...X

X...X
XX..X
X.X.X
X..XX
X...X

.XXX.
X...X
X...X
X...X
.XXX.

XXXX.
X...X
XXXX.
X....
X....

.XXX.
X...X
X...X
X..XX
.XXXX

XXXX.
X...X
XXXX.
X..X.
X...X

.XXXX
X....
.XXX.
....X
XXXX.

XXXXX
..X..
..X..
..X..
..X..

X...X
X...X
X...X
X...X
.XXX.

X...X
X...X
.X.X.
.X.X.
..X..

X...X
X...X
X.X.X
X.X.X
.X.X.

X...X
.X.X.
..X..
.X.X.
X...X

X...X
.X.X.
..X..
..X..
..X..

XXXXX
...X.
..X..
.X...
XXXXX

```

# Scoring

This is so the shortest submission in bytes wins. Any instance of a full block () can be counted as 1 byte instead of 3 so submissions that use `X` don't have an advantage.

# Answer
> 8 votes
# CJam, ~~171 165 162~~ 161 bytes

```
qS/_0=,0a*a\{{W:I;{'[{RI):I=}?i65-"c¿»ÐòO*4Õ]%ÐÎ<Ã IX]{-ïèq=ô}s×o)½2~û³'é¨1ÃlØeúN!Ö3~4ÜË|ÕÇäaepý®"255b2b5/5/=}%z1af*}%R,1a*a*}fR2a*"█
"f=

```

I am treating  as 1 byte. Rest all characters are well within ASCII range, so treating them as 1 byte too.

You can use this pastebin for the exact code

Example output for input:

```
FIRST HELLO WORLD

```

**How it works**

First of all

```
"c¿»ÐòO*4Õ]%ÐÎ<Ã IX]{-ïèq=ô}s×o)½2~û³'é¨1ÃlØeúN!Ö3~4ÜË|ÕÇäaepý®"255b2b5/5/

```

is simply the pattern for each of the 27 characters (`A-Z` and space) which is made up of `0` (at `X` positions) and `1` (at `.` positions). After decoding, this gives a 27 element array of 2D arrays of 5 rows and 5 columns representing `X` and `.` for each of the 27 characters. Let us call this array as `L`.

Now the remaining code:

```
qS/                      "Read the input and split it on space to get array Q";
   _0=                   "Get a copy of the first element of the above array";
      ,0a*               "Create an array filled with 0 with length of the first element";
          a\             "Wrap that array in another array and swap to get Q on top";
{  ...  }fR              "This is a for each loop on the array Q with R having the";
                         "current element value in each loop";
 {...}%                  "In the first iteration, the 0 array we created will be the";
                         "only thing on stack, in subsequent iterations, the result";
                         "of previous iteration will be on stack";
  W:I;                   "Initialize variable I with -1";
      {...}%             "Run this block on each element of the current array";
{'[{RI):I=}?i65-L=}%     "This is the above code block. In each iteration, we figure";
                         "out what character needs to be be put at the current index";
                         "Then we get the pattern of 0 and 1 for that character";
 '[{      }?             "Stack contains either 0 or 1. If it is 1, we want to leave";
                         "that index blank, so we put pattern of '[ which is 5X5 spaces";
    RI_:I=               "When we do not want a blank character, we get the next"
                         "character from R to fill the non empty space";
            i65-         "Convert A-Z  to 0-27 notation";
                L=       "Get the corresponding pattern from the pattern array L";
z1af*                    "After the above iterations, for each line of the previous";
                         "iteration's output, we get a vertical 2D array for next";
                         "iteration. We transpose it and join each character in";
                         "this line using a space";
      R,1a*a*            "After getting all lines from current iteration, we join them";
                         "with one full line of space characters";

 2a*                     "After all iterations, we have the 0 1 based 2D array for the";
                         "final output ASCII with each row representing a line. We join";
                         "these lines with 2, to get a 0 1 2 based array";
     "█                  "A brick, a space and a newline. Mapping 1 to 1 with 0 1 2";
"                        "based array";
 f=                      "For each of the 0 1 2 based array element, convert them to";
                         "one of the brick, space and new line character";

```

Try it online here

# Answer
> 9 votes
## Python 3, 437 bytes

```
from numpy import*
s=input().split()
d=fromstring('NONO__^Q_PQAQQNONO^_QQQQQ_QQQQAAAQDPIA[SQQQQADQQQJJH_OAQOOY_DPGAUUQOQONDQJUDDDQQQQAAQQDQIAQYQAYIPDQJUJDBQONO_A^Q_NQ_QQNA^QODNDJQD_',byte)[:,None]>>arange(5)&1
b=0
x=1
y=len(s[0])
n=[[1]*y]
for w in s:
 g=n;b+=x;x*=6;n=zeros((x,x*y),int);i=-6
 for q in g:
  o=j=0;i+=6
  for p in q:n[i:i+5,j:j+5]|=d[ord(w[o%len(w)])-65::26]*p;o+=p;j+=6
for r in n[:-b]:print(''.join(' █'[x] for x in r))

```

The character shapes are encoded in ASCII. Each ASCII byte corresponds to one row of one character, with bits representing unit blocks. It isn't a very efficient scheme, but it's easy to unpack into NumPy bitmasks for each character.

We start off with a 2d array of 1s. It has one column for each character in the first word and a single row. Then, for each word, we create a new array of 0s, six times higher and six times wider than the previous array. Where the previous array had a 1, the corresponding 6x6 section of the new array is filled with the appropriate character's bitmask.

Here's an example (with an extremely small font):

# Answer
> 5 votes
# CJam, ~~181~~ ~~174~~ 170 bytes

All those non-ASCII characters are still within the extended ASCII range, so they can all be encoded in a single byte. (Except for the , but that one is treated specially according to the challenge spec.) Therefore, I'm counting each character as a byte.

```
"Á  :½A%õÍú£àËªë8!Õ*j4¶fVËa¡ùÔ¯{+ÛyéâõKn#@?
9Ôia)(Ñç;~LÒª"257b2bYYb" █"er5/5/:L;lS/_0=,'█*a\{f{W:T;\{' ={S5*a5*}{T):T1$='A-L=}?\}%W<zSf*}Sa*}/N*

```

Stack Exchange has probably mangled some of the unprintable characters, so you might have to copy the code from this pastebin.

Test it here.

Takes input via STDIN as a space-separated list of words. The first word is the largest scale. For instance:

```
HOLISM REDUCTIONISM

```

yields

```
████                    █████             ████  █   █  ███              █████                               █████  ███  █   █ █████  ████             █   █ ████  █████ ████        █   █                    ███
█   █                   █                 █   █ █   █ █   █               █                                   █   █   █ ██  █   █   █                 ██ ██ █   █ █     █   █       █   █                   █   █
████                    ████              █   █ █   █ █                   █                                   █   █   █ █ █ █   █    ███              █ █ █ ████  ████  █   █       █   █                   █
█  █                    █                 █   █ █   █ █   █               █                                   █   █   █ █  ██   █       █             █   █ █  █  █     █   █       █   █                   █   █
█   █                   █████             ████   ███   ███                █                                 █████  ███  █   █ █████ ████              █   █ █   █ █████ ████         ███                     ███

████                    █████       ████                    █   █        ███                                            █████                   █████                                ███  █   █       █████  ████
█   █                   █           █   █                   █   █       █   █                                             █                       █                                 █   █ ██  █         █   █
████                    ████        █   █                   █   █       █                                                 █                       █                                 █   █ █ █ █         █    ███
█  █                    █           █   █                   █   █       █   █                                             █                       █                                 █   █ █  ██         █       █
█   █                   █████       ████                     ███         ███                                              █                     █████                                ███  █   █       █████ ████

████  █████ ████  █   █  ███        █████                   █████        ███                                            █   █                         █████  ████ █   █             ████        █████       ████
█   █ █     █   █ █   █ █   █         █                       █         █   █                                           ██  █                           █   █     ██ ██             █   █       █           █   █
████  ████  █   █ █   █ █             █                       █         █   █                                           █ █ █                           █    ███  █ █ █             ████        ████        █   █
█  █  █     █   █ █   █ █   █         █                       █         █   █                                           █  ██                           █       █ █   █             █  █        █           █   █
█   █ █████ ████   ███   ███          █                     █████        ███                                            █   █                         █████ ████  █   █             █   █       █████       ████

████                    █████       ████                    █   █        ███                                            █████                                           █████        ███                    █   █
█   █                   █           █   █                   █   █       █   █                                             █                                               █         █   █                   ██  █
████                    ████        █   █                   █   █       █                                                 █                                               █         █   █                   █ █ █
█  █                    █           █   █                   █   █       █   █                                             █                                               █         █   █                   █  ██
█   █                   █████       ████                     ███         ███                                              █                                             █████        ███                    █   █

████                    █████             ████  █   █  ███              █████ █████  ███  █   █ █████        ████ █   █ ████  █████ ████        █   █  ███  █████ █████              ███                    █   █
█   █                   █                 █   █ █   █ █   █               █     █   █   █ ██  █   █         █     ██ ██ █   █ █     █   █       █   █ █   █   █     █               █   █                   ██  █
████                    ████              █   █ █   █ █                   █     █   █   █ █ █ █   █          ███  █ █ █ ████  ████  █   █       █   █ █       █     █               █   █                   █ █ █
█  █                    █                 █   █ █   █ █   █               █     █   █   █ █  ██   █             █ █   █ █  █  █     █   █       █   █ █   █   █     █               █   █                   █  ██
█   █                   █████             ████   ███   ███                █   █████  ███  █   █ █████       ████  █   █ █   █ █████ ████         ███   ███    █   █████              ███                    █   █

```

## Explanation

First, we store a lookup table for letter shapes in `L`:

```
"Á  :½A%õÍú£àËªë8!Õ*j4¶fVËa¡ùÔ¯{+ÛyéâõKn#@?
9Ôia)(Ñç;~LÒª"257b2bYYb" █"er5/5/:L;

```

The first string just a compressed number. We treat the code points as base-257 digits, then we convert the resulting number to binary. `YYb` is 2 is in base 2, so it gives `[1 0]`. We use element substitution with `" █"` to turn the digits into spaces and block characters. Lastly, we split the string into rows of 5 characters, and again into blocks of 5 rows. The result is stored in `L` and discarded from the stack.

Now the general idea is to start with a single line of  of the length of the largest-scale word. And then for each word we go through the existing grid, and expand all blocks to the corresponding character at the next smaller scale (while inserting empty rows and columns for separation). Here is the input preparation:

```
lS/_0=,'█*a\
lS/          "Read input, split on spaces.";
   _0=       "Duplicate and get first word.";
      ,'█*   "Get length repeat █ that many times.";
          a  "Wrap in array, to make the grid two-dimensional.";
           \ "Swap with word list.";

```

Let's look at the outermost structure of the remaining program first. The next block `{...}/` is run for every word, and expands each of the block characters.

```
{f{...}Sa*}/N*
{         }/   "Process each word in the input.";
 f{...}        "Map this block onto each line of the grid, passing in the current word as well.";
       Sa*     "Since each original line will be turned into 5 lines, the grid is still grouped
                into blocks of 5 lines. We join them together with empty lines as required.";
            N* "Join all lines together with newlines.";

```

Lastly, let's look at how a single line is expanded:

```
W:T;\{' ={S5*a5*}{T):T1$='A-L=}?\}%
W:T;                                "Store -1 in T.";
    \                               "Swap word with line.";
     {                           }% "Map this block onto each character.";
      ' =                           "Check if the character is a space.";
         {      }{            }?    "If it is, run the first block, otherwise the second.";
          S5*                       "Create a string of five spaces.";
             a5*                    "Create an array of five such strings.";
                  T):T              "Push T, increment, store in T.";
                      1$=           "Copy the word and access the T'th character, cyclically.";
                         'A-        "Subtract A from the letter.";
                            L=      "Use the result to get the character shape from L.";
                                \   "Swap resulting block with word.";

"At this point each character is replaced with a 5x5 array of new characters.
 So we actually have a 3D array right now. Since we used a map operation, the
 current word will also be at the end of the array, which we need to get rid off.";

W<zSf*
W<     "Discard last array element - the current word.";
  z    "Zip or transpose the top two levels of the array.";
   Sf* "Join each line together with spaces.";

```

The result is printed automatically at the end of the program.

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


title: Collatz Attack!

text:
# Question
Title: Collatz Attack!
This challenge is based on some new findings related to the Collatz conjecture and designed somewhat in the spirit of a collaborative polymath project. Solving the full conjecture is regarded as extremely difficult or maybe impossible by math/number theory experts, but this simpler task is quite doable and there is many examples of sample code. In a best case scenario, new theoretical insights might be obtained into the problem based on contestants entries/ ingenuity/ creativity.

The new finding is as follows: Imagine a contiguous series of integers \[ *n1 ... n2* \] say *m* total. Assign these integers to a list structure. Now a generalized version of the Collatz conjecture can proceed as follows. Iterate one of the *m* (or fewer) integers in the list next based on some selection criteria/algorithm. Remove that integer from the list if it reaches 1. Clearly the Collatz conjecture is equivalent to determining whether this process always succeeds for all choices of *n1, n2*.

Here is the twist, an additional constraint. At each step, add the *m* current iterates in the list together. Then consider the function *f(i)* where *i* is the iteration number and *f(i)* is the sum of current iterates in the list. Look for *f(i)* with a particular "nice" property.

The whole/ overall concept is better/ more thoroughly documented here (with many examples in ruby). The finding is that fairly simple strategies/ heuristics/ algorithms leading to "roughly monotonically decreasing" *f(i)* exist and many examples are given on that page. Here is one example of the graphical output (plotted via gnuplot):

So here is the challenge: Use varations on the existing examples or entirely new ideas to build a selection algorithm resulting in a *f(i) "as close to monotonically decreasing as possible".* Entrants should include a graph of *f(i)* in their submission. Voters can vote based on that graph & the algorithmic ideas in the code.

The contest will be based on *n1 = 200 / n2 = 400* parameters only! (the same on the sample page.) But hopefully the contestants will explore other regions and also attempt to generalize their algorithms.

Note, one tactic that might be very useful here are gradient descent type algorithms, or genetic algorithms.

Can discuss this all further in chat for interested participants.

For some ref, another codegolf Collatz challenge: Collatz Conjecture (by Doorknob)

# Answer
> 4 votes
I wrote some code in Python 2 to run algorithms for this challenge:

```
import matplotlib.pyplot as plt

def iterate(n):
    return n*3+1 if n%2 else n/2
def g(a):
    ##CODE GOES HERE
    return [True]*len(a)
n1=input()
n2=input()
a=range(n1,n2+1)
x=[]
y=[]
i=0
while any(j>1 for j in a):
    y.append(sum(a))
    x.append(i)
    i+=1
    b=g(a)
    for j in range(len(a)):
        if b[j]:
            a[j]=iterate(a[j])
plt.plot(x,y)
plt.show()

```

`g(x)` takes the list of values and returns a list of bools for whether each one should be changed.

That includes the first thing I tried, as the line right after the comment, which was iterating all of the values in the list. I got this:

It doesn't look close to monotonic, so I tried iterating only values that would decrease the sum, if there are any, iterating the ones that would increase it least otherwise:

```
l=len(a)
n=[iterate(i) for i in a]
less=[n[i]<a[i] for i in range(l)]
if any(less):
    return less
m=[n[i]-a[i] for i in range(l)]
return [m[i]==min(m) for i in range(l)]

```

Unfortunately, that doesn't terminate (at least for `n1=200`, `n2=400`). I tried keeping track of values I'd seen before by initializing `c=set()`:

```
l=len(a)
n=[iterate(i) for i in a]
less=[n[i]<a[i] for i in range(l)]
if any(less):
    return less
m={i:n[i]-a[i] for i in range(l)}
r=[i for i in m if m[i]==min(m.values())]
while all([a[i] in c for i in r]) and m != {}:
    m={i:m[i] for i in m if a[i] not in c}
    r+=[i for i in m.keys() if m[i]==min(m.values())]
for i in r:
    c.add(a[i])
return [i in r for i in range(l)]

```

That doesn't terminate either, though.

I haven't tried anything else yet, but if I have new ideas, I'll post them here.

# Answer
> 2 votes
## Python 3

My main idea was to add each numbers Collatz sequence to the `f(i)` function individually in a way that it minimizes the total increasing of `f(i)`. The resulting function isn't strictly decreasing but it has a nice structure (in my opinion :)). The second graph was created with longer interval for `f(i)` and slightly different punishment function. Code on Gist.

When using the (3\*n+1)/2 rule instead the 3\*n+1 one the algorithm produces a completely monotonic `f(i)`! I'm sure this modification could make vzn's graphs a lot smoother too. The second graph was created with longer interval for `f(i)`. Code on Gist.

Both results are similar for bigger `[n,2*n]` ranges.

---
Tags: popularity-contest, math, graphical-output, number-theory
---


# Question
Title: Babylon.js - loop through a scene and apply a simple fragment shader to all of the objects
You have a library - a fully loaded 2014 Babylon.js.

You have a fragment shader - let's call it sample.fragment.fx.

You have a scene - loaded ahead of time, possibly from a .babylon JSON file.

Your goal is to assign the fragment shader to every textured object in the scene using a snippet of JavaScript or TypeScript code.

**Scoring:**

The main multiplier is calculated in the form of one divided by the total number of bytes in the snippet not counting whitespace characters used for formatting.

Additional multipliers (apply one for each condition met) -

\*0.5 (bad) - The solution does not reference the "sample" fragment shader by name.

\*0.8 (bad) - The solution is presented in TypeScript.

\*1.1 (good) - The solution implements a proper for loop (either the for or forEach keyword is used).

\*1.2 (good) - The solution intelligently applies the shader only to objects that meet a certain arbitrary criterion, for example: it has texture, or it has a certain prefix in its name.

\*1.3 (good) - After all multipliers are applied, the score is greater than 0.008.

This should remain open indefinitely. The highest score wins.

# Answer
## In Javascript

```
// The suffix of all meshes wich should have the shader applied
var suffix = "shader";

//If true, the shader will be applied on this mesh
var predicate = function(mesh) {
    return (
       mesh.material
       && mesh.name.indexOf(suffix , mesh.name.length - suffix.length) !== -1
    );
};

// Creation of the shader material
var shaderMaterial = new BABYLON.ShaderMaterial("sampleShader", scene, "sample", {
            attributes: ["position"],
            uniforms: ["worldViewProjection"]
            });

// Apply the shader on all meshes
scene.meshes.forEach(function(m) {
    if (predicate(m)) {
        m.material = shaderMaterial;
    }
});

```
> 3 votes

# Answer
```
var t = new BABYLON.ShaderMaterial("sh", scene, "./sample", {
    attributes: ["uv"], uniforms: ["view"]
});

scene.meshes.forEach(function(m) { m.material = m.material && t; });

```

score : 1/164 * 1.1 (forEach) * 1.2 (material predicate) = 0.00804 * 1.3 = **0.0104**
> 2 votes

---
Tags: code-challenge, game, graphical-output, restricted-source, javascript
---


title: Trucks in a parking lot

text:
# Question
Title: Trucks in a parking lot
There are P parking spaces in a parking lot, though some spaces are occupied by cars represented by octothorpes `#` while the free spaces are dots `.`. Soon there arrive T trucks, each of which will take up exactly L consecutive spaces. The trucks don't have to be parked next to each other.

Your task is to create a program that will find the smallest number of cars that need to be removed in order to park all of the trucks. There will always be enough spaces to fit all of the trucks, meaning `T*L<P`

## Input

In the first row there will be three integers, P, T and L separated by spaces. In the second row there will be a string of P characters representing the parking lot in its initial state.

## Output

In the first and only line your program should print out the smallest number of cars that need to be removed in order to park all of the trucks.

## Test cases

Input:
`6 1 3`
`#.#.##`

Output: `1`

Input:
`9 2 3`
`.##..#..#`

Output: `2`

Input:
`15 2 5`
`.#.....#.#####.`

Output: `3`

Shortest code wins. (Note: I'm particularly interested in a pyth implementation, if one is possible)

# Answer
> 4 votes
# Python 2, 154 bytes

```
I,R=raw_input,range
P,T,L=map(int,I().split())
S=I()
D=R(P+1)
for r in R(P):D[1:r+2]=[min([D[c],D[c-1]+(S[r]<".")][c%L>0:])for c in R(1,r+2)]
print D[T*L]

```

A straightforward DP approach. A fair chunk of the program is just reading input.

**Explanation**

We calculate a 2D dynamic programming table where each row corresponds to the first `n` parking spots, and each column corresponds to the number of trucks (or parts of a truck) placed so far. In particular, column `k` means that we've placed `k//L` full trucks so far, and we're `k%L` along the way for a new truck. Each cell is then the minimal number of cars to clear to reach the state `(n,k)`, and our target state is `(P, L*T)`.

The idea behind the DP recurrence is the following:

* If we're `k%L > 0` spaces along for a new truck, then our only option is to have come from being `k%L-1` spaces along for a new truck
* Otherwise if `k%L == 0` then we have either just finished a new truck, or we'd already finished the last truck and have since skipped a few parking spots. We take the minimum of the two options.

If `k > n`, i.e. we've placed more truck squares than there are parking spots, then we put  for state `(n,k)`. But for the purposes of golfing, we put `k` since this is the worst case of removing every car, and also serves as an upper bound.

This was quite a mouthful, so let's have an example, say:

```
5 1 3
..##.

```

The last two rows of the table are

```
[0, 1, 2, 1, 2, ∞]
[0, 0, 1, 1, 1, 2]

```

The entry at index 2 of the second last row is 2, because to reach a state of `2//3 = 0` full trucks placed and being `2%3 = 2` spaces along for a new truck, this is the only option:

```
  TT
..XX

```

But the entry at index 3 of the second last row is 1, because to reach a state of `3//3 = 1` full trucks placed and being `3%3 = 0` spaces along for a new truck, the optimal is

```
TTT
..X#

```

The entry at index 3 of the last row looks at the above two cells as options — do we take the case where we are 2 spaces along for a new truck and finish it off, or do we take the case where we have a full truck already finished?

```
  TTT            TTT
..XX.     vs     ..X#.

```

Clearly the latter is better, so we put down a 1.

## Pyth, 70 bytes

```
JmvdczdKw=GUhhJVhJ=HGFTUhN XHhThS>,@GhT+@GTq@KN\#>%hT@J2Z)=GH)@G*@J1eJ

```

Basically a port of the above code. Not very well golfed yet. Try it online

**Expanded**

```
Jmvdczd              J = map(eval, input().split(" "))
Kw                   K = input()
=GUhhJ               G = range(J[0]+1)
VhJ                  for N in range(J[0]):
=HG                    H = G[:]
FTUhN                  for T in range(N+1):
 XHhT                    H[T+1] =
hS                                sorted(                                        )[0]
>                                                                 [            :]
,                                        (      ,                )
@GhT                                      G[T+1]
+@GTq@KN\#                                       G[T]+(K[N]=="#")
>%hT@J2Z                                                           (T+1)%J[2]>0
)=GH                   G = H[:]
)@G*@J1eJ            print(G[J[1]*J[-1]])

```

Now, if only Pyth had multiple assignment to \>2 variables...

# Answer
> 3 votes
## Haskell, 196 characters

```
import Data.List
f=filter
m=map
q[_,t,l]=f((>=t).sum.m((`div`l).length).f(>"-").group).sequence.m(:".")
k[a,p]=minimum.m(sum.m fromEnum.zipWith(/=)p)$q(m read$words a)p
main=interact$show.k.lines

```

Runs all examples

```
& (echo 6 1 3 ; echo "#.#.##" )  | runhaskell 44946-Trucks.hs
1

& (echo 9 2 3 ; echo ".##..#..#" )  | runhaskell 44946-Trucks.hs
2

& (echo 15 2 5 ; echo ".#.....#.#####." )  | runhaskell 44946-Trucks.hs
3

```

Somewhat slow: **O(2^P)** were P is the size of the lot.

Probably plenty left to golf here.

---
Tags: code-golf
---


title: It's Spanish Time!

text:
# Question
Title: It's Spanish Time!
I have a simple task that should be relatively easy to implement by means of code. **Your goal** is to write a program that will output the time written in Spanish, given the time in HH:MM format. Many people likely don't know *how* to do this, so I will elaborate.

Time in Spanish is fairly logical. It usually follows the pattern of "Es la/Son las (hour) y (minutes)." Hours are in a 12-hour format, and "Es la" is **only used** if the hour is 1 (i.e. one o'clock). The minutes are a different story. If the minute is less than 30, then it is represented as shown above. If the minute is over 30, however, then the hour is rounded up and the minute is subtracted. For example, 7:35 is translated to the equivalent of "8 hours minus 25 minutes." Some more examples will be given below. The list of Spanish numbers that are necessary can be found here. There are accents on some numbers, but these are not necessary.

**Note:** The source says "uno," but to be grammatically correct it should be "una." This shouldn't affect any answers so far.

**Note 2:** Also, "cero" is not necessary. If your program outputs "Es la una" or "Son las tres," that is fine with me. Sorry for these rule changes.

## Rules

* Input will be provided through STDIN or the equivalent in your language.
* No reading from outside libraries.
* Your code can do anything with invalid input.

## Bonuses

* -10 if your code adds these extra phrases - "y cuarto" for :15, "y media" for :30, and "menos cuarto" for :45 (rounded up).
* -15 if your code can handle A.M. and P.M., responding with "de la mañana" and "de la tarde," accordingly.
* -15 if your code can translate the current time if no input is provided.

## Scoring

* This is a code-golf challenge, and it will be scored by bytes, not characters.

## Examples

Input: `8:10` Output: `Son las ocho y diez.`

Input: `6:45` Output: `Son las siete menos quince (or cuarto).`

Input: `1:29` Output: `Es la una y veintinueve.`

Input: `12:55` Output: `Es la una menos cinco.`

Let me know if there is anything to specify here. This is my first question, so it is definitely not perfect.

# Answer
# JavaScript (ES6) 308 ~~316~~

**Edit2** bug fix **Edit** forgot to claim the bonus
As a program with I/O via popup

```
s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0),
N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'),
[h,m]=prompt().split(':'),
alert(((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):''))

```

As a testable function

```
F=t=>(
  s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0),
  N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'),
  [h,m]=t.split(':'),
  ((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):'')
)

```

**Test** In FireFox/FireBug console

```
for(i=0;i<13;i++)
{
   console.log(F(i+':'+i)+'. '+F(i+':'+(i+15))+'. '+F(i+':'+(i+30))+'. '+F(i+':'+(i+45)))
}

```

*Output*

```
Son las doce. Son las doce y cuarto. Son las doce y media. Es la una menos cuarto
Es la una y uno. Es la una y dieciseis. Son las dos menos veintinueve. Son las dos menos catorce
Son las dos y dos. Son las dos y diecisiete. Son las tres menos veintiocho. Son las tres menos trece
Son las tres y tres. Son las tres y dieciocho. Son las cuatro menos veintisiete. Son las cuatro menos doce
Son las cuatro y cuatro. Son las cuatro y diecinueve. Son las cinco menos veintiseis. Son las cinco menos once
Son las cinco y cinco. Son las cinco y veinte. Son las seis menos veinticinco. Son las seis menos diez
Son las seis y seis. Son las seis y veintiuno. Son las siete menos veinticuatro. Son las siete menos nueve
Son las siete y siete. Son las siete y veintidos. Son las ocho menos veintitres. Son las ocho menos ocho
Son las ocho y ocho. Son las ocho y veintitres. Son las nueve menos veintidos. Son las nueve menos siete
Son las nueve y nueve. Son las nueve y veinticuatro. Son las diez menos veintiuno. Son las diez menos seis
Son las diez y diez. Son las diez y veinticinco. Son las once menos veinte. Son las once menos cinco
Son las once y once. Son las once y veintiseis. Son las doce menos diecinueve. Son las doce menos cuatro
Son las doce y doce. Son las doce y veintisiete. Es la una menos dieciocho. Es la una menos tres

```
> 9 votes

# Answer
Yes, the least expected language to appear on a golf contest, coded by the world's worst golfer, is back!

## Java - 676 bytes (716-10-15-15)

Golfed:

```
class A{void main(String[]a){java.util.Calendar c=java.util.Calendar.getInstance();int h,m;String s="";h=c.get(c.HOUR);m=c.get(c.MINUTE);String[]e={"doce","una","dos","tres","quatro","cinco","ses","siete","ocho","nueve","diez","once","doce","trece","catorce","quarto","çseís","çsiete","çocho","çnueve","xe","xiuno","xidós","xitrés","xiquatro","xicinco","xiséis","xisiete","xiocho","xinueve","media"};for(int i=0;++i<30;e[i]=e[i].replace("ç","dieci"),e[i]=e[i].replace("x","vient"));s+=(h==1&m<30|h==12&m>30)?"Es la ":"Son las ";s+=(m<=30)?e[h]:(h==12&m>30)?e[1]:e[h+1];s+=(m==0)?" certas":(m<=30)?" y "+e[m]:" menos "+e[60-m];s+=(c.get(c.AM_PM)==0)?" de la mañana.":" de la tarde.";System.out.println(s);}}

```

Ungolfed:

```
public class A {

    public static void main(String[] a) {
        java.util.Calendar c = java.util.Calendar.getInstance();
        int h, m;
        String s = "";
        h = c.get(c.HOUR);
        m = c.get(c.MINUTE);
        String[] e = {"doce", "una", "dos", "tres", "quatro", "cinco", "ses", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quarto", "çseís", "çsiete", "çocho", "çnueve", "xe", "xiuno", "xidós", "xitrés", "xiquatro", "xicinco", "xiséis", "xisiete", "xiocho", "xinueve", "media"};
        for (int i = 0; ++i < 30; e[i] = e[i].replace("ç", "dieci"), e[i] = e[i].replace("x", "vient"));
        s += (h == 1 & m < 30 | h == 12 & m > 30) ? "Es la " : "Son las ";
        s += (m <= 30) ? e[h] : (h == 12 & m > 30) ? e[1] : e[h + 1];
        s += (m == 0) ? " certas" : (m <= 30) ? " y " + e[m] : " menos " + e[60 - m];
        s += (c.get(c.AM_PM) == 0) ? " de la mañana." : " de la tarde.";
        System.out.println(s);
    }
}

```

Deals with the `quarto` and `media`, with the AM/PM and has no input. So I can claim all the bonuses, even though that, if I didn't implement those features, I'd have an even lower score, lol. *facepalms*
> 8 votes

# Answer
## Python 3: 294 chars - 10 = 284

```
h,m=map(int,input().split(':'))
t="y"
d="yunoydosytresycuatroycincoyseisysieteyochoynueveydiezyonceydoceytreceycatorceycuarto".split(t)*2
if m>30:h=h%12+1;m=60-m;t="menos"
print(["Es la una","Son las "+d[h]][h>1],t,[d[m]or"cero",["dieci","veint"+'ei'[m>20],"media"][m//10-1]+d[m%10]][m>15]+".")

```

This gets the ten-point bonus for using "cuarto" and "media"

We read the hours and minutes as `int`s. If the minutes are above 30, we move to the next hour, measure minutes away from 60, and change the conjunction to "menos".

The list `d` has translations of Spanish numbers up to 15. We make `d[0]` be `''` to prevent things like "diecicero". This is done by awkwardly calling `split(' ')` with an initial space; the regular `split` would just ignore it. The zero-minute case is handled later.

To get numbers above 15, we combine the tens-digit string with the appropriate one-digit string. `15` and `30` are written as "media" and "cuarto" at no cost.

Python 3 saves one char net over Python 2: -4 for `input` instead of `raw_input`, +2 for parens in print, +1 for `//`.
> 6 votes

# Answer
# C++: ~~474~~ ... ~~422~~ 411 bytes

This version is redeeming the cuarto/media bonus (-10).

```
#include<cstdlib>
#include<cstdio>
int main(int u,char**v){char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"};int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o;h=n?h%12+1:h;m=o=n?60-m:m;if(u=m>15&m!=20)o=m%10;printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]);}

```

My first attempt ever at code golfing! Will try to improve it this weekend.

Ungolfed:

```
#include<cstdlib>
#include<cstdio>
int main(int u,char**v)
{
char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"};
int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o;
h=n?h%12+1:h;
m=o=n?60-m:m;
if(u=m>15&m!=20)o=m%10;
printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]);
}

```
> 5 votes

# Answer
# PHP, ~~351~~ ~~349~~ 360 - 15 = 345 Bytes

```
<?$a=split(~ß,~œšßŠ‘ß›Œß‹šŒßœŠž‹ßœ–‘œßŒš–ŒßŒ–š‹šßœ—ß‘Šš‰šß›–š…ß‘œšß›œšß‹šœšßœž‹œšßŽŠ–‘œšß›–šœ–ß‰š–‘‹–ß‹š–‘‹ž)?><?=preg_filter(~Ð×ÑÔÖÅ×ÑÔÖÐš,'(($h=($1-($k=$2<31))%12+1)>1?~¬‘ß“žŒß:~ºŒß“žß).$a[$h].($k?~ß†ß:~ß’š‘Œß).(($m=$k?$2+0:60-$2)<16?$a[$m]:($m<20?$a[16].$a[$m%10]:($m<21?viente:($m<30?$a[17].$a[$m%10]:$a[18])))).~Ñ',$_GET[0]?:date(~·Å–));

```

This program is not command line: it takes input via $\_GET\[0\]. You may have to disable notices in your php.ini. Now comes with auto time with no input, thanks to Niet the Dark Absol.

**Tricks used:**

`~(...)` saves one byte by bitwise inverting a string, as you don't need quote marks as PHP usually assumes all ASCII from 0x80 to 0xFF is a string.

`<?=preg_filter(...,...)`: The `<?=` is a shortcut for writing `<? echo`. `preg_filter()` usually applies replacements on a string using a regex, but we can use the depreciated /e modifier to evaluate the resulting string as PHP code. Hence, instead of having to split the input string into two separate variables, we can use backreferences ($1 and $2) on the matched input string, saving large amounts of bytes.
> 5 votes

# Answer
# Lua, 450 - 10 (cuarto/media) - 15 (manana/tarde) = 425

```
n={'uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece','catorce','cuarto',[20]='veinte',[30]='media'}for i=1,9 do n[i+10]=n[i+10]or'dieci'..n[i]n[i+20]='veinti'..n[i]end H,M=io.read():match('(%d+):(%d+)')H,M=H+0,M+0 X,Y='tarde',' y 'if H<12 then X='manana'end if M>30 then H,M,Y=H+1,60-M,' menos 'end H=(H-1)%12+1 S=H==1 and'es la una'or'son las '..n[H]if M>0 then S=S..Y..n[M]end S=S..' de la '..X print(S)

```
* Dropped 12 bytes by rewriting the generator for 21-29.
* Dropped 1 more by replacing `H>=12` with `H<12` and switching the dependent expression around.
* Dropped 4 more by polluting the global namespace from a function (evil, but in the interest of golfing :).
* Fixed the regex, I forgot the colon. Doesn't change the byte count, however.
* Fixed the case of zero minutes, swapped `table.concat` out for string ops, and added @edc65's suggestion, ultimately adding 22 bytes.
* I am shamed. Pulling the `function` body out into the main chunk reduced the length by a whopping *15 bytes*.
> 4 votes

# Answer
# Python 3, 409 bytes

```
d='cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte xuno xdos xtres xcuatro xcinco xseis xsiete xocho xnueve treinta';d=str(d.replace('x','veinti')).split();t=input().split(':');i=int(t[1]);j=int(t[0]);print(["Son las","Es la"][1<(2*j+i/30)%24<=3],[d[[j%12+1,j][i<31]],'una'][j==1],'y'if i<31 else'menos',d[min(i,60-i)])

```
> 3 votes

# Answer
# D - 484 bytes

```
import std.stdio,std.conv,std.string;void main(){auto n="cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve e iuno idos itres icuatro icinco iseis isiete iocho inueve treinta".split;auto p=stdin.readln()[0..$-1];int b=to!int(p[0..$-3]),a=to!int(p[$-2..$]);auto c=a;b=a>30?b+1:b;b%=12;a=a>30?60-a:a;writefln("%s %s %s %s", b==1||b==12?"Es la":"Son las",n[b],c>30?"menos":"y",(a/10==2?"vient":"")~n[a]);}

```
> 3 votes

# Answer
# Ruby, 313 (338 - 15 - 10)

This solution translates the current time when no input was given and adds the three phrases "y cuarto", "y media" and "menos cuarto".

```
require'time'
t,x,s=Time,$*[0],%w[cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto]
1.upto(9){|i|i>5?s[10+i]="dieci"+s[i]:0;s[20+i]="veinti"+s[i]}
s[20]="veinte"
s<<"media"
c=x ?t.parse(x):t.new
h,m=c.hour%12,c.min
m<31?(a=" y "):(h,m,a=h+1,60-m," menos ")
$><<(h<2?"Es la ":"Son las ")+s[h]+a+s[m]

```
> 3 votes

# Answer
# Perl - 297 - 10 + 1 = 288 (counting the `p` flag)

Edit: thanks to @guifa, I can now claim a bonus :)

```
#!/usr/bin/perl -p
sub n{($_=shift)%10?(once,doce,trece,catorce,cuarto)[$_>9?$_-11:5]||('',dieci,veinti)[$_/10].(0,un.pop,dos,tres,cuatro,cinco,seis,siete,ocho,nueve)[$_%10]:(cero,diez,veinte,media)[$_/10]}/:/;$a=$`%12;$b=$';$c=$b>30?(++$a,$b=60-$b,menos):'y';$_=($a-1?'Son las ':'Es la ').n($a,a)." $c ".n($b,o).'.'

```

Here is the same code in multiple lines for readability:

```
sub n {
        ($_ = shift) % 10
            ? (once, doce, trece, catorce, cuarto)[$_ > 9 ? $_ -11 : 5]
                || ('', dieci, veinti)[$_ / 10]
                . (0, un.pop, dos, tres, cuatro, cinco, seis, siete, ocho, nueve)[$_ % 10]
            : (cero, diez, veinte, media)[$_ / 10]
}
/:/;
$a = $` % 12;
$b = $';
$c = $b > 30 ? (++$a, $b = 60 - $b, menos) : 'y';
$_ = ($a - 1 ? 'Son las ' : 'Es la ') . n($a, a) . " $c " . n($b, o) . '.'

```
> 2 votes

# Answer
# Bash 423

(433 - 10 = 423, removing diacritics and cuarto we could go down to 381)

```
IFS=: read h m
s=y
m=${m#0}
[ $m -gt 30 ]&&h=$(($h+1))&&s=menos
[ -z ${m%0} ]&&s=en&&m=punto
n[0]=0
o[0]=0
S=" séis siete ocho nueve"
n=(punto una dos trés cuatro cinco $S diez {on,do,tre,cator,quin}ce ${S// / dieci} veinte)
n=($(eval echo "${n[@]}" veinti\$\{n[{1..9}]\}))
n[3]=tres;n[6]=seis
n=(${n[@]} media\  $(tac -s' '<<<${n[@]}))
o=("${n[@]/q*/cuarto}")
a=Son\ las
[ $h = 1 ]&&a=Es\ la
echo $a ${n[$h]/p*/cero} $s ${o[$m]/%a/o}

```
> 2 votes

# Answer
## Scala 652 bytes - 25

```
import java.util.Scanner
object S extends App{val s=new Scanner(System.in).useDelimiter("[:\n]")
var h=s.nextInt
var m=s.nextInt
if(m>30)m-=60 else h-=1
val n=m.abs
h%=24
val p=h%12
val l=List("una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto")
val k=List("úno","dós","trés",l(3),l(4),"séis",l(6),"ócho",l(8))
println(s"""${if(p==0)"Es la"else"Son las"} ${l(p)} ${if(m>0)"y "else if(m<0)"menos "}${if(n==1)"uno"else if(n==0)""else if(n<=15)l(n-1) else if(n==30)"media"else if(n<20)"dieci"+k(n-11)else if(n==20)"veinte"else"veinti"+k(n-21)} de la ${if(h<12)"mañana"else"tarde"}.""")}

```
> 0 votes

# Answer
# Pyth: 277 a bunch more 234 - 10 (cuarto/media bonus) = 224 bytes

Now reduced over 50 bytes from original!

```
=H" y "ANkmsdcz\:Kc"cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto veinte"dI>k30=k-60k=H" menos "=N?1qN12+N1)++?+"Son las "@KN>N1"Es la una"H??eKqk20?@Kk<k16+?"dieci"<k21+PeK\i@K%kT<k30"media"

```

Insanely long for Pyth but that's because there's some raw data. Can probably be golfed even further. Uses obvious technique of splitting task up into hours, y/menos, tens digit of minutes, and ones digit of minutes and then translates numbers using translation array and everything else using a crap-ton of ternaries.

```
=H" y "                 Set H to " y "
A                       Double Assignment
 Nk                     The variables N and k (hours and mins)
 m  cz\:                Map input split by ":"
  sd                    Make both int
Kc"..."d                Set K to string split by spaces
I>k30                   If k>30
     =k-60k             Set k to 60-k
     =H" menos "        Set k to menos instead of y
     =N                 Set N
      ?   qN12          If N=12
       1                Go back to one
       +N1              Increment N
)                       Close entire if block
+                       Concat of hours and minutes
 +                      Concat hours and y/menos
  ?           >N1       If hour greater than one
   +                    Concat of son las and hour
    "Son las "          "Son las "
    @KN                 Index translation array for hour
   "Es la una"          Else es la una
  H                     " y " or " menos "
 ?               <k30   If minutes less than 30
  ?  qk20               If minutes is 20
   ek                   Last element of array (veinte)
   ?   <k16             Else check if minutes<16
    @Kk                 Get minutes directly from array
    +                   Else tens and ones sum
     ?       <k21       If minutes<21
      "dieci"           "dieci"
      +PeK\i            Else get veinti from veinte
     @K%kT              Ones digit of minutes
  "media"               Else get "media"

```

## Golfing History

* 10 bytes - bonus, quince and trienta can just be replaced in translation array so no changes required except translation essay and its same size.
* 6 bytes - reorganized ternaries - unfortunately this removed the 4 consecutive ternary operators :(
* 6 bytes - other various golfing
* 6 bytes - golfed initial hour/min assignment
* +3 bytes - fixed uno/una
* 3 bytes - constructed veinti from veinte, not hardcoded
* 18 bytes - extracted dieci from teens\<16
* 2 bytes - removed some spaces in there for no reason
* 2 bytes - used \ for one char strings
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, date
---


title: Equilibrium index of a sequence

text:
# Question
Title: Equilibrium index of a sequence
Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

```
A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0

```

3 is an equilibrium index, because:

```
A[0]+A[1]+A[2]=A[4]+A[5]+A[6]

```

6 is also an equilibrium index, because:

```
A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0

```

(sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A.

The idea is to create a program that given a sequence (array), returns its equilibrium index (any) or -1 if no equilibrium indexes exist.

# Answer
> 6 votes
### Golfscript 17 16

Since the form of the input isn't specified, this takes a string in Golfscript array format from stdin.

```
~0\{1$+.@+\}/])?

```

So run as e.g.

```
golfscript.ry eqindex.gs <<<"[-7 1 5 2 -4 3 0]"

```

The idea is very simple: it takes an array of `A_i` and maps to an array of `A_i + 2 SUM_{j<i} A_j` and then looks for the first index which is equal to the sum of the whole array.

---

For @mellamokb's challenge I offer:

```
~0\{1$+.@+\}/:S;]:A,,{A=S=},`

```

for 29 chars.

# Answer
> 5 votes
## Haskell (~~95~~ 83)

```
e l=[n|n<-[0..length l-1],sum(take n l)==sum(drop(n+1)l)]
main=interact$show.e.read

```

Reads a list in Haskell style from stdin, eg.

```
[-7,1,5,2,-4,3,0]

```

and returns a Haskell style list of the indices, eg.

```
[3,6]

```

The result is `[]`, if there is no index.

Please tell me, if your spec wants a different behavior.

### Edits:

* (95 → 83): list comprehension is more breve

# Answer
> 5 votes
## Python - 72 chars

```
A=input()
print[i for i in range(len(A))if sum(A[:i])==sum(A[i+1:])]or-1

```

Takes comma separated input

# Answer
> 4 votes
## C - 96

```
a[99],*p=a,s;main(){for(;scanf("%d",p)>0;s+=*p++
);for(;p>a;s-=*p)(s-=*--p)||printf("%d\n",p-a);}

```

Note that this prints the equilibrium indices in reverse order.

Sample usage:

```
$ ./equilibrium <<< "-7 1 5 2 -4 3 0"
6
3

```

# Answer
> 3 votes
## Ruby (~~83~~ 77)

```
a=*$<.map(&:to_i)
p (0...a.size).select{|x|a[0..x].reduce(:+)==a[x..-1].reduce(:+)}

```

Edit: Shorter version as suggested by Ventero:

```
a=$<.map &:to_i
p (0...a.size).select{|x|eval"#{a[0..x]*?+}==#{a[x..-1]*?+}"}

```

Input is one number per line, output is comma separated list of indexes in square brackets.

# Answer
> 2 votes
## JavaScript (161)

```
P=parseInt;L=prompt().split(',');S=function(A)A.reduce(function(a,b)P(a)+P(b),0);R=[i for(i in L)if(S(L.slice(0,i))==S(L.slice(P(i)+1)))];alert(R.length>0?R:-1);

```

http://jsfiddle.net/6qYQv/1/

# Answer
> 2 votes
### scala, 108

```
val l=readline().split(" ").map(w=>w.toInt)
for(i<-0 to l.length-1
if l.take(i).sum==l.drop(i+1).sum)yield i

```

# Answer
> 2 votes
## J (12 characters)

A monadic verb in tacit notation that returns a vector of equilibrium indices. Spaces inserted for legibility only.

```
[: I. +/\. = +/\

```

To explain this, first observe its explicit definition; `y` is the formal parameter:

```
3 : 'I. (+/\. y) = (+/\ y)'

```
* `+` adds its arguments. `/` is an adverb that inserts the verb left of it between the members of its right argument, e.g. `+/ 1 2 3 4` is the same as `1 + 2 + 3 + 4`.
* `\` is an adverb that applies the verb to its left to all prefixes prefixes of its right argument. For instance, with `<` drawing a box around its argument, `<\ 1 2 3 4` produces

```
┌─┬───┬─────┬───────┐
│1│1 2│1 2 3│1 2 3 4│
└─┴───┴─────┴───────┘

```
* Thus, `+/\` computes for each prefix of its right argument the sum.
* `\.` is like `\` but operates on suffixes instead of prefixes. Thus, `+/\.` computes a vector of sums of suffixes.
* `=` performs item-wise comparison of its arguments. For instance, `1 1 3 3 = 1 2 3 4` yields `1 0 1 0`.
* Thus, `(+/\. y) = (+/\ y)` yields one for all indices at which the suffix sum is equal to the prefix sum, or, an equilibrium is created.
* For vectors of zeroes and ones, `I.` returns a vector of the indices at which the vector contains a one.

# Answer
> 1 votes
# Python 2, 70

```
A=input()
e=i=s=0
for x in A:e=[e,~i][s*2==sum(A)-x];s+=x;i+=1
print~e

```

The idea is to track the running sum `s` and check whether it is half of the sum of array without the current element, and therefore equal to the sum of the array after the current element. If so, we update the equilibrium index to the current index. The last equilibrium index is printed, or the initial value `-1` if there's none.

Actually, we store the bit-complement of the equilibrium index so that we can initialize it to 0 instead.

# Answer
> 0 votes
# Python - 114

```
i=map(lambda x:int(x),raw_input().split(" "));x=0
print map(lambda x:(sum(i[0:x])==sum(i[x+1::])),range(0,len(i)))

```

# Python - 72

```
i=input()
print map(lambda x:sum(i[0:x])==sum(i[x+1::]),range(0,len(i)))

```

Prints whether or not the given index is an equilibrium index, does not print the integer indecies at which the array is balanced.

# Answer
> 0 votes
# PHP, 134 chars

```
<?for($a=explode(",",fgets(STDIN));++$i<($c=count($a));$o.=$s==0?$i:"")for($n=$s=0;$n<$c;)$s+=$n<$i?$a[$n++]:-$a[++$n];echo$o?$o:"-1";

```

I have an itch that this is far from optimal PHP golfing, but just ran out of steam (brains). At least it's shorter than with array\_sum and array\_splice :-)

# Answer
> 0 votes
# PHP (81)

`for($i=count($a)-1,$c=0;$i+1&&$c!=(array_sum($a)-$a[$i])/2;$c+=$a[$i--]);echo $i;`

http://3v4l.org/qJvhO

Since no input was specified, this needs to be initialised with the array as the variable `$a`.

---
Tags: code-golf
---


title: Code Golf: Gibberish Echo

text:
# Question
Title: Code Golf: Gibberish Echo
This is my first code golf challenge, as such I am not entirely certain if it is suitable as a Code Golf challenge, but it's all a learning experience.

The challenge is that in as few characters as possible, using whichever language you prefer, develop a code to complete the following:

1. Take a value from stdin
2. Return a value to stdout that contains the same characters as the value at stdin in a different order. Not necessarily random, but following the restrictions set out below.

*Here are a few restrictions:*

* All characters that are contained in the stdin value must appear in stdout value
* Characters must appear in stdout the same amount of times they appear in stdin
* The order of characters in the output, cannot be identical to the order of characters in input, for more than two consecutive characters. Regardless of the source of the character in the input. That is, the input and output must not have a common substring of length 3 or greater.
* Any input where no solution can be found under the previous rule, is considered an invalid input

**Examples:** aaaa, bbbb
* you do not need to test for invalid inputs, assume all inputs are valid.
* The length of stdout must be the same as the length of stdin
* You may use any method to scramble the initial value, there is nothing off limits here.

*Example:*

> stdin: Hello There
>
> stout: loTeHle reh

*Note: a character in this context can be any valid ASCII character*

# Answer
> 3 votes
# CJam, ~~31~~ 27 bytes

```
l:I{mr[_I]{_,((,\f>3f<}/&}g

```

Test it here.

Same approach as my Mathematica answer. It keeps generating random permutations of the input, until the substring restriction is satisfied. I think this can be golfed a bit further.

# Answer
> 2 votes
# Mathematica, 89 bytes

```
(For[c=Characters@#;d=c,#⋂#2&@@(Partition[#,3,1]&/@{c,d})!={},d=RandomSample@c];d<>"")&

```

Generates random permutations until there is the permutation and the original have no common substring of length 3.

# Answer
> 0 votes
# CJam, 48 bytes

This is super huge. I am not sure if there are any good algorithms to do the task. This is just a brute force.

```
q:Q;{Q(+2/zs:R,3-_0>{,{RQI>3<#W>}fI}{;}?]1b0>}gR

```

Try it online here

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


# Question
Title: Print the content of /etc/passwd with constant creation limit
Rules/Objectives:

1. The program must be executed using `./program-name` without shell parameter/arguments.
2. the `program-name` may not contain any of characters in `/etc/passwd`, that is `acdepstw`
3. You may not open any other file, including own's source code, only `/etc/passwd` that should be read.
4. The program must print the content the `/etc/passwd` file.
5. Total score of the code equal to number of characters in the code added with constant literal declaration point. Each byte of constant declaration literal equal to `+100` to the score, after `3` declaration, each byte adds `+200` to the score. So the program should not contain too many constant declaration, but you may use predeclared constants (`M_PI` for example) or exploit the reflection of the function/variable/class name (function, variable or class names in this case are not considered as constant). Counting example:

```
int x = 12;       // counted as 1 byte (12 can fit to 8-bit)
x += 345;         // counted as 2 bytes (345 can fit to 16-bit)
#define Y 'e'     // counted as 1 byte ('e')
#define X Y       // counted as 0 (not considered as constant)
string s = "abc"; // counted as 3 bytes ("abc")
:foo              // counted as 3 bytes (:foo)
                  //  ^ EACH characters in atom (Elixir, etc)
                  //    or characters in symbol (Ruby, etc)
                  //    are counted as 1 byte constant
''                // counted as 0 (not considered as constant)
[0xAC, 12, 114]   // counted as 3 bytes (0xAC, 12, 114)

```

**Clarification**:

things that counted as constant literal:

* numbers, each byte, depends on size
* strings/symbols, each character = 1 byte
* chars, one byte

things that not counted as constant literal:

* class declaration
* function declaration
* variable declaration
* operators, brackets
* predefined symbols
* predefined constants

# Answer
# CJam, 49 characters + 0 bytes constant = 49

```
W[JCJFJIJBEIDHDHDHJBKGIJDHKCIHKFKFKJJA]Y/f+Afb:cg

```

It doesn't work in the online interpreter for obvious reasons.
> 2 votes

# Answer
# NodeJS - 179 characters + 1 byte constant declaration = 279

```
#!/usr/bin/env node
fs=function fs(){};fs=require(fs.name);x=function etc(){};y=function passwd(){};z='/';fs.readFile(z+x.name+z+y.name,function(err,data){console.log(''+data);});

```

Readable version:

```
#!/usr/bin/env node
fs = function fs(){};
fs = require(fs.name);
x = function etc(){};
y = function passwd(){};
z = '/'; // 1 declaration
fs.readFile(z+x.name+z+y.name,function(err,data){
  console.log(''+data);
});

```
> 0 votes

---
Tags: restricted-source, file-system
---


title: Automated Bulls and Cows Player

text:
# Question
Title: Automated Bulls and Cows Player
This is a code golf challenge to see the shortest implementation of an automated guesser in the pen and paper game bulls and cows.

The game works as follows:

A (usually 4 digit) secret code with only distinct integers 0-9 is picked by one player. A second player guesses codes that each receive a rank. This rank contains 1 bull for every digit that is correctly placed in the guess, and 1 cow for every digit in the guess that is in the secret code, but not in the correct location within the code.

The code should assume a format as follows:

* The combination will be a 4 digit number containing only distinct digits 0-9. (eg. 0123 is valid, 0112 is not)
* After each guess, you will be given a string as a response telling you how many bulls and how many cows are in your answer. It will be formatted as xByC, in which x is the number of bulls and y is the number of cows. (i.e. 4B0C means you have won). You can assume that a made-up method called "rateGuess", which takes your guess as a string will provide the response.

# Answer
# Pyth \- 11 bytes

This will *eventually* guess the correct answer. On average 2500 tries. Literally just takes random guesses no matter what the input is. Since you can't define rateGuess in pyth just takes (uneeded) input from stdin and outputs to stdout.

```
Ofql{T4^UT4

O         Pick random
 f        filter
  ql{T4   set length is four (checks for duplicates)
  ^  4    Caretesian product with 4 repeats
   UT     Unary range till 10

```
> 1 votes

---
Tags: code-golf, game
---


title: Shortest code special string sort

text:
# Question
Title: Shortest code special string sort
Objective/Restrictions:

1. May only be answered with programming language that has function syntax (or procedure, method, lambda, macro, statement grouping and labelling) .
2. Create a function with at least 2 argument/parameter, that generates an array containing 7 random strings, each string contains 3 characters, string may only contain alphanumeric characters `[a-zA-Z0-9]`. The number 7 and 3 passed into the function
3. Create a function that sort those strings using in special alphabetical ascending order: number first, alphabet later (lower-case then upper-case), for example:

```
1aa
2ac
aab
abc
Aab
bAA
BZ2

```
4. Create a function to print each string in descending order from the last one to the first one without mutating the ascending ordered array.
5. Call all three function and produce the correct output
6. Shortest code wins!

**Note**: if possible, give the ideone (this one also example implementation in Ruby) or any other online compiler link to test the correctness.

# Answer
# J - 70 chars

```
a=:'0123456789',6}.26|.a.{~65+i.58
b=:{&a@?@$&62
c=:/:62&#.@(a&i.)
d=:\:~

```

Usage: `d c b 7 3`
> 0 votes

# Answer
# Perl 5 - 181 chars

Ungolfed

```
@z=(0..9,a..z,A..Z);

sub d{
    map{ tr/A-Za-z/a-zA-Z/; $_ } @_
}

# n - number of strings to generate
# l - length of strings
sub a{
    ($n,$l) = @_;
    $a .= $z[rand@z] for 1..$n*$l;
    ($a=~/(.{$l})/g)
}

sub b{
    d(sort d(@_))
}

sub c{
    for(-$#_..0){
        print "$_[-$_]\n"
    }
}

c b a 7,3

```

Golfed

```
@z=(0..9,a..z,A..Z);sub d{map{tr/A-Za-z/a-zA-Z/;$_}@_}sub a{($n,$l)=@_;$a.=$z[rand@z]for 1..$n*$l;($a=~/(.{$l})/g)}sub b{d(sort d(@_))}sub c{for(-$#_..0){print"$_[-$_]\n"}}c b a 7,3

```
> 2 votes

# Answer
# Perl6 145 chars

```
#! /usr/bin/env perl6

my@a='a'..'z';
my@b='A'..'Z';
my@c=^10,@a,@b;

# first argument $^a is the number of strings
# second argument $^b is the length of the strings
sub a{@c.roll($^b).join xx$^a};

# sub b{@_.sort} # numbers then upper then lower
sub b{@_.sort(*.trans(@a,@b Z=>@b,@a))}; # swaps upper and lower

sub c{say @_.reverse};

c b a 7,3

```

```
my@a='a'..'z';my@b='A'..'Z';my@c=^10,@a,@b;sub a{@c.roll($^b).join xx$^a};sub b{@_.sort(*.trans(@a,@b Z=>@b,@a))};sub c{say @_.reverse};c b a 7,3

```

After removing the comments and all of the newlines, I get 145 characters.

If the requirements were changed so that the strings were sorted by numbers then uppercase then lowercase, I could remove 25 characters from the `b` subroutine.
> 1 votes

# Answer
# Ruby, 141

Fairly straightforward solution. Uses recursion to generate the random `String`s and makes use of `String#tr` to make the sorting short and sweet.

```
O=[*?0..?9]+[*?A..?Z]+[*?a..?z]
r=->i,s{i<1?[]:([O.sample(s)*'']+r[i-1,s])}
s=->a{a.sort_by{|e|e.tr"A-Za-z","a-zA-Z"}}
p=->a{puts a.reverse}

```

Usage: `p[s[r[7,3]]]`.
> 1 votes

# Answer
# Ruby - 339 chars

```
X=[*('0'..'9')]+[*('a'..'z')].map{|c|[c,c.upcase]}.flatten
Y={};v=0;X.each{|c|Y[c]=(v+=1)}
def x n;n.times.to_a.map{X[(rand()*X.length).to_i]}.join '';end
def y m,n;m.times.to_a.map{x n};end
def z r;r.sort{|a,b|v=-1;w=0;a.each_char{|c|d=b[v+=1];next if c==d;w=(Y[c]<Y[d]?-1:1);break};w};end
def a b;b.reverse_each{|c|puts c};end
a z(y 7,3)

```

verify here
> 0 votes

---
Tags: code-golf, restricted-source
---


# Question
Title: A fastest algorithm optimization challenge
This is my first experiment with an asymptotic complexity challenge although I am happy with answers entirely in code as long as they come with an explanation of their time complexity.

I have the following problem.

Consider tasks T\_1, ... T\_n and procs M\_1, ... , M\_m. Each task takes a certain amount of time to perform depending on the procs.

Each task also costs a certain amount to perform depending on the procs.

The tasks have to be done in strict order (they can't be done in parallel) and it takes time to change proc. A task can't be moved from one proc to another after it has been started.

Finally, each task must be completed by a certain time.

**the task**

The objective is to give an algorithm (or some code) that given five tables of the form above, minimizes the total cost to complete all the tasks while making sure all the tasks are completed by their deadlines. If this isn't possible we just report that it can't be done.

**score**

You should give the big Oh complexity of your solution in terms of the variables n, m and d, where d is the last deadline. There should be no unnecessary constants in your big Oh complexity. So O(n/1000) should be written as O(n), for example.

Your score is calculated simply by setting n = 100, m = 100 and d = 1000 into your stated complexity. You want the smallest score possible.

**tie breaker**

In the case of a tie, the first answer wins.

---

**added notes**

`log` in the time complexity of an answer will be taken base 2.

**score board**

* 10^202 from KSFT (**Python**) First submitted so gets the bounty.
* 10^202 from Dominik Müller (**Scala**)

# Answer
# Score: 10^202

I kinda wish we had LaTeX support now...

Since no one else has answered, I thought I'd try, even though is isn't very efficient. I'm not sure what the big O of it is, though.

I think it works. At least, it does for the only test case posted.

It takes input like in the question, except without the machine or task number labels, and with semicolons instead of line breaks.

```
import itertools
time = [[int(j) for j in i.split()] for i in raw_input().split(";")]
cost = [[int(j) for j in i.split()] for i in raw_input().split(";")]
nmachines=len(time)
ntasks=len(time[0])
switchtime = [[int(j) for j in i.split()] for i in raw_input().split(";")]
switchcost = [[int(j) for j in i.split()] for i in raw_input().split(";")]
deadline = [int(i) for i in raw_input().split()]
d={}
m=itertools.product(range(nmachines),repeat=ntasks)
for i in m:
    t=-switchtime[i[-1]][i[0]]
    c=-switchcost[i[-1]][i[0]]
    e=0
    meetsdeadline=True
    for j in range(ntasks):
        t+=switchtime[i[e-1]][i[e]]+time[i[e]][j]
        c+=switchcost[i[e-1]][i[e]]+cost[i[e]][j]
        e+=1
        if t>deadline[j]:
            meetsdeadline=False
    if meetsdeadline:
        d[(c,t)]=i
print min(d.keys()),d[min(d.keys())]

```
> 2 votes

# Answer
# Check All - Scala

Estimated score: 2m^n

I start from each machine and iterate over all the tasks to create all permutations through the tasks with different machines that meet the deadlines. Meaning if everything is in time I would get 9 possible paths with 2 machines and 3 tasks. (m^n) Afterwards, I take the path with the lowest cost.

Input is structured like this (--\> explains the parts and thus should not be entered):

```
M_1:5 3 5 4;M_2:4 2 7 5                 --> time
M_1:5 4 2 6;M_2:3 7 3 3                 --> cost
M_1:M_1}0 M_2}1;M_2:M_1}2 M_2}0         --> switch itme
M_1:M_1}0 M_2}2;M_2:M_1}1 M_2}0         --> switch cost
5 10 15 20                              --> deadlines

```

And here is the code:

```
package Scheduling

import scala.io.StdIn.readLine

case class Cost(task: Map[String, List[Int]])
case class Switch(machine: Map[String, Map[String, Int]])
case class Path(time: Int, cost: Int, machine: List[String])

object Main {

    def main(args: Array[String]) {
        val (machines, cost_time, cost_money, switch_time, switch_money, deadlines) = getInput

        val s = new Scheduler(machines, cost_time, cost_money, switch_time, switch_money, deadlines)
        s.schedule
    }

    def getInput(): (List[String], Cost, Cost, Switch, Switch, List[Int]) = {
        val cost_time = Cost(readLine("time to complete task").split(";").map{s =>
                val parts = s.split(":")
                (parts(0) -> parts(1).split(" ").map(_.toInt).toList)
            }.toMap)

        val cost_money = Cost(readLine("cost to complete task").split(";").map{s =>
                val parts = s.split(":")
                (parts(0) -> parts(1).split(" ").map(_.toInt).toList)
            }.toMap)

        val switch_time = Switch(readLine("time to switch").split(";").map{s =>
                val parts = s.split(":")
                (parts(0) -> parts(1).split(" ").map{t =>
                        val entries = t.split("}")
                        (entries(0) -> entries(1).toInt)
                    }.toMap)
            }.toMap)

        val switch_money = Switch(readLine("time to switch").split(";").map{s =>
                val parts = s.split(":")
                (parts(0) -> parts(1).split(" ").map{t =>
                        val entries = t.split("}")
                        (entries(0) -> entries(1).toInt)
                    }.toMap)
            }.toMap)

        val deadlines = readLine("deadlines").split(" ").map(_.toInt).toList

        val machines = cost_time.task.keys.toList

        (machines, cost_time, cost_money, switch_time, switch_money, deadlines)
    }
}

class Scheduler(machines: List[String], cost_time: Cost, cost_money: Cost, switch_time: Switch, switch_money: Switch, deadlines: List[Int]) {

    def schedule() {
        var paths = List[Path]()
        var alternatives = List[(Int, Path)]()

        for (i <- machines) {
            if (cost_time.task(i)(0) <= deadlines(0)) {
                paths = paths ::: List(Path(cost_time.task(i)(0), cost_money.task(i)(0), List(i)))
            }
        }

        val allPaths = deadlines.zipWithIndex.tail.foldLeft(paths)((paths, b) => paths.flatMap(x => calculatePath(x, b._1, b._2)))

        if (allPaths.isEmpty) {
            println("It is not possible")
        } else {
            println(allPaths.minBy(p=>p.cost).machine)
        }
    }

    def calculatePath(prev: Path, deadline: Int, task: Int): List[Path] = {
        val paths = machines.map(m => calculatePath(prev, task, m))
        paths.filter(p => p.time <= deadline)
    }

    def calculatePath(prev: Path, task: Int, machine: String): Path = {
        val time = prev.time + switch_time.machine(prev.machine.last)(machine) + cost_time.task(machine)(task)
        val cost = prev.cost + switch_money.machine(prev.machine.last)(machine) + cost_money.task(machine)(task)

        Path(time, cost, prev.machine :+ machine)
    }
}

```

I also had an idea to start from the back. Since you can always choose a machine with the lowest cost if the time is smaller then the difference from the previous deadline to the new one. But that wouldn't decrease the maximal runtime if the task with the better cost takes longer then the last deadline is timed.

# Update

======

Here is another set up. time:

```
M_1 2 2 2 7
M_2 1 8 5 10

```

cost:

```
M_1 4 4 4 4
M_2 1 1 1 1

```

switch time:

```
    M_1 M_2
M_1  0   2
M_2  6   0

```

switch cost:

```
    M_1 M_2
M_1  0   2
M_2  2   0

```

deadlines:

```
5 10 15 20

```

As input into my program:

```
M_1:2 2 2 7;M_2:1 8 5 10
M_1:4 4 4 4;M_2:1 1 1 1
M_1:M_1}0 M_2}2;M_2:M_1}6 M_2}0
M_1:M_1}0 M_2}2;M_2:M_1}2 M_2}0
5 10 15 20

```

This one has two solutions: time: 18, cost: 15, path: List(M\_1, M\_1, M\_1, M\_2) time: 18, cost: 15, path: List(M\_2, M\_1, M\_1, M\_1)

Which raises the question how this should be handled. Should all be printed or just one? And what if the time would be different? Is one with the lowest cost and no missed deadline enough or should it also be the one with the lowest time?
> 1 votes

# Answer
# O(m2n) = 1000000

I am sure this will be beaten, but I figure I will give this as a reference answer.

First, construct a Directed Acyclic Graph using the data. The graph will be built out of layers (kind of like a neural net, for those who are familiar with them). The first layer just has the start vertex, a placeholder. The next layer has m vertices, one for each machine. There is an edge from the start vertex to each of the m vertices, with path cost 0. These edges represent the initial choice of which machine to start on.

The next layer has another m vertices, again representing the m machines. This time, the number of edges from the previous layer to this layer is m\*m = m2. Each of these edges has a cost equal to running task 1 on the corresponding machine in the previous layer, plus switching to the corresponding machine in the next layer. It also has a second cost equal to the switching time (you can track these two costs are tuples).

Continue on in this way: we will have one layer for each task, plus the dummy "start" and "end" layers. Each of the first n-1 non-dummy layers has m2 edges going to the next layer. So, we have a DAG with O(m2n) edges, and O(mn) vertices. Now we simply perform a topological sort on the DAG, but every time a total time cost exceeds the relevant deadline, we delete the edge that would violate the deadline, and keep going. DAG topological sorting can be done in O(|E| + |V|), so we get the answer (or lack thereof) in O(m2n) time.
> 0 votes

---
Tags: fastest-algorithm
---


# Question
Title: Printing a "Hello World" one-liner in bourne shell without directly using white space char
I'm currently trying to solve a tricky/silly challenge and i've come to a dead end.

The challenge is basically to form a one-liner /bin/sh compatible command line which essentially outputs "Hello World" without directly typing White space or Tab characters in the command itself.

for example something like -

```
echo Hello World

```

would be invalid since we used white space twice in the command line.

Any ideas?

# Answer
One which works in `dash`, so I suppose it is `sh` compatible;

```
IFS=@;command=echo@Hello@World;$command

```
> 2 votes

---
Tags: code-challenge, restricted-source, hello-world
---


title: Magnetic Sculptures... in Space!

text:
# Question
Title: Magnetic Sculptures... in Space!
# Background

This is a continuation of my earlier challenge, where the task was to compute the shape of a sculpture obtained by dropping magnets into a huge pile.

Good news: the eccentric artist liked your work, and has another project for you. He still works with magnetic sculptures, but has decided to expand his art studio -- into **space**! His current method is to blast a single cube-shaped magnet into the orbit, and shoot other magnets at it to create a huge magnetic satellite.

# Input

Your input is a finite list of `0`s and `1`s, given either in the native list format of your language, or a string. It is interpreted as a "blueprint" of a work of art, and is processed in order from left to right as follows.

You start with a single magnet floating at some integer coordinate of the 2D plane, and keep adding more magnets as per the directives. The directive `0` rotates the entire sculpture 90 degrees in the counter-clockwise direction. In the case of the directive `1`, the artist finds the leftmost column of the sculpture, and shoots a new magnet to it from below. The new magnet sticks to the bottom-most existing magnet in the column, and becomes a part of the sculpture. Note that the magnet does *not* stick to other magnets in the neighboring column, unlike in the earlier challenge; its speed is now astronomical!

# Output

The artist wants to know whether the complete sculpture will fit into his garage (how he'll get it down from the orbit remains unclear). Thus, your output is the width and height of the sculpture, ordered from lower to higher. They can be given as a two-element list, a pair, or as a string separated by a comma.

# Example

Consider the input sequence

```
[1,0,1,1,0,1,0,0,1,1]

```

To process it, we start with one magnet floating in space:

```
#

```

The first directive is `1`, so we shoot a new magnet from below:

```
#
#

```

The next directive is `0`, so we rotate the sculpture:

```
##

```

The next two directives are `1,1`, which means we'll shoot two magnets to the leftmost column:

```
##
#
#

```

Then, we rotate again and shoot once, as directed by `0,1`:

```
#
###
#

```

Finally, we rotate twice and shoot twice:

```
  #
###
# #
#

```

The resulting sculpture has width `3` and height `4`, so we output `[3,4]`.

# Rules

You can give either a function or a full program. The lowest byte count wins, and standard loopholes are disallowed.

# Test Cases

```
[1,0,1] -> [2,2]
[1,0,1,1,0,1,0,0,1,1] -> [3,4]
[1,1,0,1,1,0,1,0,1,1] -> [4,5]
[1,1,0,1,1,0,1,0,1,1,0] -> [4,5]
[1,0,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1] -> [3,3]
[0,1,0,1,1,1,1,0,0,1,0,1,0,0,1,1,0,1,0,1,0,0,1,1,0,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1] -> [5,7]
[1,0,1,1,1,1,0,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,1,1,0,1,1,0,0,1,0,1,0,0,1,0,1,1,1,0,1,1,0,0,1,0,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0] -> [11,12]

```

# Answer
# Pyth: ~~34~~ 33 bytes

```
Sml{dCuS?+G,hhGtehGHm,_ekhkGQ],ZZ

```

Input is a list of ones and zeros, like in the question. Try it online: Pyth Compiler/Executor

### Explanation:

It's a one-on-one translation of the following **Python 2** code (**126 bytes**).

```
print sorted(map(len,map(set,zip(*reduce(lambda s,i:([[-b,a]for a,b in s],s+[[min(s)[0],min(s)[1]-1]])[i],input(),[[0,0]])))))

```

I create a list of coordinates of the single magnets. This is initialized with the magnet `[0,0]`. Then for each of the integers of the blueprint I manipulate the list in the following way. If the next integer is `0`, I rotate the sculpture by changing the coordinates for each magnet `[a,b]` to `[-b,a]` (basically multiplying with a rotation matrix). If the next integer is a `1`, I search for the minimal piece `[a,b]` (which is automatically the lowest magnet of the leftmost column) and append the magnet `[a,b-1]` to the list.

After all the input is processed, I create 2 sets (for removing duplicates), one for the x-values and one for the y values, and print the sizes of them in sorted order.

```
Sml{dCuS?+G,hhGtehGHm,_ekhkGQ],ZZ
                             ],ZZ  starting list G=[(0,0)]
      u                     Q],ZZ  for H in input(): manipulate G
       S                              Sort G after each manipulation
        ?          H                  G = ... if H==1 else ...
                    m,_ekhkG            [(-b,a) for a,b in G)] (rotate)
         +G,hhGtehG                     G+[(G[0][0],G[0][1]-1)]
                                        (G[0] is the lowest magnet in the leftmost column)
     C                             Zip the coords together
                                    (creates 2 lists, x- and y-coords)
 ml{d                              for each of those list compute number of unique values
S                                  sort and print

```

An **idea for improvement**: Using complex numbers as coords for the magnets. A rotation is just a multiplication by `j` and subtracting `j` from the lowest magnet in the leftmost column. Sadly finding this lowest leftmost magnet takes way too many chars in Python, not even talking of finding the rectangle.
> 8 votes

# Answer
# CJam, 48 bytes

```
S]l~{{)S/);Sa+S*a+_z,f{_N*@\+<}}{zW%}?}/_,\z,]$p

```

Test it here.

Expects input as a CJam-style array (i.e. spaces instead of commas) and will present the output similarly. If you want to use the test cases from the question directly, copy them straight into the input field (include the `->` and results) and use this test harness, which converts the lines to the correct input format (and discards the results):

```
qN/{S/0=","Ser}%{[

S]\~{{)S/);Sa+S*a+_z,f{_N*@\+<}}{zW%}?}/_,\z,]$p

}/

```

## Explanation

I'm just implementing the rules very literally. I'm keeping a grid with the current sculpture (as an array of strings), and then for each instruction I either rotate the grid, or I add a new block. The main tricks to save bytes are:

* Add to the bottom *row* from the *right*. This is completely equivalent. I'm just one rotation ahead, and since the grid starts out rotationally invariant, that doesn't matter.
* Use a space to represent occupied blocks and a newline character to represent empty blocks. So if you actually printed out the grid you wouldn't see a whole lot and it wouldn't even look rectangular. I'm doing this, because most array-based operators only do what you want if the grid element in question is wrapped in an array. And with `S` and `N` I have access to *strings* containing the space and newline character (i.e. the character wrapped in an array), instead of having to use, say, `1a` and `0a` to get an array containing a number.

Let's go through the code:

```
"Overall program structure:";
S]l~{{...}{...}?}/_,\z,]$p
S]                         "Push a string with a space and wrap it in an array.
                            This is the initial grid containing a single block.";
  l~                       "Read the input and evaluate it.";
    {           }/         "For each instruction in the input...";
     {...}{...}?           "Execute the first block if it's 1, the second if it's 0.";
                  _,       "Duplicate the resulting grid and get its length. This
                            is one of the dimensions.";
                    \      "Swap with the other copy of the grid.";
                     z,    "Zip/transpose it and get its length. This is the other
                            dimension of the grid.";
                       ]$p "Wrap both in an array, sort them, and print the result.";

"The rotation block is simple. A rotation is equivalent to two reflection operations
 along different axes. The simplest ones available are to transpose the grid (which
 is a reflection about the diagonal) and reversing the rows (which is a reflection
 about the horizontal). In CJam these are z for zip/tranpose and W% for reversing
 an array. So I simply put these together in the right order to get a counter-
 clockwise rotation:";
zW%

"Now the interesting part, adding new blocks and growing the grid. This part consists
 of two steps: appending a block to the rightmost block in the bottom row (allowing
 for empty blocks after it). And then potentially padding the rest of the grid with
 new empty cells if the bottom row got longer.";
)S/);Sa+S*a+_z,f{_N*@\+<}
)                         "Split off the bottom row.";
 S/                       "Split the row on occupied blocks.";
   );                     "Split off the final substring - this discards trailing
                           empty cells.";
     Sa+                  "Add a new substring containing an occupied block to the row.";
        S*                "Join all substrings together with spaces, putting back in
                           all the occupied blocks.";
          a+              "Wrap it in an array to add the row back onto the grid.";

 "At this point we need to make sure the grid is still rectangular. The easiest way
  (I found) is to find the maximum row length, add that many empty blocks to each
  line and then truncate the lines to that length.";

            _             "Duplicate the grid.";
             z,           "Zip/transpose it and get the length. This is the length
                           of the longest row in a ragged array.";
               f{       } "Map this block onto each row, passing in the target length.";
                 _N*      "Duplicate the target length and get a string of that many
                           empty cells.";
                    @\    "Pull up the row and then swap it with those empty cells.";
                      +   "Add the empty cells to the end of the row.";
                       <  "Truncate to the target length.";

```
> 7 votes

# Answer
# Matlab (92)

```
S=1;for d=input(''),if d,S(find(S(:,1),1,'last')+1,1)=1;else,S=rot90(S);end;end,sort(size(S))

```

Standard input is used. Data should be introduced in the form `[1,0,1,1,0,1,0,0,1,1]`.

Ungolfed:

```
S = 1; %// initial magnet
for d = input('') %// get directives, and pick them sequentially
    if d %// if directive is 1
        S(find(S(:,1),1,'last')+1,1) = 1; %// add 1 after lowest 1 in column 1. Grow if needed
    else %// if directive is 0
        S = rot90(S); %// rotate counterclockwise. Handy Matlab built-in function
    end
end
sort(size(S)) %// display size sorted

```

Example run:

```
>> clear all
>> S=1;for d=input(''),if d,S(find(S(:,1),1,'last')+1,1)=1;else,S=rot90(S);end;end,sort(size(S))
[1,0,1,1,0,1,0,0,1,1]
ans =
     3     4

```
> 4 votes

# Answer
# Python - 211

```
import numpy as n
p=input()
q=len(p)
a=n.zeros([2*q+1]*2)
a[q,q]=1
for i in p:
 if i:x=a[:,n.where(a.any(0))[0][0]];x[len(x)-n.where(x[::-1])[0][0]+1]=1
 else:a=n.rot90(a)
z=a[:,a.any(1)]
print z[a.any(0)].shape

```
> 1 votes

# Answer
# CJam, 47 bytes

```
1]]q~{{0f+(W%_1#(1tW%a\+z{1b},}{W%}?z}/),\,)]$p

```

This takes CJam styled (space separated instead of comma) array input from STDIN and prints the result to STDOUT.

Example:

```
[1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1]

```

gives

```
[3 3]

```

output.

Explanation to follow after I am convinced that this cannot be golfed further.

Try it online here
> 0 votes

---
Tags: code-golf, grid
---