title: Extreme Whitewater Canoeing

text:
# Question
Title: Extreme Whitewater Canoeing
You are paddling a canoe down a fairly fast whitewater river. Suddenly, your paddles explode, and you find yourself in a dangerous situation hurtling down a river rapid without any paddles. Luckily, you still have your programming skills, so you decide to carve a program on the side of your canoe to help you survive the rapids. However, there is not much surface area on the side of the canoe to write your program with, so you must make the program as short as possible.

The river can be represented as an 8 by 16 grid. We will label the columns with the numbers `0` to `7` and the rows with the numbers `0` to `15`.

```
        y
--------15
--------14
--------13
--------12
--------11
--------10
--------9
--------8
--------7
--------6
--------5
--------4
--------3
--------2
--------1
--------0
01234567
x

```

*Above: A completely calm, ordinary river with no obstructions. Naturally, this is not the river you are on.*

You begin at the coordinate (4, 0) and from there move uncontrollably up the river (i.e. the vector `(0,1)`) until you hit a rock (represented by an `o` in these examples). When you hit a rock, you will have a 55% chance of moving past the rock to the left (i.e. the vector `(-1,1)`) and a 45% chance of moving past the rock to the right (i.e. the vector `(1,1)`). If the canoe is on the far left or right columns, it will always move towards the centre. If there are no rocks, it will move straight upwards.

```
        y
----x---15
----xo--14
-o--x---13
----x---12
---ox---11
---x----10
---xo---9
---ox---8
----xo--7
-----x--6
----ox--5
-o--x---4
----x---3
----xo--2
----x---1
----x---0
01234567

```

*Above: A possible route the canoe might take, represented using the character `x`*

Given the map of the river, write a program that will output the probability of the canoe finishing at a given column.

Accept input in whichever method is convenient for your program (e.g. STDIN, command line argument, `raw_input()`, reading from a file, etc). The first part of the input is a single integer from 0 to 7, representing the column the program will find the probability for. Following that is a list of tuples in the form `x,y` representing the position of the stones.

An example:

Input:

```
4 4,1 5,5 3,5

```

This would indicate a river with rocks at the positions (4,1), (5,5), and (3,5), and asks for the probability of the canoe ending at the 4th column.

Output:

```
0.495

```

Note that in this example, the positions of the rocks were symmetrical, allowing the problem to be solved with a binomial distribution. This won't always be the case!

Also, the river will always be crossable. That is, there will never be two rocks that are positioned adjacent to each other horizontally. See Glenn's comment for an example of an impossible case.

This is code golf, so lowest number of characters wins. Feel free to ask questions in the comments if the specification isn't clear.

# Answer
> 4 votes
### GolfScript, 105 characters

```
~](\2/:A;8,{4=}%15,{:B;{20*}%A{~B={[\\,.1,*\[2$=..20/9*:C-\~)C]+(1,\+1,6*2$8>+]zip{{+}*}%.}*;}/}/=20-15?*

```

A GolfScript version which became much longer than intended - but each attempt with a different approach was even longer. The input must be given on STDIN.

Example:

```
> 4 4,1 5,5 3,5
99/200

```

*Annotated code:*

```
# Evaluate the input
#  - stack contains the first number (i.e. column)
#  - variable A contains the rock coordinates (pairs of X y)
#    where X is an array of length x (the coordinate itself)
~](\2/:A;

# Initial probabilities
#  - create array [0 0 0 0 1 0 0 0] of initial probabilities
8,{4=}%

# Loop over rows
15,{:B;           # for B = 0..14
  {20*}%          #   multiply each probability by 20
  A{              #   for each rock
    ~B={          #     if rock is in current row then
                  #       (prepare an array of vectors [v0 vD vL vR]
                  #       where v0 is the current prob. before rocks,
                  #       vD is the change due to rocks,
                  #       vL is a correction term for shifting out to the left
                  #       and vR the same for the right side)
      [\\         #       move v0 inside the array
      ,           #       get x coordinate of the rock
      .1,*        #       get [0 0 ... 0] with x terms
      \[2$=       #       get x-th item of v0
      ..20/9*:C-  #       build array [0.55P -P 0.45P]
      \~)C]+      #       and append to [0 0 ... 0]
      (1,\+       #       drop the leftmost item of vD and prepend [0] again
                  #       which gives vL
      1,6*2$8>+   #       calculate vR using the 8th item of vD
      ]           #
      zip{{+}*}%  #       sum the columns of this list of vectors
      .           #       dummy dup for end-if ;
    }*;           #     end if
  }/              #   end for
}/                # end for

# take the n-th column and scale with 20^-15
=
20-15?*

```

# Answer
> 11 votes
# Ruby, ~~204~~ ~~191~~ 172 characters

```
c,*r=gets.split
o=[0]*8
s=->x,y,p{y>14?o[x]+=p :(r.index("#{x},#{y+=1}")?(x<1?s[x+1,y,p]:(x>6?s[x-1,y,p]:(s[x-1,y,p*0.55]+s[x+1,y,p*0.45]))):s[x,y,p])}
s[4,0,1]
p o[c.to_i]

```

It recursively simulates all possibly outcomes while keeping track of each individual outcome's probability, then it adds that probability to a cumulative counter when `y == 15`.

Fancy tricks:

* `c,*r=gets.split` \- the "splat" operator (`*`) takes all the remaining elements of `gets.split` and sticks them in the `r` array
* ~~`next {something} if {condition}`: essentially equivalent to~~

~~```
if {condition}
    {something}
    return
end

```~~

~~"Discovered" by evolving from `if condition; something; return; end` to `return something if condition` to `break something if condition`, and then I figured I would try a shorter "loop operator" to see if it would work (which it did, of course).~~
* Thanks to @MartinBüttner for suggesting to use chained ternary operators (which ended up becoming the enormous third line in the golfed code above) and eliminating the above point (which saved 19 (!) characters).

I did use a somewhat fancy trick with those, though: I realized that `s[foo],s[bar]` doesn't work in Ruby for two method calls in one statement. So at first I changed it to `(_=s[foo],s[bar])` (a dummy variable), but then I realized I could just add and throw away the return values: `s[foo]+s[bar]`. This only works because calls to `s` will only ever "return" other calls to `s` or a number (`o[x]+=p`), so I don't have to worry about checking for `nil`.
* Other various optimizations: `p` instead of `puts` for printing numbers, `<1` instead of `==0` (since the canoe never leaves the river) and similar comparisons elsewhere, `[0]*8` for initial probabilities as Ruby's numbers are always "pass by value"

Ungolfed:

```
column, *rocks = gets.chomp.split
outcomes = Array.new(8, 0)
simulate = -> x, y, probability {
    if y == 15
        outcomes[x] += probability
    elsif rocks.index("#{x},#{y + 1}")
        case x
        when 0 then simulate[x + 1, y + 1, probability]
        when 7 then simulate[x - 1, y + 1, probability]
        else
            simulate[x - 1, y + 1, probability * 0.55]
            simulate[x + 1, y + 1, probability * 0.45]
        end
    else
        simulate[x, y + 1, probability]
    end
}
simulate[4, 0, 1.0]
p outcomes
puts outcomes[column.to_i]

```

# Answer
> 5 votes
## C# ~~418~~ 364bytes

Complete C# program expecting input from STDIN. Works by reading the rocks into an array of all locations in the river, effectively creating a map, and then it just performs 16 iterations of moving probabilities around an 8-width decimal array before outputting the result.

```
using C=System.Console;class P{static void Main(){var D=C.ReadLine().Split();int i=0,j=D.Length;var R=new int[8,16];var p=new decimal[8];for(p[4]=1;--j>0;)R[D[j][0]-48,int.Parse(D[j].Substring(2))]=1;for(;i<16;i++){var n=new decimal[j=8];for(;j-->0;)if(R[j,i]>0){n[j<1?1:j-1]+=p[j]*0.55M;n[j>6?6:j+1]+=p[j]*0.45M;}else n[j]+=p[j];p=n;}C.WriteLine(p[D[0][0]-48]);}}

```

Formatted code:

```
using C=System.Console;

class P
{
    static void Main()
    {
        var D=C.ReadLine().Split();
        int i=0,j=D.Length;
        var R=new int[8,16];
        var p=new decimal[8];

        for(p[4]=1;--j>0;) // read rocks into map (R)
            R[D[j][0]-48,int.Parse(D[j].Substring(2))]=1;

        for(;i<16;i++) // move up the river
        {
            var n=new decimal[j=8];
            for(;j-->0;)
                if(R[j,i]>0)
                { // we hit a rock!
                    n[j<1?1:j-1]+=p[j]*0.55M;
                    n[j>6?6:j+1]+=p[j]*0.45M;
                }
                else
                    n[j]+=p[j];
            p=n; // replace probability array
        }

        C.WriteLine(p[D[0][0]-48]); // output result
    }
}

```

# Answer
> 2 votes
## PHP, 358

Using brainpower to determine the possible paths and their probabilities is hard, and would probably require more code than simply simulating 1,000,000 canoe accidents. *Oh, the humanity!*

```
define('MX',7);
define('MY',16);
define('IT',1000000);
error_reporting(0);

function roll(){return rand()%100 > 44;}

function drift($rocks,$print=false) {
    for($px=4,$py=0;$py<MY;$py++) {
        if(isset($rocks[$px][$py])){
            if(roll()) $px--;
            else $px++;
        }
        else if($px==0) $px++;
        else if($px==MX) $px--;
        if($print) {
            for($i=0;$i<MX;$i++){
                if($i==$px) echo 'x';
                else if(isset($rocks[$i][$py])) echo 'o';
                else echo '-';
            }
            echo " $py\n";
        }
    }
    return $px;
}

$input = $argv[1];
$tmp = explode(' ',$input);
$end_target = array_shift($tmp);
$rocks = array();
array_map(function($a) use(&$rocks) {
    list($x,$y) = explode(',',$a);
    $rocks[$x][$y]=1;
}, $tmp);

$results=array();
for($i=0;$i<IT;$i++) {
    $results[drift($rocks)]++;
}

drift($rocks, true); // print an example run

foreach($results as $id=>$result) {
    printf("%d %0.2f\n", $id, $result/IT*100);
}

```

Example:

```
php river.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
----x-- 0
---xo-- 1
---x--o 2
--xo--- 3
--x---- 4
--x--o- 5
--x---- 6
--x---- 7
--x---- 8
--x---- 9
--x---- 10
--x---- 11
--x---- 12
--x---- 13
--x---- 14
--x---- 15
4 49.53
2 30.18
6 20.29

```

Golfed:

```
<? function d($r){for($x=4,$y=0;$y<16;$y++){if(isset($r[$x][$y])){if(rand()%100>44)$x--;else $x++;}elseif($x==0)$x++;elseif($x==7)$x--;}return $x;}$t=explode(' ',$argv[1]);$e=array_shift($t);$r=array();array_map(function($a)use(&$r){list($x,$y)=explode(',',$a);$r[$x][$y]=1;},$t);$c=0;for($i=0;$i<1000000;$i++){if(d($r)==$e)$c++;}printf("%.4f", $c/1000000);

```

This version does not do any pretty printing and outputs the float probability of the canoe landing at the specified position.

```
# php river_golf.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.4952

```

# Answer
> 2 votes
## PHP, 274

I can't read/write GolfScript to save my life, but glancing over @Howard's submission pointed me in a better direction than simply simulating 1 million canoe accidents.

Starting with an array of probabilities for starting positions we can simply split those numbers each time a rock is encountered.

```
function psplit($i){ return array(.55*$i,.45*$i); }
function pt($a) {
    foreach($a as $p) {
        printf("%1.4f ", $p);
    }
    echo "\n";
}

$input = $argv[1];
$tmp = explode(' ',$input);
$end_target = array_shift($tmp);
$rocks = array();
array_map(function($a) use(&$rocks) {
    list($x,$y) = explode(',',$a);
    $rocks[$x][$y]=1;
}, $tmp);

$state = array(0,0,0,0,1,0,0,0);
pt($state);
for($y=1;$y<16;$y++){
    for($x=0;$x<8;$x++){
        if(isset($rocks[$x][$y])){
            echo('   o   ');
            list($l,$r)=psplit($state[$x]);
            $state[$x]=0;
            $state[$x-1]+=$l;
            $state[$x+1]+=$r;
        } else { echo '   -   '; }
    }
    echo "\n";
    pt($state);
}

```

Example Output:

```
# php river2.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000
   -      -      -      -      o      -      -      -
0.0000 0.0000 0.0000 0.5500 0.0000 0.4500 0.0000 0.0000
   -      -      -      -      -      -      o      -
0.0000 0.0000 0.0000 0.5500 0.0000 0.4500 0.0000 0.0000
   -      -      -      o      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.2475 0.4500 0.0000 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.2475 0.4500 0.0000 0.0000
   -      -      -      -      -      o      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000
   -      -      -      -      -      -      -      -
0.0000 0.0000 0.3025 0.0000 0.4950 0.0000 0.2025 0.0000

```

Golfed:

```
<? $t=explode(' ',$argv[1]);$e=array_shift($t);$r=array();foreach($t as $n){list($j,$k)=explode(',',$n);$r[$j][$k]=1;}$s=array(0,0,0,0,1,0,0,0);for($y=1;$y<16;$y++){for($x=0;$x<8;$x++){if(isset($r[$x][$y])){$s[$x-1]+=$s[$x]*.55;$s[$x+1]+=$s[$x]*.45;$s[$x]=0;}}}echo $s[$e];

```

Example run:

```
# php river2_golf.php "4 4,1 5,5 3,3 6,2 9,4 12,3 13,5"
0.495

```

# Answer
> 2 votes
# Haskell, 256 bytes

```
import Data.List
m=map;v=reverse
a p n x=take n x++(x!!n+p:drop(n+1)x)
l=abs.pred
o[_,n]s=n#(s!!n)$s
n#p=a(11*p/20)(l n).a(9*p/20)(7-(l$7-n)).a(-p)n
b=0:0:0:0:1:b
k(c:w)=(foldl1(.)$m o$v$sort$m(v.read.('[':).(++"]"))w)b!!read c
main=getLine>>=print.k.words

```

Here is a very ungolfed version along with some tricks that were used:

```
import Data.List

-- Types to represent the distribution for the canoe's location
type Prob = Double
type Distribution = [Prob]

-- Just for clarity..
type Index = Int

-- An Action describes some change to the probability distribution
-- which represents the canoe's location.
type Action = Distribution -> Distribution

-- Helper to add k to the nth element of x, since we don't have mutable lists.
add :: Index -> Prob -> Action
add n k x = take n x ++ [p] ++ drop (n + 1) x
    where p = k + x!!n

-- A trick for going finding the index to the left of n,
-- taking the boundary condition into account.
leftFrom n = abs (n - 1)

-- A trick for getting the other boundary condition cheaply.
rightFrom = mirror . leftFrom . mirror
    where mirror = (7 -)

-- Make the action corresponding to a rock at index n.
doRock :: Index -> Action
doRock n p = (goLeft . goRight . dontGoForward) p
    where goLeft  =  (leftFrom n) `add` (p_n * 11/20)
          goRight = (rightFrom n) `add` (p_n * 9/20)
          dontGoForward =  (at n) `add` (-p_n)
          p_n = p!!n
          at = id

initialProb = [0,0,0,0,1,0,0,0]

-- Parse a pair "3,2" ==> (3,2)
readPair :: String -> (Index,Index)
readPair xy = read $ "(" ++ xy ++ ")"

-- Coordinate swap for the sorting trick described below.
swap (x,y) = (y,x)

-- Put it all together and let it rip!
main = do
    input <- getLine
    let (idx : pairs) = words input
    let coords = reverse . sort $ map (swap . readPair) pairs
    let rockActions = map (doRock . snd) coords
    let finalProb = (foldl1 (.) rockActions) initialProb
    print $ (finalProb !! read idx)

```

The last trick I used was to note that you can act as if rocks in a single row are actually separated by some infinitesimal amount. In other words, you can apply the probability distribution transformer for each rock in the same row sequentially and in whatever order you want, rather than applying them all simultaneously. This only works because the problem disallows two horizontally adjacent rocks.

So the program turns each rock's location into a probability distribution transformer, ordered by the rock's y coordinate. The transformers are then just chained in order and applied to the initial probability distribution. And that's that!

# Answer
> 2 votes
# Haskell, 237

I just hope the canoe comes with ghc installed...

The trick with the infinite list is stolen from Matt Noonan, kudos to him!

```
import Data.List
r=reverse
(a:b:x)%0=0:a+b:x
x%7=r(r x%0)
x%n=take(n-1)x++(x!!(n-1)+x!!n*0.55:0:x!!(n+1)+x!!n*0.45:drop(n+2)x)
q=0:0:0:0:1:q
u(w:x)=(foldl(%)q.map last.sort.map(r.read.('[':).(++"]"))$x)!!read w
main=interact$show.u.words

```

I hope I got the logic right, but Matt's example `"5 4,4 1,5 5,3 3,6 2,9 4,12 3,13"` yields `0.5613750000000001` and OP's example `"4 4,1 5,5 3,5"` yields `0.49500000000000005`, which seems to be correct apart from some floating point errors.

Here it is in action:

```
>>> echo 5 4,4 1,5 5,3 3,6 2,9 4,12 3,13 | codegolf
0.5613750000000001

```

# Answer
> 2 votes
# Perl 169 Bytes

Reads from STDIN.

```
$_=<>;s/ (.),(\d+)/$s{$1,$2}=1/eg;/./;$x{4}=1.0;for$y(1..15){for$x(0..7){if($s{$x,$y}){$x{$x-1}+=$x{$x}*($x%7?.55:1);$x{$x+1}+=$x{$x}*($x%7?.45:1);$x{$x}=0}}}print$x{$&}

```

Pretty straight forward, implicitly uses columns -1 and 8 to smoothen border cases. Probabilities can safely be propagated to each next level because there arent any adjacent stones, thus a single run suffices.

---
Tags: code-golf, graph-theory, probability-theory
---


# Question
Title: Return the last color of the input in Manufactoria
This puzzle is the next in my series of Manufactoria challenges.

# Background

Manufactoria is a game / two-dimensional programming language. The player must create programs that will manipulate a queue to arrive at the desired output. It is easy to learn but hard to master, so it lends itself to creating a wide variety of challenges. If you don't know what I am talking about, I advise that you play the first few tutorial levels of the game.

# Challenge

Your challenge is to create a machine that will return the very last element of the input string. To make this even more challenging, the input string can be *any* combination of *all four colors*.

The official custom level to be used is found here:

http://pleasingfungus.com/Manufactoria/?ctm=Last\_in\_Line!;IN:\_a\_series\_of\_colors\_OUT:\_the\_very\_last\_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0;

This week's challenge is mostly focused on the idea of compression. I chose this challenge to require a huge mess of conveyor belts. The fact that all four colors appear in the input means that it is very hard to store information.

Although I did not attempt compression, my first working prototype had 114 parts and fit into the 13x13 space with almost no room to spare.

# Scoring

The goal of this challenge is to use a few parts as possible. The score is the number of parts placed, and the lowest score wins.

Although there are only 8 test cases, your creation should be able to theoretically function under any test case. The test cases provided are for debugging purposes.

# Examples

```
in:  byrgyrbyrrgry
out: y
in:  ggryybrryr
out: r
in:         #don't you love degenerate cases?
out:
in:  gyrbrygbrygbyrb
out: b

```

# Answer
# 65 parts

To be honest I couldn't even come up with the idea of putting pairs of readers directly against each other until I saw it in the already-posted solutions. But later I started to come up with a lot of optimization tricks.

Link
> 6 votes

# Answer
## 73 69 parts

Organizing as a strip seems to save a lot of devices. Left-to-right, the columns are "last color was yellow", "last color was blue", two columns of devices, "last color was red", "last color was green", and "all done".

http://pleasingfungus.com/Manufactoria/?lvl=35&code=c10:8f2;q11:6f5;i11:7f0;p11:8f5;i12:6f4;q12:7f5;p12:8f5;c13:8f0;i10:7f6;i10:6f6;i13:6f7;i13:7f7;c9:6f3;c9:7f3;c9:8f3;q11:9f3;q12:9f3;c9:9f2;i10:9f3;i13:9f2;g12:12f3;c10:10f1;c13:11f1;c13:10f1;c10:11f1;p12:2f3;q12:3f3;c13:2f3;i13:3f5;c11:2f0;c10:2f3;i10:3f1;c11:3f0;c9:3f3;p11:11f3;p12:10f3;i11:10f1;i12:11f5;c14:3f3;c14:6f3;c14:7f3;c14:8f3;c14:9f0;i14:4f5;c14:5f3;i13:4f5;c13:5f3;y11:12f3;c11:13f2;c9:4f3;c9:5f3;c10:4f3;c10:5f3;b11:5f1;c11:4f2;c12:4f2;c15:4f3;c15:5f3;c15:6f3;c15:8f3;c15:7f3;c15:9f3;c15:10f3;c15:11f3;c15:12f3;c15:13f0;c14:13f0;c13:13f0;r12:5f1;&ctm=Last\_in\_Line!;IN:\_a\_series\_of\_colors\_OUT:\_the\_very\_last\_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;
> 7 votes

# Answer
### 99 90 84 81 Parts

Yes - this is a mess of conveyer belts. But finally considerably less than 100 parts - also thanks to Volatility.

http://pleasingfungus.com/Manufactoria/?lvl=33&code=p12:9f3;i12:2f1;c11:9f0;c9:8f2;c10:8f2;i11:8f7;i12:8f5;i12:4f5;i12:5f5;c12:6f3;i12:7f1;i13:9f3;c14:8f3;i13:8f3;q12:3f3;q15:4f7;p15:5f7;c14:5f3;i14:6f1;i14:7f1;i13:7f0;i13:6f0;i13:5f4;c11:7f3;c10:7f2;c15:7f0;c16:5f3;c16:7f0;c11:2f3;c13:2f0;c14:2f0;c15:2f0;c16:3f1;c16:4f1;c16:2f0;c17:4f0;c17:5f1;c17:7f1;c17:8f1;c8:8f1;c8:7f1;c8:5f1;c8:4f2;c16:6f3;c17:6f1;g15:6f0;c8:6f1;c8:9f1;c8:10f1;c9:9f1;c9:10f0;p10:9f7;q10:10f3;b10:11f2;c11:10f2;c11:11f2;i12:10f5;c12:11f3;c13:10f1;c13:11f0;c16:10f2;c17:9f1;c17:10f1;c12:12f3;p14:9f7;q14:10f7;r14:11f0;c15:9f1;c15:8f1;c15:10f2;c11:3f3;q11:4f3;p11:5f3;y11:6f2;c10:5f3;c10:6f3;c9:4f2;c10:4f2;c13:3f3;c13:4f2;c14:4f2;&ctm=Last\_in\_Line!;IN:\_a\_series\_of\_colors\_OUT:\_the\_very\_last\_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0;
> 4 votes

# Answer
## 91 88 parts

The upper left gadget handles green/blue, the lower right gadget handles red/yellow.

http://pleasingfungus.com/Manufactoria/?lvl=35&code=q8:6f5;c8:7f2;c9:5f2;p9:6f4;q9:7f2;i10:5f7;c10:6f0;p10:7f3;i12:6f6;i13:6f6;c13:11f0;i14:6f6;p14:10f3;r14:11f0;c15:6f0;p15:9f6;q15:10f0;c15:11f2;c16:6f0;q16:9f5;c16:10f0;i16:11f3;c17:6f0;c17:7f1;c17:8f1;c17:9f1;c17:11f1;b10:8f2;i11:8f7;c12:4f3;c12:7f3;c12:8f3;i12:9f5;i12:10f1;c12:11f3;i12:12f5;c14:3f3;c14:4f3;c9:4f2;i10:4f7;i11:4f7;c7:8f2;i8:8f3;c9:8f3;c9:9f2;c10:9f2;i11:9f7;i13:9f7;c14:9f2;c13:10f0;i11:10f6;c10:10f0;c9:10f0;c8:10f1;c8:9f1;c15:7f0;i14:7f6;i13:7f6;c15:8f0;i14:8f6;c13:8f3;c8:4f2;c16:7f0;g8:5f1;y16:8f1;q12:3f7;c13:2f3;i13:3f5;c13:4f3;i11:3f6;c10:3f3;p12:2f7;c11:2f3;c7:6f3;c7:7f3;c11:5f3;i11:6f6;c11:7f3;c12:5f3;c13:5f3;c14:5f3;c17:10f1;c11:11f3;c11:12f2;c13:12f2;c14:12f2;c15:12f2;c16:12f1;&ctm=Last\_in\_Line!;IN:\_a\_series\_of\_colors\_OUT:\_the\_very\_last\_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0;
> 4 votes

# Answer
# 75 parts

http://pleasingfungus.com/Manufactoria/?lvl=34&code=c11:9f1;q11:11f3;p11:12f7;g11:13f2;i12:9f1;i12:10f1;i12:11f1;i12:12f5;p13:9f7;i13:11f1;i13:12f5;i14:11f0;q13:10f3;c14:9f0;c15:11f0;c14:12f1;i14:10f4;c15:9f3;c15:10f3;c10:12f1;i10:11f0;i10:10f0;c10:9f1;c9:11f1;c9:10f1;c9:9f1;b13:13f0;c11:10f0;c9:6f2;c9:7f1;c9:8f1;c10:5f3;i10:6f5;i10:7f1;c10:8f2;r11:4f2;i11:5f0;i11:6f4;q11:7f5;p11:8f1;c12:4f3;i12:5f1;i12:6f5;i12:7f5;i12:8f5;y13:4f0;p13:5f1;q13:6f5;c13:7f2;c13:8f3;c14:5f3;i14:6f5;i14:7f5;c14:8f3;c15:6f3;c15:7f3;c15:8f3;p12:2f7;q12:3f3;c11:3f0;i14:3f5;c13:3f2;c15:3f3;c15:4f3;c15:5f3;c14:4f3;c10:4f3;c9:5f3;c9:4f3;c9:3f3;c10:2f3;c14:2f3;c13:2f2;c11:2f0;i10:3f1;&ctm=Last\_in\_Line!;IN:\_a\_series\_of\_colors\_OUT:\_the\_very\_last\_color;byrgyrbyrrgry:y|bbrrbryyyrrbr:r|ggryybrryr:r|b:b|:|gyrbrygbrygbyrb:b|brbrbryyrygbrg:g|rrrrrrrrrr:r;13;3;0;

Yeah, I know, it's six parts more than Keith Randall's solution, but what can I say? I like the symmetry.
> 2 votes

---
Tags: code-golf, manufactoria
---


title: Expression that equals its length

text:
# Question
Title: Expression that equals its length
Given a number, find an expression in words equaling that number, with a length of that number.

Thus, to an input of `15`, you might output `sixteen minus one`, which has fifteen characters (not counting spaces). If multiple solutions exist, print whichever you want. If none exist, print `impossible`

Use only the operators `plus`, `minus`, `times`, and `divided by`. Operators are evalutated left to right.

Format 1234 as `one thousand two hundred thirty four`. Note the absence of "and", and that there are no dashes or commas.

The input and all numbers used in the output must be positive integers less than 10,000.

The input will be given as a command line argument. Print to standard output.

## Examples

```
1: impossible
4: four
7: impossible
13: eight plus five (you could also output "five plus eight")
18: one plus two times six (note that operators are evaluated from left to right)
25: one thousand divided by forty

```

# Answer
> 1 votes
# Javascript, 434 characters

```
function f(s){return s.replace(/[A-Z]/g,function(t){return{O:'one',T:'two',H:'three',F:'four',I:'five',S:'six',E:'seven',G:'eight',N:'nine',Z:'ten',P:' plus ',M:' minus ',U:' times ',X:'teen',A:'thir',B:'twenty'}[t]})}A='TPAX|GeenMT|EXUO|B FMS|F|GPSUT|ZPHPG|BPFMT|AXPFPS|BPGMF|EUOPGeen|NPT|B GMSPI|GPI|EPE'.split('|');O=26640;function S(n){return n<15&&!(O>>n&1)?'Invalid':f(A[v=n%15])+(new Array(~~(n/15)+(O>>v&1))).join(f('PSPN'))}

```

Yields a function in the global namespace, `S`, that accepts any non-negative integer and returns the required string, or `"Invalid"` if the integer cannot be represented within the specifications.

I would appear to have used the same approach as @optokopper, having made the same observation that `"plus six plus nine"` is the shortest possible padding string, and that all numbers greater than 27 can be expressed by concatenating one of 15 base strings to repeated copies of the pad.

Having said that, the tables of base strings we use differ, and my solution relies on bit twiddling and the remainder operator (`%`). It also includes `"multiplied by"` as a possible operation. And naturally the mechanics of how the strings are constructed are completely different due to the dissimilarity between C and Javascript.

That's my best attempt, at any rate. ;)

Special thanks to @chiru, whose discussion of which numbers were achievable helped prevent fruitless searching.

# Answer
> 22 votes
# JS, 1719/1694

# Theory

Unfortunately, the rule set that you provide may not be a wise decision from a mathematical point of view. In fact, using a smaller subset of rules, you can find a solution for every number in the given interval

>

except for

>

for which there is no solution.

## Reduced rule set

Consider the following subet of rules:

* Use only the operators `plus`, `minus` and `times`.
* You **don't need to implement** multiple occurrences of `plus` or `minus` in your expressions.
* You **don't need to implement** neither `division` nor `operator associativity` (as their solution set is already covered by the first rule).

The reason why this works is that, as you discussed earlier with @Qwix, you allow **boring answers**, that is, expressions that end in the regular expression `( times one)+$`. Allowing this, each number in the given interval will have a solution.

When you replied in one of your comments,

> @Qwix Yes; boring answers are acceptable, although that one doesn't work for 104, 105, 106, 107, 108, 109, 110, or 111. –

you were absolutely right: This does not work when you're trying to build your expression starting with the numbers themselves, i.e. `one hundred four times one times one …` or any other of those numbers.

If however, your expression starts with an expression whose evaluation equals one of the given numbers, you're out of luck. For example, note that `17 + 87` is indeed `104`, so we could write `104` as:

```
104: seventeen plus eighty seven times one times one times one times one times one times one times one times one times one times one

```

To see that this subset works, save this file as **`num.js`** and make sure that SpiderMonkey, a JavaScript engine for command lines, is installed on your system.

## The algorithm

* Let us define the property `K` for positive integers as the state of the number having `N` letters and having a value of `N`.
* Let us further define the property `F` for an expression as the state of its word conversion being `8k`-times shorter than its evaluation with k ∈ ℕ. `F` stands for "fillable" and describes whether or not we can fill the word conversion of the expression with expressions of length 8 (i.e. `" times one"`) such that the resulting expression might get the property `N`.

We then proceed as follows:

* Convert the input number to words.
* Check if the input number has property `K`.
    + If it does, return the words (`4` is the only number with this property, unfortunately).
    + If it doesn't, proceed.
* For all two-operand expressions (additions, subtractions and multiplications in this order) that result in the input number, check if their evaluation has property `K`.
    + If it does, return the words.
    + If it doesn't, check if the two-operand expression has property `N`.
        - If it does, fill the expression with `" times one"` and check if the evaluation of the resulting expression has property `K`.
            * If it does, return the words
            * If it doesn't, proceed
        - If it doesn't, proceed
* Go drink a coffee

# Practice

## num.js (for SpiderMonkey / command lines)

```
function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>t*n;)++n;if(t*n===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this};print(Y(0|arguments[0]))
```

## num.js (for browsers)

The given code from above can't work for browsers due to its last command, which grabs the command line arguments in order to make a nice command out of the given script.

In order to run the JavaScript code directly from within your browser, select this piece of the above code:

```
function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>t*n;)++n;if(t*n===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this}
```

Now, paste it into your browser's JavaScript console, so you can produce the same results from within your browser with, for example:

```
Y(1234);

```

## Examples (command line)

```
chiru@chiru ~ $ js num.js 28
28: fourteen plus fourteen times one
chiru@chiru ~ $ js num.js 7
7: impossible
chiru@chiru ~ $ js num.js 42
42: nine thousand sixty minus nine thousand eighteen

```

And in order to see the trick with which you can make each number work, just have a look at the **boring answer** for `js num.js 1337`:

```
1337: ten plus one thousand three hundred twenty seven times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one
```

The provided codes generates valid solutions for the given interval (and probably even above, you'd only have to raise the value of the variable `L`).

## Statistics

I was interested in "how **boring**" the expressions were (or: how much the substring `times one` was used per expression within this algorithm), as this part was responsible for finding a solution for every number within the given interval. See for yourselves:

**x**: n-th expression (min. 0, max. 10,000)

**y**: number of occurences of substring " times one" within expression (min. 0, max. 1245)

**Conclusions:**

* The expressions tend to get more and more boring in a linear manner.
* Over 99% of solutions are boring.

# Answer
> 6 votes
## C, 450 characters

Edit: removed `zero`

Edit: using only `plus` and `minus`

I searched for the shortest expression that adds chars and keeps the condition true. I found `plus ten plus five` is 15 long and adds 15 to the string.

I need only expressions for the first 15 numbers that are not impossible, to express any possible number. 12 is the biggest impossible number, therefore it suffices to hardcode numbers smaller 28.

```
4 = four
11 = six plus five
13 = eight plus five
14 = twenty minus six
15 = twenty minus five
16 = eighteen minus two
17 = fourteen plus three
18 = twenty two minus four
20 = thirty two minus twelve
21 = twenty plus two minus one
22 = twenty plus four minus two
23 = thirty minus eight plus one
24 = twenty plus eight minus four
25 = twenty plus eight minus three
27 = twenty eight minus six plus five
```

We can write every number \>27 as x\*15 + one of the numbers above.

## Golfed

```
#define P" plus "
#define M" minus "
#define U"four"
#define F"five"
#define E"eight"
#define W"twenty"
#define A"ten"P F P
*e[]={0,0,0,0,U,0,0,0,0,0,0,F P"six",0,E P F,W M"six",W M F,E"een"M"two",U"teen"P"three",W" two"M U,A U,"thirty two"M"twelve",W P"two"M"one",W M"two"P U,"thirty"P"one"M E,W P E M U,W M"three"P E,A F P"six",W" "E M"six"P F};main(n){n=atoi(1[(int*)1[&n]]);for(printf("%d: ",n);n>27;n-=15)printf(A);puts(e[n]?e[n]:"impossible");}

```

## Readable Code

```
#include <stdio.h>
#include <stdlib.h>

// add fifteen to string, both as value and as character count (without spaces)
const char *add_fifteen = "plus ten plus five";

// table with hardcoded expressions
// NOTE: we could calculate 19, 26, 28 and 29 from 4, 11, 13 and 14
// but we would need more logic, so we hardcode those 4 numbers too.
const char *expressions[30]={"impossible", "impossible", "impossible", "impossible",
    "four", "impossible", "impossible", "impossible", "impossible",
    "impossible", "impossible", "five plus six", "impossible",
    "eight plus five", "twenty minus six",
    "fourteen plus one", "eighteen minus two", "fourteen plus three",
    "twenty two minus four", "four plus ten plus five",
    "thirty two minus twelve", "nine plus seven plus five",
    "twenty plus four minus two", "twelve plus seven plus four",
    "twenty plus eight minus four", "twenty plus eight minus three",
    "five plus six plus ten plus five", "twenty eight minus six plus five",
    "eight plus five plus ten plus five", "seven plus seven plus ten plus five"};

int main(int argc,char *argv[])
{
    int n = strtol(argv[1], NULL, 0);
    int fifteens = 0;

    printf("%d: ", n);

    // how many times do we need to add fifteen?
    if(n>29){
        fifteens=(n/15) - 1;
        n -= fifteens*15; // ensure 30 > n >= 15, so we don't get "impossible"
    }

    // look up the expression for n
    printf("%s", expressions[n]);

    // add fifteens till we are done
    while(fifteens-- > 0) {
        printf(" %s", add_fifteen);
    }

    printf("\n");
    return 0;
}

```

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


title: ASCII Art Calendar

text:
# Question
Title: ASCII Art Calendar
Let's make an ASCII art clock and calendar that tells us the current month, day of the month, day of the week, hour, minute, and whether it's night or day (but not the year or second).

At any particular time the calendar will look something like this: (it looks better with less line spacing)

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                  ___                                       | |
| |                _(   )                                      | |
| |               (___)__)           -.-                       | |
| |                                                            | |
| |                                                            | |
| |      -.-                                                   | |
| |         -.-                                                | |
| |                     ___                                    | |
| |                   _(   )                                   | |
| |                  (___)__)                                  | |
| |                                                            | |
| |                                          ___               | |
| |                                        _(   )              | |
| |    _                                  (___)__)             | |
| |   /|\                                                      | |
| |  / | \                                                     | |
| | /__|__\                                                    | |
| |____|____                                                   | |
| |\_______/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-~~-~~~~~| |
| |____________________________________________________________| |
|/______________________________________________________________\|

```

It is always a 66 by 23 character "picture frame" whose border never changes.

The image within the frame tells us the time and date:

* During the day (6:00am - 5:59pm) the month is determined by the number of birds (`-.-`) in the sky. January = 1 bird, February = 2 birds, etc.
* During the night (6:00pm - 5:59am) the birds are replaced with 3 times as many stars (`*`). January = 3 stars, February = 6 stars, etc. Birds and stars are never in the sky at the same time.
* The day of the month is determined by the number of characters between the two dashes (`-`) on the water. e.g. `~~-~~~~-~~` means it is the fourth day of the month. Depending on the minute, the boat may need to be between the dashes (the dashes do not loop around).
* The day of the week is determined by the number of clouds in the sky (all clouds look the same). Sunday = **0 clouds**, Monday = 1 cloud, ..., Saturday = 6 clouds.
* The hour is determined by the level of water (and the boat). At its lowest (as above) it is 1 o'clock, during 2 o'clock it is one character higher, and so on up to 12 o'clock, then back to 1 o-clock. (It's a 12 not a 24 hour clock.)
* The minute is determined by the horizontal position of the boat. At the top of the hour the boat touches the left edge of the frame (as above). At each subsequent minute the boat moves right by one character. In minutes 51 to 59 it loops from the right side of the frame back to the left.

So, given that the example above has 3 birds, 3 clouds, 2 chars between dashes, the water at the lowest level, and the boat on the far left we can tell that the date is Wednesday March 2nd, and the time is 1:00pm.

Here is another example from Sunday April 25th, at 3:58am:

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                                                            | |
| |                                                     * *    | |
| |                            *       *                 *     | |
| |               *                                            | |
| |                                                            | |
| |                           *                                | |
| |         *                      *                           | |
| |                                                            | |
| |                                 *                          | |
| |                                                            | |
| |                                 *                          | |
| |  _                                                         | |
| | /|\                          *                             | |
| |/ | \                                                       | |
| |__|__\                                                     /| |
| |__|____                                                   __| |
| |______/~~~~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~~-~~~~~\_| |
| |                                                            | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```

# Goal

Your goal is to write the shortest program possible that outputs these ASCII art "calendars" to stdout using the time when the program is run.

Every run of the program should output one time-scene. Updates should not be automatic (or animated).

The clouds, stars, and birds, should be placed randomly in the sky (so every run, even ones at the same time are likely to be different). They should never overlap the boat or each other. (Also the water dashes should not overlap the boat hull.)

Notice that nothing I have described appears underwater. This is for you to do. During one predetermined hour of every week (your choice), something *interesting* should be drawn underwater. It could be a sea monster or sunken ship or anything, it's up to you. During that hour you may even alter the design of the rest of the scene (staying in the frame bounds).

# Scoring

This is a code-golf popularity-contest combo.

Your score is `(bytes in program) - 4 * (upvotes - downvotes)`. The lowest score wins.

Use http://mothereff.in/byte-counter as a byte counter if you use non-ASCII characters.

# Notes and Updates

* You may use buoys instead of dashes, since, lets face it, they're much more appropriate:

```
   |     |
~~(_)~~~(_)~~ (3rd of the month)

```
* The dashes (or buoys) do not have to be random but it would be nice if they were.
* Your "special hour" should last 60 minutes from the top of the hour to 1 minute before the next hour.
* During the special hour the things you draw underwater may move and may alter the surface and the sky when it makes sense (e.g. sea monster eating the boat, black hole forming at the sea floor, etc.)

# Answer
## Ruby, At World's End, ~~1260~~ ~~1070~~ 967 bytes

Anyone remember that Pirates of the Caribbean film?

```
c=("   #{?_*60}
")*2
c+="| |#{' '*60}| |
"*19+c
[67,132,-2,-66,-67,-69,-71,-132,-134].map{|i|c[i]=?|}
a=c[68]=c[-3]=?\\
e=c[131]=c[-66]=?/
[1,2,-4,-65,63,64].map{|i|c[i]=?_}
t=Time.now
w,_,n,l,d,m=t.wday,*t.to_a
p=l>11
q=(l-1)%12+1
h=(20-(l-1)%12)*67+3
c[h,60]=?~*60
f=(n+9)%60
f=f+d>58?n>d+2?0:n-12:f
c[h+f]=c[h+f+d+1]=?-
s=l==18&&w==0
z=->s{s.chars.map(&:to_i)}
b={?_=>z['5410110125'+g='020304050607121315161718222326'],e=>z['08213243'],a=>z['00273645'],?|=>z['14243444'],?#=>[3,3,3,5]}
b={?_=>z[g+'272855140824'].map{|i|i-1},a=>b[e],e=>b[a],?|=>z['142434']}if s
b.each{|k,v|v.each_slice(2){|j,i|c[h-67*j*(s ?-1:1)+(i+n)%60]=k}}
r=->(m,t){k=0
(x=rand(53)
y=rand(19-q)
m.values.flatten.each_slice(2).any?{|j,i|c[h-(y+j)*67+i+x]!=' '}? next: m.each{|k,v|v.each_slice(2){|j,i|c[h-(y+j)*67+i+x]=k}}
k+=1)while k<t}
r[{?(=>[1,0,2,2],?)=>z['141726'],?_=>z['111213151621333435'],?#=>z['232425']},w]
r[l>5&&l<18?{?-=>[1,0,1,2],?.=>[1,1]}:{?*=>[1,0]},m]
puts c.tr(?#,' ')

```

There's still a lot of room for improving the golfitude there, but it's a start.

Now what's with the movie reference? Apparently that Green Flash happens a lot more often than Jack Sparrow wants us to believe. In fact, it happens about once a week instead of once every ten years. Every Sunday at sunset, the Black Ruby (hrhr) does one round in the land of the dead:

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| | *                          *                       *       | |
| |                     *                            *         | |
| |         *  *                  *             _______        | |
| |-~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/_______\~~~~~~~| |
| |                                             ___|___        | |
| |                                             \  |  /        | |
| |                                              \ | /         | |
| |                                               \_/          | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```
> 21 votes

# Answer
# Java - Cute Kraken (A lot of bytes)

EDIT: Further improvements to birds/stars bring up top and clouds, now the most busy calendar (12pm, Saturday, December) works about 70% of the time. Other 30% I get a (get ready for this) Stack Overflow error because I use recursion. New pics of busiest possible calendar and new Kraken pic, which shows off the lows/highs of stars/clouds.

Now better handles situations in which the random scattering of stars/birds prevents the random insertion of clouds. When things are too crowded and it doesn't work after 200 tries, we re-do the stars/birds in hopes that the next configuration will allow the clouds some personal space.

Who's a cute wittle kwaken? Who's a cute wittle kwaken? You are! You are!

Minor edits, still no golfing. Kwaken shows up on the 9s because he knows everyone expects him at midnight. He's small and shy now, but one day he hopes to eat the ship.

Clouds have a tendency to be low in the sky, while stars and birds like to fly above them; things tend to get a little crowded around 8 o'clock though.

```
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TimeFlies
{
   static char[][] frame = new char[23][66];
   static char[] bird = new char[] {'-', '.', '-'};
   static char[][] boat = new char[][]{
   {' ', ' ', ' ', ' ', '_', ' ', ' ', ' ', ' '},
   {' ', ' ', ' ', '/', '|', '\\', ' ', ' ', ' '},
   {' ', ' ', '/', ' ', '|', ' ', '\\', ' ', ' '},
   {' ', '/', '_', '_', '|', '_', '_', '\\', ' '},
   {'_', '_', '_', '_', '|', '_', '_', '_', '_'},
   {'\\', '_', '_', '_', '_', '_', '_', '_', '/'},
   };
   static char[][] cloud = new char[][]{
   {' ', ' ', ' ', '_', '_', '_', ' ', ' '},
   {' ', '_', '(', ' ', ' ', ' ', ')', ' '},
   {'(', '_', '_', '_', ')', '_', '_', ')'},
   };
   static char[][] kraken = new char[][]{
   {' ', ' ', ' ', '_', '_', '_', '_', '_', '_', '_', '_', ' ', ' ', ' ', ' '},
   {' ', ' ', '/', ' ', ' ', '_', ' ', ' ', ' ', '_', ' ', '\\', ' ', ' ', ' '},
   {' ', '|', ' ', ' ', '|', '_', '|', ' ', '|', '_', '|', ' ', '|', ' ', ' '},
   {' ', ' ', '\\', '_', '_', '_', '\\', ' ', '/', '_', '_', '/', ' ', ' ', ' '},
   {' ', ' ', ' ', '/', '|', ' ', '|', ' ', '|', ' ', '|', '\\', ' ', ' ', ' '},
   {'_', '_', '/', ' ', '|', ' ', '|', ' ', '|', ' ', '|', ' ', '\\', '_', '_'},
   {' ', ' ', '_', '/', ' ', ' ', '|', ' ', '|', ' ', ' ', '\\', '_', ' ', ' '},
   {' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' '}};

   static int day, month, hours, minutes, weekday, attempts = 0;
   static boolean isFirstTime, birds = true;
   static String timeStamp;

   public static void main()
   {
       timeStamp = new SimpleDateFormat("MMddHHmm").format(Calendar.getInstance().getTime());
       isFirstTime = true;
       retry();
   }

   public static void retry()
   {

       day = Integer.parseInt(timeStamp.substring(2, 4));
       month = Integer.parseInt(timeStamp.substring(0, 2));
       hours = Integer.parseInt(timeStamp.substring(4, 6));
       minutes = Integer.parseInt(timeStamp.substring(6, 8));

       Calendar c = Calendar.getInstance();
       c.set(2014, month, day);
       weekday = c.get(Calendar.DAY_OF_WEEK) - 1;

       int timeTemp = hours*60 + minutes;
       if(timeTemp < 360 || timeTemp > 1080)
       {
           birds = false;
           month *= 3;
       }
       if(hours > 12)
           hours -= 12;
       initiateFrame();

       if(isFirstTime)
       {
           printFrame();
           isFirstTime = false;
       }
   }

   public static void insertStuff()
   {
       for(int i = 0; i < boat.length; i++)
           for(int k = 0; k < boat[0].length; k++)
           {
               if(3+k+minutes > 62)
                   frame[15 + i - hours][3 + k + minutes-60] = boat[i][k];
               else
                   frame[15 + i - hours][3 + k + minutes] = boat[i][k];
           }

       boolean beganDayCount = false;
       for(int i = 0; i <= 22; i++)
           for(int k = 0; k <=65; k++)
               if(i == (20 - hours) && (k > 2 && k < 63) && frame[i][k] == ' ')
               {
                   if(!beganDayCount)
                   {
                       frame[i][k] = '-';
                       beganDayCount = true;
                   }
                   else
                   {
                       if(day > 0)
                           frame[i][k] = '~';
                       if(day == 0)
                           frame[i][k] = '-';
                       else
                           frame[i][k] = '~';
                       day--;
                   }
               }
       putInBirdsOrStars();
       putInClouds();
       if(hours == 9)
           putInKraken();
   }

   public static void putInKraken()
   {
       for(int i = 0; i < kraken.length; i++)
           for(int k = 0; k < kraken[0].length; k++)
               frame[i + 12][k + 20] = kraken[i][k];
   }

   public static void putInClouds()
   {
       int x = (int)(Math.random() * 7) + (14-hours);
       int y = (int)(Math.random() * 54) + 2;
       boolean noFreeSpace = true;

       for(int i = 0; i < cloud.length; i++)
       {
           for(int k = 0; k < cloud[0].length; k++)
           {
               if(frame[x + i][y + k] == ' ' )
                   noFreeSpace = false;
               else
               {
                   noFreeSpace = true;
                   break;
               }
           }
           if(noFreeSpace)
               break;
       }

       if(x + 2 > 20 - hours)
           noFreeSpace = true;

       if(!noFreeSpace)
       {
           for(int i = 0; i < cloud.length; i++)
               for(int k = 0; k < cloud[0].length; k++)
                   frame[x + i][y + k] = cloud[i][k];
           weekday--;
       }

       attempts++;
       if(attempts > 200)
       {
           attempts = 0;
           retry();
       }
       if(weekday > 0)
           putInClouds();
   }

   public static void putInBirdsOrStars()
   {
       int x = (int)(Math.random() * 5) + (12 - hours);
       int y = (int)(Math.random() * 60) + 2;
       boolean freeSpace = false;

       for(int i = 0; i < bird.length; i++)
           if(frame[x][y] == ' ' && frame[x][y + 1] == ' ' && frame[x][y + 2] == ' ')
               freeSpace = true;

       if(x > 20- hours)
           freeSpace = false;
       if(birds && freeSpace)
       {
           for(int i = 0; i < bird.length; i++)
               frame[x][y++] = bird[i];
           month--;
       }
       else if(freeSpace)
       {
          frame[x][y] = '*';
          month--;
       }
       if(month > 0)
           putInBirdsOrStars();
   }

   public static void initiateFrame()
   {
       for(int i = 0; i <= 22; i++)
           for(int k = 0; k <=65; k++)
           {
               if(((k == 0 || k == 65) && (i > 0)) || ((k == 2 || k == 63) && (i > 1 && i < 22)))
                   frame[i][k] = '|';
               else if((i == 0 && (k > 0 && k < 65)) || ((i == 1 || i == 21) && (k > 2 && k < 63)) || (i == 22 && (k > 1 && k < 64)))
                   frame[i][k] = '_';
               else
                   frame[i][k] = ' ';
           }

       frame[1][1] = '\\'; frame[1][64] = '/'; frame[22][1] = '/';frame[22][64] = '\\';
       insertStuff();
   }

   public static void printFrame()
   {
       for(int i = 0; i <= 22; i++)
       {
           for(int k = 0; k <=65; k++)
               System.out.print(frame[i][k]);
           System.out.println();
       }
   }
}

```

Casual output

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                                                      -.-   | |
| |                                   -.-                      | |
| |                                                            | |
| |      -.-                                                   | |
| |                                                            | |
| |               -.-                                          | |
| |                                                            | |
| |                     -.-                           -.-      | |
| |    -.-                                  ___                | |
| |            -.-                        _(   )      ___      | |
| |             ___                      (___)__)   _(   )     | |
| |           _(   )        ___               _    (___)__)    | |
| |          (___)__)     _(   )             /|\               | |
| |     ___              (___)__)   ___     / | \              | |
| |   _(   )                      _(   )   /__|__\             | |
| |  (___)__)                    (___)__) ____|____            | |
| |-~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~\_______/~~~~~~~~~~~~| |
| |                                                            | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```

super busy output

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |  *  * **    * *        *  *    **       * *   *    * *  *  | |
| |*  _   *  *       **  *        *         *   *  *      *    | |
| |  /|\*    ___  *  **  *     *        *      ___  *     *    | |
| | / | \  _(   )    ___      ___       ___  _(   )    ___     | |
| |/__|__\(___)__) _(   )   _(   )    _(   )(___)__) _(   )    | |
| |___|____       (___)__) (___)__)  (___)__)       (___)__)  _| |
| |_______/-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~\| |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```

If we're to introduce our kraken by hard coding some values, we get...

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                                                            | |
| |*           *  *     *                                   *  | |
| |  *       *                                    *   *   *    | |
| |*          ___      *  *                   *    *           | |
| |         _(   )  _         ___      *   *                   | |
| |     *  (___)__)/|\*     _(   )  *   *    *   ___   *   *   | |
| |   ___         / | \    (___)__)   ___      _(   )    ___   | |
| | _(   )       /__|__\            _(   )    (___)__) _(   )  | |
| |(___)__)     ____|____          (___)__)           (___)__) | |
| |-~~~~~~~~~~~~\_______/~~~-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| |
| |                    ________                                | |
| |                   /  _   _ \                               | |
| |                  |  |_| |_| |                              | |
| |                   \___\ /__/                               | |
| |                    /| | | |\                               | |
| |                 __/ | | | | \__                            | |
| |                   _/  | |  \_                              | |
| |                      /   \                                 | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```
> 13 votes

# Answer
## Python3 - Pirates and Jellyfish: ~~1580~~ 1472 bytes

Every Wednesday at midnight a pirate ship sinks our boat. The noise wakes up a giant jellyfish who randomly roams the frame for an hour.

```
from random import*
from datetime import*
l=len;r=range
n=randint
def f(s,p,*a):
 global c,o;j=l(s[0])
 while 1:
  x=n(3,63-j);y=n(3,p);g=y+l(s);h=x+j
  if not(o[y][x]or o[g][h]or o[g][x]or o[y][h]):break
 if l(a)!= 0:x,y=a
 for w in r(l(s)):
  for m in r(j):c[y+w][x+m]=s[w][m];o[y+w][x+m]=1
E=datetime.now();D=(E.weekday()+1)%7
h=E.hour;M=E.month
t=6<h<18;N=(3*M,M)[t]
H=9if h==0 else 21-h%12
s=min(H-1,12)
o=[[0]*66 for i in r(23)]
c=[['']*66 for i in r(23)]
c[0]=[' ']+['_']*64+[' ']
c[1]=['|','\\']+['_']*62+['/','|']
for i in r(2,21):c[i]=['|',' ','|']+[' ']*60+['|',' ','|']
c[21]=['|',' ','|']+['_']*60+['|',' ','|']
c[22]=['|','/']+['_']*62+['\\','|']
for i in r(3,63):c[H][i]='~'
Z=(D!=3or h!=0)
B=(['    _~_      ','  __)__)__   ','  )_))_))_)  ','.--:--:--:-=/',' \\_o__o__o_/ '],['    _    ','   /|\\   ','  / | \  ',' /__|__\\ ','____|____','\\_______/'])[Z]
j=l(B[0]);y=H-l(B)+1;x=E.minute
while 1:
 b=n(3,63)
 if b<x or b>(x+j):break
z=E.day+1;d=b+z
if b<x<d:d+=j
if d>63:d=b-z
if d<x<b:d-=j
c[H][b]=c[H][d]='-'
for w in r(l(B)):
 for m in r(j):
  g=x+m;k=y+w
  if g>59:c[k][g-57]=B[w][m];o[k][g-57]=1
  else:c[k][g+3]=B[w][m];o[k][g+3]=1
f((["  ,'',  ",".°____°."," :::::: ",",';:::'."," ,';:'. "],[''])[Z],s,n(3,50),n(10,13))
f((['  o  ° o °','°________°','/___°____\\'],[''])[Z],s,15,18)
for i in r(D):f(['   ___  ','  (   ) ','(___)__)'],s-3)
for i in r(N):f(('*',['-.-'])[t],s)
for w in r(23):
 for m in r(66):print(c[w][m],end='')
 print('')

```

---

Example at Tuesday Aug 19 23:27

On Wednesdays around midnight:
> 11 votes

# Answer
# Cobra - 994

Without Bouys: 994

```
class P
    def main
        r,d=Random(),DateTime.now
        h,y,t,a=(d.hour+23)%24+1,d.day,d.month,d.dayOfWeek to int
        u,i,q=18-(h-1)%12,List<of String>[](20),1-(h+7)%24//13
        for p in 20
            i[p],s=['| |\n'],'__'
            for x in 60,i[p],s=[if(p-u,'[' _'[p//19]]','~')]+i[p],s+'_'
        for g in 6,for c in 9,i[u-g][(d.minute+c)%60]='[r'\_______/____|____ /__|__\   /#|#\     /|\       _    '[g*9+c]]'
        while x,if'~'==i[u][p-=p-r.next(60-y)]==i[u][p+y+1],i[u][p],i[u][p+y+1],x='-','-',0
        while g+c
            o,c,g=i,a,t+t*q*2
            for z in 99,if if(c,o[y-=y-r.next(u-2)][x-=x-r.next(52):x+8]+o[y+1][x:x+8]+o[y+2][x:x+8],o[y-=y-r.next(u)][x-=x-r.next(60-3+3*q):x+4-3*q]).join('').trim==''and g,for m in 3-(p-=p-if(c,0,1))*2,for n in 8-p*5,o[y+m][x+n-p*n*q],c,g=if(c,'['   ___   _(###) (___)__)'[m*8+n]]',['['-.-'[n]]','*'][q]),c-(m+n)//9,g-p*n//2
        print' _[s]_ \n|\\[s]/|'
        for l in o,for k in['| |']+l
            Console.foregroundColor=if(k<>'~'or h+a>1,7,9)to ConsoleColor
            Console.write(if(k=='#',' ',k))
        print'|/[s]\\|'

```

With Bouys: 1084

```
class P
    def main
        r,d=Random(),DateTime.now
        h,y,t,a=(d.hour+23)%24+1,d.day,d.month,d.dayOfWeek to int
        u,i,q=18-(h-1)%12,List<of String>[](20),1-(h+7)%24//13
        for p in 20
            i[p],s=['| |\n'],'__'
            for x in 60,i[p],s=[if(p-u,'[' _'[p//19]]','~')]+i[p],s+'_'
        for g in 6,for c in 9,i[u-g][(d.minute+c)%60]='[r'\_______/____|____ /__|__\   /#|#\     /|\       _    '[g*9+c]]'
        while x<>3,if''==(i[u][p-=p-r.next(58-y):p+3]+i[u][p+y+3:p+y+7]).join('').trim(c'~')
            i[u-1][p+1]=i[u-1][p+y+4]='|'
            for x in 3,i[u][p+x]=i[u][p+y+3+x]='['(_)'[x]]'
        while g+c
            o,c,g=i,a,t+t*q*2
            for z in 99,if if(c,o[y-=y-r.next(u-2)][x-=x-r.next(52):x+8]+o[y+1][x:x+8]+o[y+2][x:x+8],o[y-=y-r.next(u)][x-=x-r.next(60-3+3*q):x+4-3*q]).join('').trim==''and g,for m in 3-(p-=p-if(c,0,1))*2,for n in 8-p*5,o[y+m][x+n-p*n*q],c,g=if(c,'['   ___   _(###) (___)__)'[m*8+n]]',['['-.-'[n]]','*'][q]),c-(m+n)//9,g-p*n//2
        print' _[s]_ \n|\\[s]/|'
        for l in o,for k in['| |']+l
            Console.foregroundColor=if(k<>'~'or h+a>1,7,9)to ConsoleColor
            Console.write(if(k=='#',' ',k))
        print'|/[s]\\|'

```

At 1am every Sunday, the endless expanse of the tilde sea on comes alive with a dazzling blue shine. Hope returns to the people of the desolate shell-world.
> 6 votes

# Answer
## C# ~~1124~~ 1128bytes

Once a week, a shoddy ASCII submarine should appear for an hour below the waterline, and increase my byte count noticeably *hopefully this code will actually work now*. I dread to think what happens on Saturdays at 11:00 in December...

```
using System;class P{static string G(DateTime t){Func<int,int>K=new Random().Next;int i,j,D=t.Day,H=t.Hour,W=19-H%12,E=(int)t.DayOfWeek;var M=new char[60,19];Func<int,int,int,string,bool>T=(x,y,w,s)=>{for(i=0;i<s.Length;)if(M[(x+i%w)%60,y+i++/w]>0)return 0>1;for(;i-->0;)M[(x+i%w)%60,y+i/w]=s[i];return 1>0;};T(t.Minute,W-5,9,@"    _       /|\     / | \   /__|__\ ____|____\_______/");while(M[j=K(59-D),W]+M[j+D+1,W]>0){}M[j+D+1,W]=M[j,W]='-';for(j=60;j-->0;)T(j,W,1,"~");for(;++j<E;)while(!T(K(53),K(W-3),8,"   ___   _(   ) (___)__)")){}var N=H<6|H>=18;for(j=0;j++<t.Month*(N?3:1);)while(!T(K(60-(N?1:3)),K(W-1),3,N?"*":"-.-")){}if(H==18&E==4)T(K(59),W+2,17,@"    __            __/  \_________ (_______________)");var res=" ________________________________________________________________\n|\\ ____________________________________________________________ /|\n| |";for(j=0;j<19;j++){for(i=0;i<60;i++)res+=M[i,j];res+="| |\n| |";}return res+"____________________________________________________________| |\n|/______________________________________________________________\\|";}static void Main(){Console.Write(G(DateTime.Now));}}

```

Somewhat formatted code (which re-draws every 15seconds because I mis-read the spec):

```
using System;

class P
{
    static string G(DateTime t)
    {
        Func<int,int>K=new Random().Next;
        int i,j,D=t.Day,H=t.Hour,W=19-H%12,E=(int)t.DayOfWeek;
        var M=new char[60,19];

        Func<int,int,int,string,bool>T=(x,y,w,s)=>
        {
            for(i=0;i<s.Length;)
                if(M[(x+i%w)%60,y+i++/w]>0)
                    return 0>1;
            for(;i-->0;)
                M[(x+i%w)%60,y+i/w]=s[i];
            return 1>0;
        };

        T(t.Minute,W-5,9,@"    _       /|\     / | \   /__|__\ ____|____\_______/");

        while(M[j=K(59-D),W]+M[j+D+1,W]>0){}
        M[j+D+1,W]=M[j,W]='-';

        for(j=60;j-->0;)
            T(j,W,1,"~");

        for(;++j<E;)
            while(!T(K(53),K(W-3),8,"   ___   _(   ) (___)__)")){}

        var N=H<6|H>=18;
        for(j=0;j++<t.Month*(N?3:1);)
            while(!T(K(60-(N?1:3)),K(W-1),3,N?"*":"-.-")){}

        if(H==18&E==4)
            T(K(59),W+2,17,@"    __            __/  \_________ (_______________)");

        var res=@" ________________________________________________________________
|\ ____________________________________________________________ /|
| |";

        for(j=0;j<19;j++)
        {
            for(i=0;i<60;i++)
                res+=M[i,j];
            res+="| |\n| |";
        }

        return res+@"____________________________________________________________| |
|/______________________________________________________________\|";
    }

    static void Main()
    {
        for(;;)
        {
            Console.Clear();
            Console.Write(G(DateTime.Now));
            System.Threading.Thread.Sleep(15000);
        }
    }
}

```

Example output (should read 3:31, Wednesday, 13th August):

```
 ________________________________________________________________
|\ ____________________________________________________________ /|
| |                                                            | |
| |         *  *                                               | |
| |                         *                                  | |
| |      *                 *                                   | |
| |                     *                                      | |
| |            ___                        * *                  | |
| |          _(   )                                            | |
| |        *(___)__)      *                   *                | |
| |                                  *                         | |
| |           ___    *                                      *  | |
| |     *   _(   )  *                             ___    *     | |
| |      * (___)__)                   _         _(   )         | |
| |        *             *           /|\       (___)__)  *  *  | |
| |                                 / | \     *           *    | |
| |                                /__|__\                     | |
| |                               ____|____                    | |
| |~~-~~~~~~~~~~~~~-~~~~~~~~~~~~~~\_______/~~~~~~~~~~~~~~~~~~~~| |
| |                                                            | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```
> 5 votes

# Answer
# Lua - more than stars

I'm done!

Well, not done done. I'm done with this code and challenge. It's not golfed, it's missing the month indicator. There's no avoidance... I'm only posting it so that in the off chance nobody completes this chalange, at least you saw something, got an idea.

```
--Halfed Assed Calender
math.randomseed(os.time())
math.randomseed(os.time())
math.randomseed(os.time())
local bh=os.date("%I")
local bm=os.date("%m")
local wdm=os.date("%d")
local cdw=os.date("%w")
local bsm=os.date("%M")
local hh=tonumber(os.date("%H"))
local function tp(t)
    for i=1,#t do
        for k= 1, #t[i] do
            io.write(t[i][k])
        end
        print()
    end
end

local function s2a(s)
    local ns = {}
    for i=1, table.getn(s) do
        local nns={}
        for k = 1, string.len(s[i]) do
            table.insert(nns, string.sub(s[i],k,k))
        end
        table.insert(ns,nns)
    end
    return ns
end

function ca(bg, a, x,y)
    ntb={} lbg=#bg la=#a lax=#a[1] lbgx=#bg[1]
    if lbgx-((lax+y)-1)<0 then
    elseif lbg-((la+x)-1)<0 then
    else
        for i=1,la do
            for j = 1, lax do
                if " "==a[i][j] then
                else
                    table.remove(bg[x+(i-1)],y+(j-1))
                    table.insert(bg[x+(i-1)],y+(j-1), a[i][j])
                end
            end
        end
    end
    return bg
end
f=s2a({" ________________________________________________________________ ","|\\ ____________________________________________________________ /|","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |                                                            | |","| |____________________________________________________________| |","|/______________________________________________________________\\|"})
boat=s2a({"    _    ","   /|\\     ","  / | \\   "," /__|__\\  ","____|____ ","\\_______/  "})
ccc=s2a({"   ___  "," _(   ) ","(___)__)"})
water=s2a({"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"})
tblock=s2a({"xxx","xxx","xxx"})
temp=ca(f,water,19-bh,4)
if hh<18 and hh>= 6 then
    n=bm sb = {{"-",".","-"}}
else
    n=3*bm sb={{"*"}}
end

for i = 1,n do
    r1=math.random(14 -bh)
    r2=math.random(59)
    temp=ca(temp,sb,r1+3,r2+3)
end
if cdw==0 then
else
    for i=1,cdw do
        r1=math.random(11-bh)
        r2=math.random(52)
        temp=ca(temp,ccc,r1+3,r2+3)
    end
end
temp=ca(temp,boat,14-bh, bsm)
tp(temp)

```

You can take look at it here.

---

```
|\ ____________________________________________________________ /|
| |                                                            | |
| |       -.-                                                  | |
| |                                                            | |
| |                                        ___                 | |
| |                                      _(   )                | |
| |                  -.-   -.-          (___)__)               | |
| |                                                            | |
| |                            -.-             _        ___    | |
| |          -.-                              /|\     _(   )   | |
| |              -.-                         / | \   (___)__)  | |
| |                                         /__|__\ -.-.-      | |
| |                                        ____|____           | |
| |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\_______/~~~~~~~~~~~| |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |                                                            | |
| |____________________________________________________________| |
|/______________________________________________________________\|

```
> 2 votes

---
Tags: code-challenge, ascii-art, kolmogorov-complexity, date
---