title: Forecast the weather

text:
# Question
Title: Forecast the weather
Write the shortest program to forecast the weather for the next 7 days

The input (from stdin) is the *weekday* and the *season*

The output (to stdout) is seven lines *weekday* and the *temperature* in centigrade

The weekdays begin on the input weekday

The temperatures are random numbers with the range depending on the season

```
Spring 10 - 30 degrees
Summer 20 - 40 degrees
Autumn  5 - 25 degrees  (Fall is a synonym for autumn)
Winter -5 - 15 degrees

```

**Sample Input**

`Thursday Winter`

**Sample Output**

```
Thursday -1
Friday 3
Saturday 8
Sunday 7
Monday 10
Tuesday 10
Wednesday -1

```

Your program must not have identical output every time it is run with the same input

# Answer
## Ruby 1.8, 95 characters

```
#!ruby -nrdate
7.times{|i|puts (Date.parse($_)+i).strftime"%A #{"\023\004\016\016\035"[$_[-3]%5]-9+rand(21)}"}

```

The character escapes inside the string should be replaced by the character literals they represent.

* Found a shorter way to pack the data, Ruby 1.9 would be 4 characters longer now (add `.ord` after `$_[-3]`).
* 112 -\> 105 by stealing Joey's idea of not splitting the input.
* 105 -\> 101. Note that the first line is actually parsed by the Ruby interpreter itself, so it even works when running the solution like `echo "Thursday Winter" | ruby1.8 forecast.rb`
* 101 -\> 96. Stole Joey's idea again to just embed the temperatures into a string instead of an array.
* Whoops, just noticed it should be rand(21), not rand(20).
* 96 -\> 95. Removed unnecessary whitespace.
> 8 votes

# Answer
### Windows PowerShell, 104

```
[dayofweek]$d,$s=-split$input
(0..6*2)[+$d..(6+$d)]|%{''+[dayofweek]$_,((random 20)-5+'☼

↓'[$s[3]%5])}

```

The strings in there are a bit icky, so a hex view for your convenience:

```
000: 5B 64 61 79 6F 66 77 65 │ 65 6B 5D 24 64 2C 24 73  [dayofweek]$d,$s
010: 3D 2D 73 70 6C 69 74 24 │ 69 6E 70 75 74 0A 28 30  =-split$input◙(0
020: 2E 2E 36 2A 32 29 5B 2B │ 24 64 2E 2E 28 36 2B 24  ..6*2)[+$d..(6+$
030: 64 29 5D 7C 25 7B 27 27 │ 2B 5B 64 61 79 6F 66 77  d)]|%{''+[dayofw
040: 65 65 6B 5D 24 5F 2C 28 │ 28 72 61 6E 64 6F 6D 20  eek]$_,((random
050: 32 30 29 2D 35 2B 27 0F │ 00 0A 0A 19 27 5B 24 73  20)-5+'☼ ◙◙↓'[$s
060: 5B 33 5D 25 35 5D 29 7D │                          [3]%5])}

```

History:

* 2011-02-04 00:16 **(179)** – First, straightforward attempt.
* 2011-02-04 00:20 **(155)** – Why match whole season names when you can get away with individual characters and a regex match? Won't deal nicely with invalid input but that's always to be expected in Golfing.
* 2011-02-06 13:12 **(149)** – Got rid of `$t` which only lengthened things.
* 2011-02-10 22:50 **(142)** – Day name generation made simpler. I just generate a week twice, index in the correct position and pull out seven items.
* 2011-02-10 22:52 **(138)** – Moving the initial cast to the declaration of `$d` saves a few bytes as well – and gets rid of `$x`.
* 2011-02-10 23:03 **(135)** – Moving the cast further down the pipeline to avoid an array cast (which needs additional `[]`). Also changed output to casting a list of objects to string which implicitly inserts a space (`$OFS` default).
* 2011-02-11 20:54 **(132)** – Replaced the regex match by a list of character codes and indexing into a hashmap with the third character from the season.
* 2011-02-11 21:00 **(122)** – Replaced the hash map by an array.
* 2011-02-11 21:12 **(117)** – More array-y goodness. And shorter to boot. Modulo 8 packs the array a bit shorter.
* 2011-02-11 21:16 **(116)** – Extracted a factor of five to replace `0,0,2` by `0..2` which is shorter.
* 2011-02-11 21:22 **(114)** – Used a slightly different calculation. It still maps autumn and fall to the same index and has the advantage of only requiring five values. Very nice. The negative index into the string also plays very well with »Fall« being shorter than the rest.
* 2011-02-11 21:45 **(112)** – Stolen Ventero's way of determining the season's temperature range which is two bytes shorter.
* 2011-02-12 03:16 **(105)** – Back to 105 after a different attempt just printed a single line.
* 2011-02-12 13:23 **(104)** – Back to 104 again, using a positive index into the season since I split again.

Test script (as long as it outputs nothing the result is ok):

```
foreach ($d in 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') {
    foreach ($s in 'Winter','Summer','Spring','Autumn','Fall') {
        $o=-split("$d $s"|./weather_foo.ps1)
        if ($o.Count -ne 14) { "Wrong output length" }
        $days = $o -notmatch '\d'
        $temps = $o -match '\d'
        if ($days[0]-ne$d) { "Found "+ $days[0] + " instead of $d" }
        $m = $temps | measure -min -max
        switch ($s) {
            'Summer'{ $min = 20 }
            'Spring'{ $min = 10 }
            'Fall'  { $min = 5  }
            'Autumn'{ $min = 5  }
            'Winter'{ $min = -5 }
        }

        if ($m.Minimum -lt $min) { "Minimum temperature $($m.Minimum) didn't match for $s" }
        if ($m.Maximum -gt $min + 20) { "Maximum temperature $($m.Maximum) didn't match for $s" }
    }
}

```
> 4 votes

# Answer
## Golfscript - 110 chars

```
' ':^/){*}*43845%7&5*:|;){*}*333121%7&:$;7,{($+'Sun Mon Tues Wednes Thurs Fri Satur'^/.+='day '+20rand|+5-+n}/

```
* Fully support all the temperature ranges, seasons and also support "Fall" as synonym for "Autumn" too.
* I think there is some rooms for improvement, but my current golfscript knowledge is limited so far.

### Here is the tests, 2 passes each to confirm randomness

```
$ echo -n Thursday Spring | gs codegolf-404.gs
Thursday 23
Friday 28
Saturday 25
Sunday 22
Monday 19
Tuesday 14
Wednesday 25

$ echo -n Thursday Spring | gs codegolf-404.gs
Thursday 27
Friday 12
Saturday 26
Sunday 12
Monday 27
Tuesday 17
Wednesday 21

$ echo -n Friday Autumn | gs codegolf-404.gs
Friday 10
Saturday 5
Sunday 17
Monday 24
Tuesday 24
Wednesday 12
Thursday 18

$ echo -n Friday Autumn | gs codegolf-404.gs
Friday 13
Saturday 7
Sunday 14
Monday 6
Tuesday 14
Wednesday 21
Thursday 5

$ echo -n Sunday Summer | gs codegolf-404.gs
Sunday 39
Monday 31
Tuesday 35
Wednesday 34
Thursday 21
Friday 36
Saturday 28

$ echo -n Sunday Summer | gs codegolf-404.gs
Sunday 34
Monday 20
Tuesday 30
Wednesday 39
Thursday 30
Friday 31
Saturday 37

$ echo -n Monday Fall | gs codegolf-404.gs
Monday 6
Tuesday 7
Wednesday 18
Thursday 13
Friday 7
Saturday 5
Sunday 14

$ echo -n Monday Fall | gs codegolf-404.gs
Monday 16
Tuesday 22
Wednesday 19
Thursday 23
Friday 21
Saturday 9
Sunday 17

$ echo -n Saturday Winter | gs codegolf-404.gs
Saturday 0
Sunday -5
Monday 10
Tuesday -3
Wednesday -5
Thursday 13
Friday -1

$ echo -n Saturday Winter | gs codegolf-404.gs
Saturday -4
Sunday 13
Monday 11
Tuesday 0
Wednesday 0
Thursday -5
Friday 9

$ echo -n Tuesday Summer | gs codegolf-404.gs
Tuesday 38
Wednesday 29
Thursday 25
Friday 29
Saturday 34
Sunday 20
Monday 39

$ echo -n Tuesday Summer | gs codegolf-404.gs
Tuesday 33
Wednesday 26
Thursday 31
Friday 37
Saturday 39
Sunday 24
Monday 28

$ echo -n Wednesday Winter | gs codegolf-404.gs
W    ednesday 7
Thursday 12
Friday 0
Saturday -3
Sunday 11
Monday 14
Tuesday 8

$ echo -n Wednesday Winter | gs codegolf-404.gs
Wednesday 0
Thursday -1
Friday 7
Saturday 12
Sunday -5
Monday -3
Tuesday 2

```
> 3 votes

# Answer
# D: 436 Characters

```
import std.algorithm, std.random, std.range, std.stdio, std.typecons;

void main(string[] g)
{
    alias canFind w;
    alias tuple t;

    auto s = g[2];
    auto e = w(s, "g") ? t(10, 30) : w(s, "Su") ? t(20, 40) : w(s, "W") ? t(-5, 15) : t(5, 25) ;
    auto r = rndGen();

    int v()
    {
        r.popFront();
        return e[0] + cast(int)(r.front % (e[1] - e[0]));
    }

    auto x = findSplitBefore(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], [g[1]]);

    foreach(q; chain(x[1], x[0]))
        writefln("%s %s", q, v());
}

```

Version with extraneous whitespace removed (which is how it comes to 436 characters):

```
import std.algorithm,std.random,std.range,std.stdio,std.typecons;void main(string[] g){alias canFind w;alias tuple t;auto s=g[2];auto e=w(s,"g")?t(10,30):w(s,"Su")?t(20,40):w(s,"W")?t(-5,15):t(5,25);auto r=rndGen();int v(){r.popFront();return e[0]+cast(int)(r.front%(e[1]-e[0]));}auto x=findSplitBefore(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],[g[1]]);foreach(q;chain(x[1],x[0]))writefln("%s %s",q,v());}

```
> 2 votes

# Answer
## PHP, ~~353~~ ~~319~~ ~~305~~ ~~304~~ 288 characters

```
<?$i=split(" ",fgets(STDIN));$d=$i[0][0].$i[0][1];$s=$i[1][2];$r=json_decode('{"i":[10,30],"m":[20,40],"t":[5,25],"n":[-5,15]}',true);$n=array(Sun,Mon,Tues,Wednes,Thurs,Fri,Satur);$z=$x=0;while($z<7)if($n[++$x][0].$n[$x][1]==$d||$z){$z++;echo$n[$x%7]."day ".rand($r[$s][0],$r[$s][1])."
";}

```

**Ungolfed**

```
<?php
    $input = fgets(STDIN);
    $info = split(" ", $input);
    $day = substr($info[0], 0, 2);
    $season = $info[1][2];
    $range[i][] = 10;
    $range[i][] = 30;
    $range[m][] = 20;
    $range[m][] = 40;
    $range[t][] = 5;
    $range[t][] = 25;
    $range[n][] = -5;
    $range[n][] = 15;
    $days[0] = "Sun";
    $days[1] = "Mon";
    $days[2] = "Tues";
    $days[3] = "Wednes";
    $days[4] = "Thurs";
    $days[5] = "Fri";
    $days[6] = "Satur";

    $i = $d = 0;

    while($i<7)
        if(substr($days[++$d], 0, 2)==$day||$i){
            $i++;
            echo $days[$d%7]."day ".rand($range[$season][0], $range[$season][1])."\n";
        }
?>

```

305 -\> 304: Switched the newline
304 -\> 288: Uses JSON arrays instead of PHP arrays
> 2 votes

# Answer
**C# 350 Characters**

There must be a more efficient way than this. But here's what I've got so far:

```
using System;class P{static void Main(string[]x){var r=new Random();var s=x[1][2];int l=s=='r'?10:s=='m'?20:s=='n'?-5:5,u=s=='r'?31:s=='m'?41:s=='n'?16:26,i=0,z=(int)Enum.Parse(typeof(DayOfWeek),x[0]);for(;i<7;i++){var d=z<1?"Sun":z<2?"Mon":z<3?"Tues":z<4?"Wednes":z<5?"Thurs":z<6?"Fri":"Satur";Console.WriteLine(d+"day "+r.Next(l,u));z=z>5?0:z+1;}}}

```

Or in a more readable format, with a couple of comments:

```
using System;
class P
{
    static void Main(string[] x)
    {
        var r = new Random();
        var s = x[1][2]; //3rd char of season, first where all have unique letter

   // lower & upper limits for random, based on season
        int l = s == 'r' ? 10 : s == 'm' ? 20 : s == 'n' ? -5 : 5,
            u = s == 'r' ? 31 : s == 'm' ? 41 : s == 'n' ? 16 : 26,
            i = 0,
   // this line makes me cringe, but converting to an int and back seems
   // the easiest way to loop through days
            z = (int)Enum.Parse(typeof(DayOfWeek), x[0]);

        for (; i < 7; i++)
        {
            var d = z < 1 ? "Sun" : z < 2 ? "Mon" : z < 3 ? "Tues" : z < 4 ? "Wednes" : z < 5 ? "Thurs" : z < 6 ? "Fri" : "Satur";
            Console.WriteLine(d + "day " + r.Next(l, u));
            z = z > 5 ? 0 : z + 1; // increments day, resets to 0 after saturday
        }
    }
}

```
> 1 votes

# Answer
**Javascript - 251 chars**

```
d=['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun'],g=function(c){return Math.random()*21+c|0},p=prompt();for(i=0,j=7,t=true;i<j;i++){t=t&&p.indexOf(d[i])!=0;t?j++:console.log(d[i>6?i-7:i]+'day '+g(/mm/.test(p)?20:/g/.test(p)?10:/te/.test(p)?-5:5))}

```

Unfortunately the script does not meet the stdin/stdout requirement but it accepts Fall as a synonym for Autumn.

Whitespaced:

```
  d = [
    'Mon'
  , 'Tues'
  , 'Wednes'
  , 'Thurs'
  , 'Fri'
  , 'Satur'
  , 'Sun'
  ]
, g = function(c) {
    return Math.random()*21+c|0
  }
, p = prompt()

  ;

  for(i = 0, j = 7, t = true; i < j; i++) {
    t = t && p.indexOf(d[i]) != 0;
    t ?
      j++ :
      console.log(d[i > 6 ? i - 7 : i] + 'day ' + g(/mm/.test(p) ?
                                                      20 :
                                                    /g/.test(p) ?
                                                      10 :
                                                    /te/.test(p) ?
                                                      -5 :
                                                      5
                                                    )
                  )
  }

```
> 1 votes

# Answer
# PHP - 150 Characters

```
<?$t=array("m"=>15,"r"=>5,"n"=>-10);for($a=split(" ",fgets(STDIN));$i<7;$i++)echo date("l ",strtotime($a[0]."+$i day")),rand(5,25)+$t[$a[1][2]],"\n";

```

I figured I'd write my own PHP solution after the current one doesn't even fully satisfy the challenge conditions.

It relies on strtotime to parse the day, and date to echo it back. To determine the season, it follows the third letter of the season name, which is unique (as given).

To run properly, it requires notices to be disabled and short tags to be enabled.
> 1 votes

# Answer
# Python 2, 220 characters

A little large but (almost) readable.

```
import random
c,e=raw_input().split()
a=[d+'day'for d in'Mon Tues Wednes Thurs Fri Satur Sun'.split()]*2
x='rmtn'.index(e[2])*2
g=(10,30,20,40,5,25,-5,15)[x:x+2]
f=a.index(c)
for b in a[f:f+7]:
 print b,random.randint(*g)

```

Output

```
# echo "Monday Summer" | python forecast.py
Monday 33
Tuesday 29
Wednesday 33
Thursday 28
Friday 25
Saturday 21
Sunday 30

```
> 1 votes

# Answer
# Mathematica 218

```
s_~g~d_ :=
Grid@RotateLeft[r = Thread@{DateString[{2012, 1, #}, {"DayName"}] & /@ Range@7,
  RandomInteger[Cases[{{"Spring", {10, 30}}, {"Summer", {20, 40}}, {"Autumn", {5, 25}},
  {"Winter", {-5, 15}}}, {s, _}][[1, 2]], 7]}, Position[r, d][[1, 1]] - 1]

```

**Usage**

```
g["Winter", "Sunday"]

```
> 0 votes

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


# Question
Title: Rock-paper-scissors competition simulator
You decided to organize a rock-paper-scissors championship to find out who is the best. You don't want to let luck to decide the winner so everyone has to give you his or her tactic in writing before the competition. You also like simple things so a move of a competitor (showing rock, paper or scissors) has to be based only the previous turn (RvR, RvP, RvS, PvR, PvP, PvS, SvR, SvP or SvS). In the first turn a player has to show a fixed sign.

You decided to write a program (or function) to simulate the championship.

## Details of the competition

* There will be at least 2 contestants.
* Every player plays exactly one match with everyone else.
* One match lasts 7 rounds.
* In every round the winner gets 2 points the loser gets none. In the event of a tie both player score 1 point.
* A players score in a match is the sum of his or her points over the turns of the match.
* A players final score in the championship is the sum of his or her points over all matches.

## Details of the input:

* your program or function receives `N` 10 character long strings each of them corresponds to a players strategy. All characters are (lowercase) `r` `p` or `s` meaning that in the given situation the player will show rock paper or scissors.
* The first letter codes the first turn (in every match for that competitor). The second shows what happens if the last round was rock vs rock. The next ones are RvP, RvS, PvR, PvP, PvS, SvR, SvP and SvS where the first letter is the player's sign and the second is the opponent's. E.g. `rrpsrpsrps` means the player starts with rock and then copies the opponent's last move.
* You can input the list of strings as a list/array or similar data of your language or as one string. In the latter case some kind of separator character is a must.

## Details of the output:

* Your program or function should output the final scores of each player in the same order as the input was supplied.
* Scores should be separated by spaces or newlines. Trailing space or newline is allowed.

## Examples:

Input: `['rrpsrpsrps', 'rpppsprrpr']`

Output: `5 9` (turns are `rvr rvp pvs svp pvr rvp pvs`)

Input: `['rrpsrpsrps', 'rpppsprrpr', 'ssssssssss']`

Output: `13 17 12` (matches are `5-9` (1st vs 2nd), `8-6` (1st vs 3rd) and `8-6` (2nd vs 3rd))

This is code-golf so the shortest entry wins.

# Answer
# Python 2: ~~201~~ 188 chars

```
def f(Q):c=lambda m:'rps'.index(m);l=len(Q);r=[0]*l;i=0;exec'p,q=i/l,i%l;m,n=c(Q[p][0]),c(Q[q][0]);exec"r[p]+=(p!=q)*(m+1-n)%3;m,n=c(Q[p][m*3+n+1]),c(Q[q][n*3+m+1]);"*7;i+=1;'*l*l;return r

```

The logic of the program: I convert the letters to number (`r=0`,`p=1`,`s=2`). `m` is the number of the first, `n` the number of the second person. Because the game is cyclic, `(m-n)%3` already determines the result. And of course, I can shift the result by one `f=(m+1-n)%3`. Now `f=0` means, second player `q` wins, `f=1` means a tie, and `f=2`, first player `p` wins. It also is already the score for player 1. Therefore I only need to add all values `(p!=q)*(m+1-n)%3` for each player.

Test it with `print f(['rrpsrpsrps', 'rpppsprrpr', 'ssssssssss'])`
> 2 votes

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


title: Grow words from fertile vocabularies

text:
# Question
Title: Grow words from fertile vocabularies
An *incremental word chain* is a sequence of words of a vocabulary such that each word is the result of either prepending or appending a single character to the previous word, ignoring capitalization. An example of such a chain can be found below.

> I → is → his → hiss

Your task is to write a program that for a given vocabulary finds the longest incremental word chain. The input is provided from standard input a vocabulary as one word per line. The words are composed of the lowercase letters a to z only. The output of your program shall go to standard output and shall be one word per line a longest word chain of the input vocabulary, starting with the shortest word.

This is code golf, the solution with the least character count wins. Different forms of input or output are not possible, but the terms *standard input* and *standard output* may be interpreted in a reasonable way for the language you are solving this problem in.

Please demonstrate that your code works by publishing the longest word chain you find on the xz-compressed vocabulary found here. This vocabulary was generated by executing the following series of commands on the file *british-english-insane* from the SCOWL project in the C locale:

```
tr 'A-Z' 'a-z' <british-english-insane | sed -n '/^[a-z]*$/p' | sort -u | xz -9e >voc.xz

```

A solution in polynomial time is possible and highly appreciated.

# Answer
### Ruby ~~139~~ 127

```
h={}
$<.map{|l|h[l.strip]=1}
v=->w,c=[]{w<?a?c:h[w]&&(v[w.chop,z=[w]+c]||v[w[1..-1],z])}
puts h.map{|k,_|v[k]||0}.max_by &:size

```

Runs in ~3.5 seconds and prints:

```
r
ra
rah
rahm
brahm
brahma
brahman
brahmani
brahmanis
brahmanism
brahmanisms

```
> 1 votes

# Answer
# Ruby, 127

Runs in about 6.5 seconds. Uses a couple of cool tricks. ARGF (`$<` or stdin, really) is enumerable! If an array is passed as a block argument, it can be "exploded" and assigned to a parameter using `{|w,| ... }`. Notice the comma.

I found an even shorter solution which uses `Array#&` (set intersection) to do the lookup of words, but that runs extremely slow, unfortunately.

Thanks to w0lf for shaving off a few characters

```
D={}
$<.map{|l|D[l.strip!]=l}
puts D.map{|w,|c=[w]
w.chars.all?{w=c[0]
r=D[w.chop]||D[w[1..-1]]
r ?c=[r]+c :p}
c}.max_by &:size

```

### Output

```
r
ra
rah
rahm
brahm
brahma
brahman
brahmani
brahmanis
brahmanism
brahmanisms

```

### Readable version

```
D = {}
$<.lines { |l| D[l.strip] = l.strip }

chains = D.map do |word, _|
  chain = [word]

  word.chars.all? do
    word   = c.first
    result = D[w.chop] || D[w[1..-1]]

    result ? chain.unshift(result) : nil
  end
end

puts chains.max_by(&:size)

```
> 2 votes

# Answer
# Python 2, 208 bytes

Here is a not very small solution. It firsts creates an index of the word parts, then recursively searches for the longest chain.

```
import sys
d={}
b=lambda k:d.setdefault(k,[]).append(e)
for e in sys.stdin:e=e[:-1];b(e[1:]);b(e[:-1])
def f(a):
 g=a
 for c in d.get(a[-1],[]):g=max(g,f(a+[c]),key=len)
 return g
for e in f([''])[1:]:print e

```

It returns:

```
a
ab
rab
arab
arabi
arabin
arabine
carabine
carabiner
carabinero
carabineros

```

in 6.2 seconds.

The code before minifier looks like this:

```
import sys

lookup = {}
addindex = lambda k: lookup.setdefault(k, []).append(word)

for word in sys.stdin :
    word = word[:-1];
    addindex(word[1:]);
    addindex(word[:-1])
print 'Indexed' # DEBUG

def find(wordlist):
    best = wordlist
    for newword in lookup.get(wordlist[-1], []) :
        best = max(best, find(wordlist+[newword]), key=len)
    return best

for word in find([''])[1:] :
    print word

```
> 1 votes

# Answer
# Haskell, 175 Bytes

```
import Data.Set
main=interact$unlines.snd.maximum.g.lines
g l=Prelude.map(f(0,[]))l where f z@(d,r)w|notMember w(fromList l)=z|1<2=max(f(d+1,w:r)(tail w))(f(d+1,w:r)(init w))

```

finds

```
r
ra
ran
fran
franc
franci
francis
francisc
francisca
franciscan
franciscans

```

Spent about 30 bytes for the use of a `Set` data structure for efficient lookups but that are useless (in code golf!) otherwise.

How it works: for every word from the input build recursively a list with valid child words. Take the longest list and print it. A "child word" is the word with either first or last letter missing. It is "valid" if it's in the input. If both child words exist, take the one that builds the longer sublist.
> 1 votes

# Answer
**J: 246 bytes**

```
's p'=:(*(>./i)>:])|:(6 s:[:s:}.;}:)S:0 w[i=:6 s:v=:s:w=:~.a:,<;._2 fread'voc'
l=:[:,([:(#S:0)5 s:_6 s:])"0
f=:3 :'(y{~])^:(~:0:)^:a:"0 y'
q=:_6 s:]
d=:[:+/@:*"1 f
ds=:d s[dp=:d p
n=:(ds<:dp)}s,:p[m=:ds>.dp
echo}:"1 q(r{i),.(r=:([:I.]=>./)m){f n

```

output:

```
`franciscans `franciscan `francisca `francisc `francis `franci `franc `fran `fra `fr `f

```

Version with comments.
> 1 votes

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


title: Keep your distance!

text:
# Question
Title: Keep your distance!
Every player has a number. Can yours be the farthest from them all?

## Requirements

Write a Java, Python 2, or Ruby function named `choose()` that accepts three arguments:

* an integer - the number of rounds already completed
* an integer - the number of players
* an array of strings - the results of each previous round
    + each string is a space-separated list of integers, sorted from lowest to highest

For example, `choose(2, 4, ["4 93 93 174", "1 84 234 555"])` means:

* there were already two rounds (this is the third round)
* there are a total of four players
* in the first round, the numbers chosen were 4, 93, 93, 174
* in the second round, the numbers chosen were 1, 84, 234, 555

You must return a whole number from 1 to 999 (inclusive).

For each other player, your score is the square root of the distance between your number and theirs. Your score for the round is the total of all of these scores.

100 rounds will be played. The highest total score wins!

## Rules

* Your code may not use any I/O, including console, files, network, etc.
* You may not interfere with the control program or any other players.
* Programs which look like they violate the above rules will be excluded.
* Each call of a function should take under five seconds on my computer (Intel Core i5 2450M with 8GB of RAM).
* If a program throws an exception or returns an invalid value, it will be treated as if it returned 1.
* Each user may submit at most one program.

## Miscellaneous

* The control program is on GitHub.
* There are three built-in players. They can be found in this answer.
* The winner will be chosen on January 28.

## Leaderboard

The winner is Conservator.

Honorable mention to Gustav, the highest scoring player with a non-constant strategy.

* Conservator - 36226
* High - 36115
* FloorHugger - 35880
* NumberOne - 35791
* Overestimator - 35791
* Gustav - 35484
* Historian - 35201
* Sampler - 34960
* Incrementer - 34351
* JumpRightIn - 34074
* Vickrey - 34020
* Teenager - 33907
* Randu - 33891
* Weightlifter - 33682
* Middleman - 33647
* BounceInwards - 33529
* NastyMathematician - 33292
* Jumper - 33244
* Copycat - 33049

The full results can be found here. (I recommend disabling text wrapping.)

# Answer
## Python, Conservator

```
def choose(round, players, scores):
    return 999

```

Since every exception throws 1, it stays away as much as possible from it. Makes its fortune at the expense of the weak.

Fun fact: I thought about improving it, but couldn't find a better way than just hiding in a corner.
> 9 votes

# Answer
# Number One, Java

The name explains this one completely.

```
public static int choose(int round, int players, String[] args) {
    return 1;
}

```
> 6 votes

# Answer
# Python, AncientHistorian

Firmly believes that the future will be exactly like the past, but believes the last round is too recent to be histiry, so it just loops through 1 - 999 and chooses what would have been the best the previous rounds exept the last. First 2 round returns 500.

```
def choose(round, players, scores):
    calc = lambda n, scores: sum([abs(int(i)-n)**.5 for i in scores.split(' ')])
    return max(range(1, 1000), key=lambda n: sum([calc(n, j) for j in scores[1:]])) if round>1 else 500

```
> 5 votes

# Answer
# Python, Vickrey

```
def choose(rounds, players, results):
    if not results:
        return (id(0)/7)%999 + 1

    def best(array):
        score = lambda x: sum(abs(x-y)**.5 for y in array)
        m = max(score(x) for x in range(1, 1000))
        return [x for x in range(1, 1000) if score(x) == m]

    def second_best(array):
        array.extend(best(array))
        options = best(array)
        return options[(id(0)/7) % len(options)]

    results = [map(int, s.split()) for s in results]
    counts = {}

    for round_ in results:
        for number in round_:
            counts[number] = counts.get(number, 0) + 1

    most_common = sorted([(c, n) for n,c in counts.items()], reverse=True)
    to_avoid = [t[1] for t in most_common[:players]]

    return second_best(to_avoid)

```

Makes a list of numbers which have been played often, assumes that everyone else will play optimally and opts for the *second* best choice given the list.

For example, if the most common numbers are `[1, 990, 999]`, then Vickrey inserts the optimal play 200 to give `[1, 200, 990, 999]`, then picks the best option for the new array (which is 556).
> 4 votes

# Answer
## Java, Overestimator

As the name suggests, this program assumes all the other programs will try to play "well" by picking the best answer based on the last round - so this "overestimator" always picks the **worst** possible position based on the previous round.

```
 public static int choose(int round, int players, String[] args) {
     String[] lastRoundStrings = args[args.length - 1].split(" ");
     int[] lastRound = new int[lastRoundStrings.length];
     int worstSelection = 0;
     for (int i = 0; i < lastRound.length; i++) {
         double worstScore = Double.MAX_VALUE;
         for (int j = 1; j < 999; j++) {
             double computedScore = score(j, lastRound);
             if (computedScore < worstScore) {
                 worstScore = computedScore;
                 worstSelection = j;
             }
         }
     }
     return worstSelection;
 }

 public static double score(int position, int[] otherPositions) {
     double total = 0;
     for (int i = 0; i < otherPositions.length; i++) {
         total += Math.sqrt(Math.abs(otherPositions[i] - position));
     }
     return total;
 }

```
> 4 votes

# Answer
# Java - Weightlifter

Loops through 1-999 to figure out which would be the best for each round. Weighs them according to recency (recent rounds have more weight), and returns its best overall guess. Hopefully if patterns form in later round, this will be able to pick up on it.

**Edit: Now with +Inf% more recursion!** Not being able to store/save/see what you chose on previous rounds is a drag. Taking your own inputs into account messes you up when trying to figure out what *others* are going to do. So, let's compute it! This will now recurse to figure out what it chose on the previous round and ignore that when calculating the next move.

Note that it only *really* ignores its own input from the last turn, but since that one is weighted the highest, it seems to work okay. This could be fixed with a bit more work, but I'll wait for the leaderboard to see if it's needed.

```
int choose(int rounds, int players, String[] hist){
    if(rounds < 1)
        return 1;

    int lastChoice = choose(rounds-1,players,java.util.Arrays.copyOf(hist, hist.length-1));

    int[][] history = new int[hist.length][players];
    for(int i=0;i<hist.length;i++){
        String[] tokens = hist[i].split(" ");
        boolean flag = false;
        for(int j=0;j<tokens.length;j++){
            history[i][j] = Integer.parseInt(tokens[j]);
            if(i==history.length-1 && history[i][j]==lastChoice && !flag){
                flag = true;
                history[i][j] = -1;
            }
        }
    }

    double best = 0;
    int guess = 1;
    for(int i=1;i<1000;i++){
        double score = 0;
        for(int j=0;j<history.length;j++){
            double weight = (double)(j+1)/history.length;
            for(int k=0;k<history[j].length;k++){
                if(history[j][k] > 0)
                    score += Math.sqrt(Math.abs(history[j][k]-i)) * weight;
            }
        }
        if(score > best){
            best = score;
            guess = i;
        }
    }
    return guess;
}

```
> 4 votes

# Answer
# Ruby, JumpRightIn

```
def choose(round, players, args)
    return 500 if args.size == 0
    last_round = args[-1].split.map(&:to_i) + [1000]
    max_gap = 0
    last = 0
    move = 1
    last_round.each { |i|
        gap = i - last - 1
        if gap > max_gap
            max_gap = gap
            move = (i + last)/2
        end
        last = i
    }
    move
end

```

It's probably the most straight-forward strategy. It finds the largest gap in the last round, and chooses the number right in the middle of that gap.
> 3 votes

# Answer
# Ruby, Copycat

Simply returns whichever number won last time.

```
def choose r, p, hist
  last = hist.last.split.map &:to_i
  scores = last.map{|n| last.map{|m| (n-m).abs ** 0.5 }.inject :+ }
  last[scores.index scores.max]
end

```
> 3 votes

# Answer
# Gustav (Python 2)

This is a pretty straight forward meta strategy, shamelessly copied from one of my old answers in a similar KotH challenge. It considers a few simple strategies, looks how they would have performed over all previous rounds, and then follows the highest scoring one for the next round.

```
def choose(k, N, h):
    if k<2: return 999
    H = [[int(x) for x in l.split()] for l in h]
    score = lambda x,l: sum(abs(x-y)**.5 for y in l)
    S = [range(1,1000)
         + [max(range(1,1000), key=lambda x: score(x, H[i-1]))]
         + [max(range(1,1000), key=lambda x: score(x, H[i-2]))]
         + [min(range(1,1000), key=lambda x: score(x, H[i-1]))]
         + [min(range(1,1000), key=lambda x: score(x, H[i-2]))]
         for i in range(2,k+1)]
    scores = [sum(score(s[j],l) for s,l in zip(S[:-1], H[2:]))
              for j in range(len(S[0]))]
    return max(zip(scores, S[-1]))[1]

```

I realize now that the algorithm still has some flaws. E.g. it might keep "chasing itself" because it does not distinguish its own moves from those of the opponents. However, I'll leave it like this for now.
> 3 votes

# Answer
# Python, Randu

Numbers selected by the most ill-conceived random number generator ever.

```
def choose(round, players, scores):
    x = 15
    for i in range(round * players + 1):
        x = (x * 65539) % 2147483648
    y = int((x / 2147483648.0) * 999.0)+1
    return y

```
> 2 votes

# Answer
The following three programs are built-in.

## High (Ruby)

```
def choose(round, players, args)
    return 990
end

```

## Incrementer (Java)

```
public static int choose(int round, int players, String[] args) {
    return round * 10 + 5;
}

```

## FloorHugger (Python)

```
def choose(round, players, args):
    if len(args) == 0:
        return 10
    last = args[-1].split();

# next line from http://stackoverflow.com/a/7368801/3148067
    last = map(int, last)

    dist = 0
    for i in range(1, 999):
        if i in last:
            dist = 0
        else:
            dist = dist + 1
            if dist == 10:
                return i
    return 500

```
> 1 votes

# Answer
# Python, Sampler

Out of a list of places, choose the one that is farthest away from recently used numbers, ignoring the previous turn.

```
def choose(turn, players, history):
    sample = map(int, (' '.join( history[-5:-1] )).split())
    def distance(x): return sum(abs(x-y)**0.5 for y in sample)
    places = range(1, 1000, 13)
    score, place = max((distance(x), x) for x in places)
    return place

```
> 1 votes

# Answer
## Java, BounceInwards

Starting at 1, it gradually gets closer to 500 while bouncing between the higher and lower option.

```
public static int choose(int round, int players, String[] args) {
    return round%2 == 0 ? round * 5 : 1000 - round * 5;
}

```
> 1 votes

# Answer
## NastyMathematician (Java)

Examines the last two rounds (if the best numbers were 70 and 80, it will output 90). It is nasty because it tries to take as high numbers as possible to win against his opponents.

```
public static int choose(int round, int players, String[] args) {
    if (round == 0) {
        return 999;
    }

    int[][] results = new int[args.length][players];

    // parse input
    for (int i = 0; i < args.length; i++) {
        String[] rounds = args[i].split(" ");
        for (int j = 0; j < rounds.length; j++) {
            results[i][j] = Integer.parseInt(rounds[j]);
        }
    }

    int bestNumber = 0;
    double bestScore = -1;

    // get the best number for the last round
    for (int i = 1; i < 1000; i++) {
        double score = 0;
        for (int result : results[results.length - 1]) {
            score += Math.sqrt(Math.abs(i - result));
        }
        if (score >= bestScore) {
            bestScore = score;
            bestNumber = i;
        }
    }

    if (round == 1) {
        return bestNumber;
    }

    int bestNumber2 = 0;
    double bestScore2 = -1;

    // get the best number for the second last round
    for (int i = 1; i < 1000; i++) {
        double score = 0;
        for (int result : results[results.length - 2]) {
            score += Math.sqrt(Math.abs(i - result));
        }
        if (score > bestScore2) {
            bestScore2 = score;
            bestNumber2 = i;
        }
    }

    // add the difference between last round and second last round to get this rounds best number
    int difference = bestNumber - bestNumber2;
    bestNumber = bestNumber + difference;

    return bestNumber > 999 ? 999 : bestNumber;
}

```
> 1 votes

# Answer
# Python - I don't want to think of a name...

If the average of the numbers chosen in the past rounds is less than 500, it picks 999. It picks 1 otherwise.

```
def choose(a,b,c):
    total=0
    for i in c:
        for j in i.split(" "):
            total+=int(i)
    average=total/(a*b)
    if average<500:
        return 999
    return 1

```
> 1 votes

# Answer
## Python, Middleman (based on conservator by @clabacchio)

```
def choose(round, players, scores):
    return 500;

```

After I noticed that the upper edge scores high (and outperformed the lower edge), I wondered whether there could be anything worse than just getting caught in the middle.
> 0 votes

# Answer
# Jumper (Ruby)

```
def choose(round, players, args)
    495*(round%3)+5
end

```

Alternates between bottom, middle and top. (5,500,995)
> 0 votes

---
Tags: king-of-the-hill
---


title: Binary encryption

text:
# Question
Title: Binary encryption
This is based on xkcd #153.

Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter.

The processing performed must be equivalent to the following:

1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc.
2. For each character in the second parameter, in order, execute the corresponding instruction:
    * `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`.
    * `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`.
    * `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`.
    * `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`.
3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them.

Example (in Python):

```
>>> f("b", "rfu")
01110011

```

It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`).

### Flexibility

Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented.

### Scoreboard

Thanks to @Optimizer for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet".

```
var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|<h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});}
```

```
body { text-align: left !important}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div>
```

# Answer
> 1 votes
# CJam, ~~34~~ 32 bytes

```
1l+256b2b1>l{~"11W:mm%!<>">4%~}/

```

It uses the following characters for instructions:

```
0: left rotation
1: right rotation
2: reverse
3: flip

```

The input is taking from STDIN with the word on the first line and the instruction string on the second line.

Test it here.

## Explanation

Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for.

That's what this part of the code does:

```
1l+256b2b1>

```

Now I read the list of instructions and execute a block for each character in the instruction string:

```
l{...}/

```

The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation:

```
Integer:  Code  Operation
0         1m<   "Left rotation";
1         1m>   "Right rotation";
2         W%    "Reverse";
3         :!    "Flip each bit";

```

I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter:

```
"11W:mm%!<>">4%~

```

First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`.

The bit string is printed automatically at the end of the program.

# Answer
> 2 votes
# CJam, 34 bytes

Another approach in CJam.

```
1l+256b2b1>l_S/,1&@f=_,,@f{W%~}\f=

```

The input text is on the first line and the instructions are on the second line.

Instructions:

```
)        Rotate left.
(        Rotate right.
 (space) Flip.
~        Reverse.

```

# Answer
> 2 votes
## Pyth 33

```
jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z

```

Uses:

```
0    : rotate right
1    : rotate left
2    : reverse order
3    : flip values

```

Pyth github

Try it online here.

This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so:

```
AbC
0321

```

Explanation:

```
                                    : z=input() (implicit)
jk                                  : join("", ...)
  u@[                 )sHw          : reduce(select from [...] the value at int(H), input(), ...)
     +eGPG                          : [ G[-1] + G[:1],
          +tGhG                     : G[1:] + G[1],
               _G                   : G[::-1],
                 ms!dG              : map(lambda d: int(not(d)), G) ]
                          smjCk2z   : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z)

```

Something I couldn't quite squeeze in: Pyth's `reduce` automatically uses `G` for the previous value, and `H` for the next value.

# Answer
> 1 votes
# Matlab (166 bytes)

This uses letters `abcd` instead of `lrfu` respectively.

```
function D=f(B,C)
D=dec2bin(B,8)';
D=D(:);
g=@circshift;
for c=C
switch c-97
case 0
D=g(D,-1);
case 1
D=g(D,1);
case 2
D=char(97-D);
case 3
D=flipud(D);
end
end
D=D';

```

Some tricks used here to save space:

* Using `abcd` letters lets me subtract `97` once, and then the letters become `0`, `1`, `2`, `3`. This saves space in the `switch`-`case` clauses.
* Defining `circshift` as a one-letter anonymous function also saves space, as it's used twice.
* Since `D` consists of `'0'` and `'1'` characters (ASCII codes `48` and `49`), the statement `D=char(97-D)` corresponds to inversion between `'0'` and `'1'` values. Note that this `97` has nothing to do with that referred to above.
* Complex-conjugate transpose `'` is used instead of transpose `.'`.

# Answer
> 1 votes
# Scala - 192

```
def f(i:String,l:String)=(i.flatMap(_.toBinaryString).map(_.toInt-48)/:l){
case(b,'l')⇒b.tail:+b.head
case(b,'r')⇒b.last+:b.init
case(b,'f')⇒b.map(1-_)
case(b,'u')⇒b.reverse}.mkString

```

# Answer
> 0 votes
# Python 2 - 179

```
b="".join([bin(ord(i))[2:]for i in input()])
for i in input():b=b[-1]+b[:-1]if i=="r"else b[1:]+b[0]if i=="l"else[str("10".find(j))for j in b]if i=="f"else b[::-1]
print"".join(b)

```

# Answer
> 0 votes
### C#, 418 bytes

```
using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}}

```

Formatted:

```
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    string F(string a, string o)
    {
        // define string operations
        var f = new Dictionary<char, Func<string, IEnumerable<char>>>
        {
            {'l', s => s.Substring(1) + s[0]},
            {'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)},
            {'u', s => s.Reverse()},
            {'f', s => s.Select(c => (char) (97 - c))}
        };
        // for each operation invoke f[?]; start from converted a
        return o.Aggregate(
            // convert each char to binary string, pad left to 8 bytes and join them
            string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))),
            // invoke f[c] on result of prev operation
            (r, c) => new string(f[c](r).ToArray())
        );
    }
}

```

# Answer
> 0 votes
# JavaScript (E6), 163 ~~167~~

Fully using the input flexibility, a named function with 2 array parameters.

* First parameter, array of bytes corresponding to 7 bit character codes
* Second parameter, array of bytes corresponding to ascii characters 'F','L','R','U' --\> 70, 76, 82, 85

The function returns a character string composed of '1' and '0'

```
F=(a,s,r='')=>
  a.map(c=>r+=(128|c).toString(2).slice(-7))-
  s.map(c=>a=c<71?a.map(c=>1-c):c<77?a.concat(a.shift):c<83?[a.pop(),...a]:a.reverse(),a=[...r])
  ||a.join('')

```

**Example** `f("b", "rfu")` translate to `F([98],[82,70,85])`, result is `0111001`

**Note** using character strings is so much longer in javascript! Byte count **186**

```
F=(a,s,r='')=>
  [for(c of a)r+=(128|c.charCodeAt()).toString(2).slice(-7)]-
  [for(c of(a=[...r],s))a=c<'G'?a.map(c=>1-c):c<'M'?a.concat(a.shift):c<'S'?[a.pop(),...a]:a.reverse()]
  ||a.join('')

```

**Example** `F("b", "RFU")`, result is `0111001` again

# Answer
> 0 votes
## J, 164

```
([: >@:}. (([: }. >&{.) ; >@:{.@:>@:{. 128!:2 >@:}.)^:({.@:$@:>@:{.))@:(>@:((<;._1 ' 1&|."1 _1&|."1 -. |."1') {~ 'lrfu' i. 0&({::)@:]) ; ;@:([: (8$2)&#: a. i. 1&({::)))

```

Formatted:

```
nextop=:([: }. >&{.)
exec=: (>@:{.@:>@:{.) apply"1 >@:}.
times=: ({.@:$@:>@:{.)
gapply=: [: >@:}. (nextop ; exec)^:(times) f.

tobin=: ;@:([: (8#2)&#:(a.i.1&{::))
g=:'1&|.';'_1&|.';'-.';'|.'
tog =:  g {~ ('lrfu' i. 0&{::@:])
golf=: gapply @: (>@:tog;tobin)  f.

```

Example

```
golf ('rfu';'b')
0 1 1 1 0 0 1 1

golf ('lruuff';'b')
0 1 1 0 0 0 1 0

(8#2)#: 98
0 1 1 0 0 0 1 0

golf ('lruuff';'AB')
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0

tobin '';'AB'
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0

```

# Answer
> 0 votes
# Ruby, 151

```
f=->i,s{s.chars.inject(i.unpack("B*")[0]){|a,c|
a.reverse! if c==?u
a.tr!"01","10" if c==?f
a<<a.slice!(1..-1) if c==?l
a<<a.slice!(0..-2) if c==?r
a}}

```

Fairly straightforward. Loops trough the characters in `s` and performs an action for any of them.

# Answer
> 0 votes
## Python 2, 142

```
j="".join
f=lambda S,I:reduce(lambda s,i:[s[1:]+s[0],s[-1]+s[:-1],s[::-1],j([`1^int(c)`for c in s])][int(i)],I,j([bin(ord(c))[2:]for c in S]))

```

Similar to my pyth answer in approach: I build a list of all the strings and index into it based on the value of the instruction string that I iterate over using reduce.

Uses:

```
0  ->  Rotate left
1  ->  Rotate right
2  ->  Reverse order
3  ->  Invert bits

```

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


title: Typing with scrambled keys

text:
# Question
Title: Typing with scrambled keys
Your friend isn't too good with computers so as a practical joke someone scrambled the letters (a-z) on his keyboard. When he sit down and tried to type his name looking at the keyboard he realized that the letters are scrambled and asked your help.

You are smart so you know that if he types his name and then repeatedly retypes what comes up on the screen instead of his name he will succeed inputting in his name eventually. You are also kind and rearrange the keys but want to know how many turns would it take to succeed.

Your task is to write a program or function that given the shuffling of the letters and the friend's name computes the number of turns.

## Input details:

* Two string are given as input in a structure convenient for your language.
* The first string is the list of the new lowercase letters in alphabetical order of the old ones. (The first character is the one that is at the position of `a`, last one is at the position of `z`.) Some change will always occur in the string.
* The second string is the name. It could contain any printable ascii character but only the upper and lowercase alphabetical characters will be shuffled if any. The name itself might not get shuffled at al.

## Output details:

* Output is a single integer the number of turns minimally required. Newline is optional.

## Examples:

Input: `'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe'` (d, e, f positions changed)

Output: `3` (The shown names are: `Mr. John Fod` =\> `Mr. John Eof` =\> `Mr. John Doe` )

Input: `'nopqrstuvwxyzabcdefghijklm' 'Mr. John Doe'` (the ROT13 cipher)

Output: `2` (Any input name that contains letters will take `2` rounds to produce the original name.)

Input: `'aebcdjfghiqklmnopzrstuvwxy' 'John Doe'`

Output: `140`

This is code-golf so the shortest entry wins.

# Answer
> 9 votes
# Pyth, 16 bytes

```
JGfqzuXGJrQ0UTz1

```

Try it here.

Input should be given on two lines, name and then permutation. Permutation should be quoted. Name may be quoted or unquoted. For example:

```
"John Doe"
"aebcdjfghiqklmnopzrstuvwxy"

```

Gives 140.

### Explanation:

```
                            Implicit:
                            z = input()              z is the name.
                            Q = eval(input())        Q is the permutation.
                            G = 'abcdefghijklmnopqrstuvwxyz'

JG                          J = G
  f             1           Starting at 1 and counting upwards, find
                            the first case where the following is true:
   qz                       z ==
     u       UTz            reduce, where the accumulator, G, is initialized to z on
      XG                    translate G
        J                   from the normal alphabet, J
         rQ0                to Q.lower().

```

# Answer
> 10 votes
# CJam, ~~31 27 25~~ 24 bytes

```
l:A;lel:N{_A_$er_N#}g;],

```

Takes input in the form of:

```
aebcdjfghiqklmnopzrstuvwxy
Mr. John Doe

```

i.e. first line - alphabets, second line - name.

**How it works**:

```
l:A;lel:N{_A_$er_N#}g;],
l:A;                         "Read the alphabets from the 1st line in A and pop from stack";
    lel:N                    "Read the name in small caps from 2nd line and store in N";
         {         }g        "Run a while loop until we have the original name back again";
          _                  "Put a dummy string on stack just to keep count of times";
           A                 "Put the alphabets on stack";
            _$               "Copy them and sort the copy to get the correct order";
              er             "Transliterate the right keys with the wrong ones";
                _N#          "Copy the result and see if its equal to the original name";
                     ;]      "Pop the last name and wrap everything in an array";
                       ,     "Get the length now. Since we were putting a dummy string";
                             "on stack in each iteration of the while loop, this length";
                             "represents the number of times we tried typing the name";

```

Try it online here

# Answer
> 5 votes
# Ruby, 58

```
->a,n{t=""+n
(1..2e3).find{t.tr!("a-zA-Z",a+a.upcase)==n}}

```

### Explanation

* Input is taken as arguments to a lambda.
* Use `Enumerable#find` (thanks @Ventero!) and `String#tr!` to replace characters until the replaced `String` matches the real name.

# Answer
> 2 votes
# CJam, ~~32~~ 31 bytes

```
llel_2e3,{;'{,97>3$er_2$=}#)p];

```

Test it here. It takes the permutation on the first line, and the name on the second line of the input.

## Explanation

```
llel_2e3,{;'{,97>3$er_2$=}#)p];
ll                              "Read both lines into strings.";
  el_                           "Convert the name to lower-case and duplicate.";
     2e3,                       "Get a range from 0 to 1999 to cover all possible results.";
         {               }#     "Find the first index where the block yields a true result.";
          ;                     "Discard the number, it's just a dummy.";
           '{,97>               "Create a string of the lower-case alphabet.";
                 3$             "Copy the permutation.";
                   er           "Substitute letters in the second copy of the name.";
                     _2$=       "Duplicate and check for equality with original name.";
                           )p   "Increment by 1 and print.";
                             ]; "Clear the stack to prevent extraneous output.";

```

# Answer
> 2 votes
## Pyth 26

```
KGJ@GrQZfqJusm@zxKdGUTJ!!J

```

Try it online here.

There are quite a few unfortunate consequences that cost this program bytes, like having to store G in K to use it in the reduce, as well as needing to use not(not(J)) to start the filter. Because of this, I expect this can still be golfed.

This is a program that takes input like:

```
aebcdjfghiqklmnopzrstuvwxy
'John Doe'

```

(Note the lack of quotes in the first argument)

Explanation to come after crippling exhaustion ;)

# Answer
> 2 votes
# Haskell 131 bytes

```
import Data.Char
h n=(!!((ord n)-97))
g s n m|n==m=1|0<1=1+g s(h n s)m
f s=foldr1 lcm.map((\x->g s(h x s)x).toLower).filter isAlpha

```

Call `f` with the permutation string and name to get the result

### Explanation

```
-- h finds the mapping of a character given the permutation
h :: Char   -> -- Character to map
     String -> -- Character permutation
     Char      -- Mapped character

-- g finds the number of character mappings required to reach a given character
-- by calling h on the given character every time it calls itself.
g :: String -> -- The character permutation
     Char   -> -- The current character
     Char   -> -- The character to find
     Int       -- The number of mapped to find the character

-- f finds the number of mappings required to return the given string back to itself
-- by finding the lowest common multiple of the period of all the characters in the
-- given string
g :: String -> -- The permutation string
     String -> -- The string to get back
     Int       -- The final answer

```

# Answer
> 1 votes
## GolfScript (33 bytes)

```
~{32|}%\:A&{.{A$?A=}%.-1$=!}do],(

```

Takes input as two (single- or double-) quoted strings separated by any amount of whitespace; e.g.

```
'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe'

```

Online demo

### Dissection

```
~           # Eval. Stack: perm name
{32|}%      # Lower-case name (also affects non-alphabetic characters but...)
\:A&        # Store perm in A and filter name to alphabetic characters, giving str_0
{           # do-while loop. Stack: str_0 str_1 ... str_i
  .         #   Duplicate str_i
  {A$?A=}%  #   tr 'a-z' perm   giving str_{i+1}
  .-1$=!    #   Loop while str_{i+1} != str_0
}do         # end do-while loop
],(         # Gather the sequence of permuted strings in an array and take its length - 1
            # to account for containing str_0 twice

```

The transliteration relies on the fact that all the characters are affected (it's `{'ABC'?'abc'=}%` with the sorted string `A$` replacing `'ABC'` and the permutation `A` replacing `'abc'`); the more general alternatives don't save enough because the filter to alphabetic characters is so cheap.

This also relies on `-1$` to access the bottom of the stack, which is a relatively rare GS trick.

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


# Question
Title: Ordering an array of negatives, zero and positives integers with one iteration
Take an array of integers containing negative numbers, positive numbers and zeros. Group it **with one iteration and in place** such that all of the negative numbers come first, followed by all of the zeros, followed by all of the positive numbers.

Example:

```
Input:  5, 3, 0, -6, 2, 0, 5
Output: -6, 0, 0, 3, 2, 5, 5

```

Note that the numbers do not need to be fully sorted: just sorted by sign.

So, the final array will look like this: `-, -, ..., -, -, 0, 0, ..., 0, 0, +, +, ..., +, +`

### Rules

* You may only use the input array and a constant amount of additional memory (i.e. you may not create any more arrays)
* You may only use one loop, which may execute only as many times as the length of the array. You may not use built-in functions which conceal any kind of loop. This includes built-in sort functions.
* The result should be in the format I described

The winner will be the person who will submit the shortest code (counted in bytes) that changes the initial array into a correct format (like described above).

# Answer
# C, 92

This could probably be reduced by at least 10 bytes; there are many expressions going to waste.

The first argument should point to the beginning of the array; the second should point after the end of the array.

```
*x;f(b,e)int*b,*e;{for(x=b;x<e;x++)*x>0&&--e-x?*x--^=*e^=*x^=*e:*x<0?b-x?*x^=*b=*x:0,b++:0;}

```

Ungolfed with random test generator:

```
*x;
f(b,e)int*b,*e;{
    for(x=b;x<e;x++) {
        if(*x<0) {
            if(b == x)
                b++;
            else
                *b++ = *x, *x=0;
        } else if(*x>0 && x != --e) {
            *x^=*e^=*x^=*e;
            x--;
        }
    }
}

int main()
{
    int a[999];
    srand(time(0));
    int n = rand() % 50;
    int i;
    for(i = 0; i < n; i++) printf("%d ", a[i] = rand() % 9 - 4);
    f(a, a+n);
    puts("");
    for(i = 0; i < n; i++) printf("%d ", a[i]);
    return 0;
}

```
> 3 votes

# Answer
## STATA 242

Follows the wikipedia page exactly. Thanks @PeterTaylor

Takes input as a space separated set of numbers from std in and outputs as such as well to std out.

```
di _r(a)
token $a//converts to array (kind of)
loc i=0
loc j=0
loc q=wordcount($a)
loc n=`q'-1
while `j'<=`n' {
loc t=``j''
if `t'<0{
loc `j'=``i''
loc `i'=`t'
loc ++i
loc ++j
}
else if `t'>0{
loc `j'=``n''
loc `n'=`t'
loc --n
}
else
loc ++j
}
//used only to output
forv x=1/`q'{
di ``x'' _c
}

```
> 1 votes

# Answer
# Python 2: 116 bytes

```
a=input();i=j=0;n=len(a)
while j<n:b=a[j];r,s=b<0,b>0;c=i*r+n*s-s+j*(b==0);a[c],a[j]=b,a[c];i+=r;n-=s;j+=b<1
print a

```

This is a golfed Python translation of the Dutch national flag pseudo-code.

# Possible 112 bytes

Not sure, if this is allowed. It creates a second array of size 3 (constant amount of additional memory!).

```
a=input();i=j=0;n=len(a)-1
while j<=n:b=a[j];k=(i,j,n)[cmp(b,0)+1];a[k],a[j]=b,a[k];i+=b<0;n-=b>0;j+=b<1
print a

```
> 1 votes

# Answer
# C,90

Straightforward implementation of the algorithm in the wikipedia article per Peter Taylor's comment on the question.

Expects to find the data in an array called `a` like the other C answer. `n`,`p` and `z` are pointers for the insertion of negative and positive numbers and zeroes. `n` and `p` are taken as arguments pointing to the first and last elements of the data.

```
f(n,p){int t,z;for(z=n;p-z;z++)(t=a[z])?a[z]>0?a[z]=a[p],a[p--]=t:(a[z]=a[n],a[n++]=t):0;}

```
> 1 votes

# Answer
# ECMAScript 157 Bytes

Takes the numbers as space separated or comma separated set from a prompt dialog and returns the result with a alert dialog.

```
for(v=prompt().split(/,?\s+/),s=function(j,n){t=v[j],v[j]=v[n],v[n]=t},i=j=0,n=v.length-1;j<=n;)
!(~~v[j]<0&&!s(i++,j++)||~~v[j]>0&&!s(j,n--))&&j++;alert(v);

```
> 1 votes

# Answer
# Rebol - ~~149~~ ~~142~~ 140

```
a: to-block input i: j: 1 n: length? a while[j <= n][case[a/:j < 0[swap at a ++ i at a ++ j]a/:j > 0[swap at a j at a -- n]on[++ j]]]print a

```

This is a direct port of the Dutch national flag wikipedia pseudocode. Below is how it looks ungolfed:

```
a: to-block input
i: j: 1
n: length? a

while [j <= n] [
    case [
        a/:j < 0 [swap at a ++ i at a ++ j]
        a/:j > 0 [swap at a j at a -- n]
        on       [++ j]
    ]
]

print a

```

Usage example:

```
rebol dutch-flag.reb <<< "5 3 0 -6 2 0 5"
-6 0 0 2 3 5 5

```

NB. Rebol arrays (blocks) don't use commas - `[5 3 0 -6 2 0 5]`

And if its OK wrap this up into a function which takes an array and modifies it in place then we can get it down to 128 chars:

```
>> f: func[a][i: j: 1 n: length? a while[j <= n][case[a/:j < 0[swap at a ++ i at a ++ j]a/:j > 0[swap at a j at a -- n]on[++ j]]]n]

>> array: [5 3 0 -6 2 0 5]
== [5 3 0 -6 2 0 5]

>> print f array
-6 0 0 2 3 5 5

>> ;; and just to show that it as modified array

>> array
== [-6 0 0 2 3 5 5]

```

In fact if didn't need to return array (ie. just modify) then you could shave off 1 more char.
> 0 votes

# Answer
# PHP (146)

```
function f($s){for($i=0,$n=count($s)-1;$j++<=$n;)if($k=$s[$j]){$l=$k>0?n:i;$x=$s[$$l];$s[$$l]=$k;$s[$j]=$x;$k>0?$n--|$j--:$i++;}echo print_r($s);}

```

http://3v4l.org/ivRX5

PHP's relatively verbose variable syntax is a bit painful here...
> 0 votes

# Answer
## C++

Un-golfed solution: n counts the negatives added to front of array. For each element if negative swap with element at n, if zero swap with element at n+1 else swap with last element.

```
void p(int* k,int n)
{
for(int i=0;i<n;i++)
{
cout<<*(k+i)<<' ';
}
cout<<endl;
}

void s(int *x,int i,int j)
{
int t=*(x+j);
*(x+j)=*(x+i);
*(x+i)=t;
}
void f(int *x,int L)
{
int n=0;
int k;
for(int i=1;i<L;i++)
{
k=*(x+i);
if(k<0)
{
s(x,i,n);
n++;
}
else if(k==0)
{
s(x,i,n+1);
}
else if(k>0)
{
s(x,i,L-1);
}
}
}

int main()
{
int x[]={5,2,-1,0,-2,4,0,3};
f(x,8);
p(x,8);
return 0;
}

```
> 0 votes

# Answer
# CJam - ~~72~~ 67

```
q~_,(:N;{_U=:B0>{U1$N=tNBtN(:N;}{B{U1$T=tTBtT):T;}{}?U):U;}?UN>!}gp

```

Input: `[5 3 4 0 -6 2 0 5]`
Output: `[-6 0 0 4 2 3 5 5]`

Try it at http://cjam.aditsu.net/

**Explanation:**

This is another implementation of the algorithm from wikipedia, using `T` for `i` and `U` for `j` (both automatically initialized to 0).

```
q~                    read and evaluate the array (let's call it "A")
_,(:N;                keep A on the stack and set N ← size of A - 1
{                     do...
    _U=:B             keep A on the stack and set B ← A[U] (also leaving B on the stack)
    0>{               if B > 0
        U1$N=t        A[U] ← A[N]
        NBt           A[N] ← B
        N(:N;         N ← N - 1
    }{                else
        B{            if B ≠ 0
            U1$T=t    A[U] ← A[T]
            TBt       A[T] ← B
            T):T;     T ← T + 1
        }{            else (do nothing)
        }?            end if
        U):U;         U ← U + 1
    }?                end if
UN>!}g                ...while not (U > N)
p                     print representation of A

```
> 0 votes

---
Tags: code-golf, number, sorting, array
---


title: Golfing at the Bank

text:
# Question
Title: Golfing at the Bank
Our new bank needs a teller transaction system but there is a problem. There is only a few hundred bytes of space left on our server, so you will have to write very compact code.

## Database

Thankfully our database is very simple (it was built by the schoolboy son of our bank president), and we only have a few customers so far.

file `Bank.data` is:

```
Account Firstname Lastname Balance Date
123 Maree Jones 346.22 2014-12-13
035 Thomas Breakbone 3422.02 2015-01-03
422 Henrietta Throsby-Borashenko 277847.74 2014-11-21
501 Timmy Bongo 7.95 2014-11-04
105 William Greene 893.00 2015-01-06
300 Mary Galoway 1228.73 2014-12-28
203 Samantha Richardson 2055.44 2014-11-01
151 Bruce Wayne 956119.66 2014-10-09
166 Chip Stonesmith 266.71 2014-12-15
888 Alexandria Cooper 1299.82 2014-12-30

```

## Application Specification

Our bank application must implement the following commands:

`open <firstname> <lastname>` Creates (opens) a new account printing a unique 3 digit account number.

`withdraw <account> <amount>` Withdraw amount from an account.

`deposit <account> <amount>` Deposit amount into an account.

`close <account>` Close account if empty.

`report <fieldname>` Print a report of the database sorted by fieldname. Move the fieldname column to the first position. Each column width will be the maximum of the widest data and fieldname width, separated by one space. The first line will be the field titles. The balances only must be right justified with a leading `$` sign.

`print <account>` Print the fieldnames and record for this account formated like the report.

Each time a record is changed, the `Date` field in the record must be updated to the current date.

The application will show a "# " prompt when waiting for a command. If a command fails (such as an operation on an unknown account or insufficient funds), the application must print the informative error message "failed". The program must write changes back to the file after each change, and read from the file on each command as there are many teller programs around the world operating on the file concurrently (we don't need file locking - that may reduce performance).

**EDIT:** String fields are simple ASCII (a-z,A-Z,-) without white space and the amount will always be between 0.00 and 1000000000.00 (1 billion) dollars with 2 decimal places indicating cents. The date will be in local time at each branch (a simple solution but may lead to some problems later...).

## Output

Answers will need to demonstrate that they meet the specification. Please attach the output from your program after processing the following commands:

```
report Balance
open Clark Kent
print 001
deposit 001 4530
withdraw 105 893
close 105
report Date

```

Ensure you use an original copy of the `Bank.data` file given above.

## Scoring

This is code-golf, so your score will be the byte count of your code. Standard loopholes are prohibited.

# Answer
# Ruby, 918

This question is quite long to golf as it consists of many small parts. For a moment, I almost wanted to define some additional classes to make things neater with polymorphism etc... (but in the end I didn't).

```
l=->a,i{a.map{|x|x[i].to_s.size}.max}
y=1..-1
d=File.open(f="bank.data").each.map(&:split)
j=[k=%w{Account Firstname Lastname Balance Date}]
_=->{puts"Failure"}
q=->t,v=0{z=-1;puts t.map{|r|([v]+((0..4).to_a-[v])).map{|c|b=l[t,c];c!=3?r[c].ljust(b):(?$*(z+=z<1?1:0)+r[c]).rjust(b>7?b+1:b)}*' '}}
w=->d{File.open(f,?w).write(d.map{|x|x*' '}*?\n)}
s=->i,m=!0{o=d.select{|r|r[0]==i};o==[]?_[]:m ?q[[k]+o]:1}
u=->{Time.now.to_s[0..9]}
($><<"# ";i=gets.split;o=i.size;("report"==h=i[0])?((v=k.index i[1])?q[j+d[y].sort_by{|x|v!=3?x[v]:x[v].to_f},v]:_[]):h=="print"?s[i[1],0]:h=="close"?(s[m=i[1]]?w[d=j+d[y].select{|r|r[0]!=m}]:0):h=="open"?((o==3&&t=((1..999).map{|x|'%03d'%x}-d.map{|x|x[0]})[0])?(w[d=d+[[t,i[1],i[2],'0.00',u[]]]];puts t):_[]):h=="withdraw"||h=="deposit"?(o==3&&s[i[1]]?w[d=j+d[y].map{|r|i[1]==r[0]?(b=(c=r[3].to_f)+i[2].to_f*(i[0][0]==?w?-1:1);0>b&&(b=c;_[]);r[0..2]+["%.2f"%b,u[]]):r}]:_[]):_[])while 1

```

Probably can be golfed further. But as of now, I can't even keep track of what I did in the last line.

Output:

```
# report Balance
   Balance Account Firstname  Lastname           Date
     $7.95 501     Timmy      Bongo              2014-11-04
   $266.71 166     Chip       Stonesmith         2014-12-15
   $346.22 123     Maree      Jones              2014-12-13
   $893.00 105     William    Greene             2015-01-06
  $1228.73 300     Mary       Galoway            2014-12-28
  $1299.82 888     Alexandria Cooper             2014-12-30
  $2055.44 203     Samantha   Richardson         2014-11-01
  $3422.02 035     Thomas     Breakbone          2015-01-03
$277847.74 422     Henrietta  Throsby-Borashenko 2014-11-21
$956119.66 151     Bruce      Wayne              2014-10-09
# open Clark Kent
001
# print 001
Account Firstname Lastname Balance Date
001     Clark     Kent       $0.00 2015-02-01
# deposit 001 4530
# withdraw 105 893
# close 105
# report Date
Date       Account Firstname  Lastname              Balance
2014-10-09 151     Bruce      Wayne              $956119.66
2014-11-01 203     Samantha   Richardson           $2055.44
2014-11-04 501     Timmy      Bongo                   $7.95
2014-11-21 422     Henrietta  Throsby-Borashenko $277847.74
2014-12-13 123     Maree      Jones                 $346.22
2014-12-15 166     Chip       Stonesmith            $266.71
2014-12-28 300     Mary       Galoway              $1228.73
2014-12-30 888     Alexandria Cooper               $1299.82
2015-01-03 035     Thomas     Breakbone            $3422.02
2015-02-01 001     Clark      Kent                 $4530.00
#

```
> 1 votes

# Answer
# Cobra - 1505

```
class P
    var m='Account Firstname Lastname Balance Date'
    def main
        while[d=DateTime.now.toString('yyyy-MM-dd'),z='0.00']
            print'#'stop
            try,branch (c=Console.readLine.split)[r=0]
                on'open'
                    post while u in for x in.f get x[0],u=(r+=1).toString('000')
                    print u
                    .f=.f.toList+[@[u,c[1],c[2],z,d]]
                on'deposit'or 'withdraw'
                    n=.z(if(c[0]>'deposit','-','')+c[2])
                    assert.z(.i(c[1])[3])+n>=0
                    .f=for x in.f get if(x[0]==c[1],@[x[:3].join(' '),'[(.z(x[3])+n).toString(z)]',d],x)
                on'close'
                    assert.i(c[1])[3]==z
                    .f=for x in.f where.i(c[1])<>x
                on'report',.a(.f,c[1])
                on'print',.a([.i(c[1])])
                else,assert 0
            catch
                print'failed'
    def z(s='')as float
        return float.parse(s)
    pro f as String[]?*
        get
            return for x in File.readAllLines('Bank.data')[1:]get x.split
        set
            File.writeAllLines('Bank.data',[.m]+for x in value get x.join(' '))
    def a(f as String[]?*,c='Account')
        i,l=(m=.m.split).toList.indexOf(c),[7,9,8,8,4]
        assert c in m
        print (for q in (for z in (for x in[m]+f.toList.sorted(do(a as String[],b as String[]))get for y in 5 get[t=try' '.repeat(l[y]-x[y].length)catch get'',if(y-3,x[y]+t,t+if(x==m,' ','$')+x[y])][1])get[z[i]]+for p in z where p<>z[i])get q.join(' ')).join('\n')
            for v in[a,b],for k in 5,if (u=v[k].length)>l[k],l[k]=u
            return[d=a[i].compareTo(b[i]),d,d,.z(a[3]).compareTo(.z(b[3])),DateTime.parse(a[4]).compareTo(DateTime.parse(b[4]))][i]
    def i(s='')as String[]?
        return (for x in.f where x[0]==s)[0]

```

Output:

```
#report Balance
   Balance Account Firstname  Lastname           Date
     $7.95 501     Timmy      Bongo              2014-11-04
   $266.71 166     Chip       Stonesmith         2014-12-15
   $346.22 123     Maree      Jones              2014-12-13
   $893.00 105     William    Greene             2015-01-06
  $1228.73 300     Mary       Galoway            2014-12-28
  $1299.82 888     Alexandria Cooper             2014-12-30
  $2055.44 203     Samantha   Richardson         2014-11-01
  $3422.02 035     Thomas     Breakbone          2015-01-03
$277847.74 422     Henrietta  Throsby-Borashenko 2014-11-21
$956119.66 151     Bruce      Wayne              2014-10-09
#open Clark Kent
001
#print 001
Account Firstname Lastname   Balance Date
001     Clark     Kent         $0.00 2015-02-04
#deposit 001 4530
#withdraw 105 893
#close 105
#report Date
Date       Account Firstname  Lastname              Balance
2014-10-09 151     Bruce      Wayne              $956119.66
2014-11-01 203     Samantha   Richardson           $2055.44
2014-11-04 501     Timmy      Bongo                   $7.95
2014-11-21 422     Henrietta  Throsby-Borashenko $277847.74
2014-12-13 123     Maree      Jones                 $346.22
2014-12-15 166     Chip       Stonesmith            $266.71
2014-12-28 300     Mary       Galoway              $1228.73
2014-12-30 888     Alexandria Cooper               $1299.82
2015-01-03 035     Thomas     Breakbone            $3422.02
2015-02-04 001     Clark      Kent                 $4530.00

```
> 2 votes

# Answer
## T-SQL 1919

Called with "exec q 'Your command here'" I don't think T-SQL can actually get user input, so I think this is as close as it can be.

Uses the bcp utility for I/O which I haven't tried before because it comes with SQL Server 2014.

I'm not sure if it would be better or worse to use only the main stored procedure and put the rest of the code in there.

```
CREATE PROC q @ CHAR(99)AS
CREATE TABLE ##(A CHAR(3),F CHAR(99),L CHAR(99),B MONEY,D DATE)bcp ## in Bank.data -t " " -T
DECLARE @g INT,@w MONEY,@z CHAR(9),@y CHAR(99),@x CHAR(99)SET @g=patindex('% %',@)SET @z=substring(@,1,@g-1)SET @=substring(@,@g+1,99)SET @g=patindex('% %',@)SET @y=substring(@,1,@g-1)SET @=substring(@,@g+1,99)SET @g=patindex('% %',@)SET @x=substring(@,1,@g-1)SET @w=CONVERT(MONEY,@x)*2*(LEN(@z)-7.5)IF @z='open'exec o @y,@x
IF @z='close'exec c @y
IF @z='withdraw'exec w @y,@w
IF @z='deposit'exec w @y,@w
IF @z='print'exec p @y
IF @z='report'exec r @y
bcp ## out Bank.data -t " " -T
SELECT'#'
CREATE PROC r @q CHAR(9)AS
DECLARE @a char(9)='A Account',@f char(11)='F Firstname',@l char(10)='L Lastname',@b char(45)='CONCAT(''$'',SPACE(9-LEN(B)),B) Balance',@d char(6)='D Date',@ varchar(999)='SELECT '
IF @q='Account'SET @+=@a+','+@f+','+@l+','+@b+','+@d
IF @q='Balance'SET @+=@b+','+@a+','+@f+','+@l+','+@d
IF @q='Date'SET @+=@d+','+@a+','+@f+','+@l+','+@b
IF @q='Lastname'SET @+=@l+','+@a+','+@f+','+@b+','+@d
IF @q='Firstname'SET @+=@f+','+@a+','+@l+','+@b+','+@d
IF LEN(@)<9
BEGIN
SELECT'failed'RETURN
END
SET @+=' FROM ## ORDER BY '+@q
exec(@)CREATE PROC p @ CHAR(3)AS
DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@)IF @r IS NULL SELECT'failed'ELSE SELECT*FROM ## WHERE A=@
CREATE Proc o @f CHAR(99),@l CHAR(99)AS
DECLARE @ INT=0,@r CHAR(9)=(SELECT 1 FROM # WHERE A='000')WHILE @r IS NOT NULL
BEGIN

SET @+=1
SET @r=(SELECT 1 FROM # WHERE CONVERT(INT,A)=@)END
IF @>999 SELECT'failed'ELSE INSERT INTO # OUTPUT Inserted.A VALUES(REPLICATE('0',3-LEN(@))+CONVERT(CHAR(3),@),@f,@l,0,GETDATE())CREATE PROC w @ CHAR(3),@b MONEY AS
DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@ AND B>@b)IF @r IS NULL SELECT'failed'ELSE UPDATE ## SET B=B-@b,D=GETDATE()WHERE A=@
CREATE Proc c @q CHAR(3)AS
DECLARE @r CHAR(9)=(SELECT 1 FROM ## WHERE A=@q AND B=0)IF @r IS NULL SELECT'failed'ELSE DELETE FROM ## WHERE A=@q

```
> 2 votes

# Answer
# Python 2 - 2205 bytes

Here is a rather verbose attempt at a solution.

```
import sys, time, re
def db(recs):
    text = '\n'.join(' '.join(row) for row in [titles]+recs)
    open('Bank.data', 'wt').write(text+'\n')
def wid(col, recs):
    w = max(len(r[col]) for r in [titles]+recs)
    return w if col == 3 else -w
while 1:
    inp=raw_input('# ').split()
    try:
        cmd = inp.pop(0)
        data = [d.split() for d in open('Bank.data', 'rt').readlines()]
        titles = data.pop(0)
        today = '-'.join('%02u' % v for v in time.localtime()[:3])
        alist = set(int(r[0]) for r in data)
        if cmd == 'open':
            assert re.match(r'[-a-zA-Z]{2,}', inp[0]+inp[1])
            acct = '%03u'%([n for n in range(1, 1000) if n not in alist][0])
            rec = [acct] + inp + ['0.00', today]
            db(data+[rec])
            print acct
        elif cmd == 'withdraw':
            a, m = inp[0], float(inp[1])
            rec = [r for r in data if r[0] == a][0]
            b = float(rec[3])
            assert b >= m
            rec[3] = '%.2f' % (b-m)
            rec[4] = today
            db(data)
        elif cmd == 'deposit':
            a, m = inp[0], float(inp[1])
            rec=[r for r in data if r[0]==a][0]
            rec[3]='%.2f'%(float(rec[3])+m)
            rec[4]=today
            db(data)
        elif cmd=='close':
            rec=[r for r in data if r[0]==inp[0]][0]
            assert int(rec[3])==0
            data=[r for r in data if r!=rec]
            db(data)
        elif cmd=='report':
            for r in data: r[3]='$'+r[3]
            fmtlist=['%'+str(wid(c,data))+'s' for c in range(5)]
            loc=titles.index(inp[0])
            for r in data: r.insert(0,r.pop(loc))
            data.sort(key=lambda x: float(x[0][1:]) if loc==3 else x[0])
            titles.insert(0,titles.pop(loc))
            fmtlist.insert(0,fmtlist.pop(loc))
            for r in [titles]+data: print ' '.join(fmtlist)%tuple(r)
        elif cmd=='print':
            for r in data: r[3]='$'+r[3]
            rec=[r for r in data if r[0]==inp[0]][0]
            fmt=' '.join('%'+str(wid(c,[rec]))+'s' for c in range(5))
            for r in [titles,rec]: print fmt%tuple(r)
        else: raise()
    except:
        print 'failed'

```

Here is a sample of the application in use:

```
# report Balance
   Balance Account Firstname  Lastname           Date
     $7.95 501     Timmy      Bongo              2014-11-04
   $266.71 166     Chip       Stonesmith         2014-12-15
   $346.22 123     Maree      Jones              2014-12-13
   $893.00 105     William    Greene             2015-01-06
  $1228.73 300     Mary       Galoway            2014-12-28
  $1299.82 888     Alexandria Cooper             2014-12-30
  $2055.44 203     Samantha   Richardson         2014-11-01
  $3422.02 035     Thomas     Breakbone          2015-01-03
$277847.74 422     Henrietta  Throsby-Borashenko 2014-11-21
$956119.66 151     Bruce      Wayne              2014-10-09
# open Clark Kent
001
# print 001
Account Firstname Lastname Balance Date
001     Clark     Kent       $0.00 2015-01-13
# deposit 001 4530
# withdraw 105 893
# close 105
# report Date
Date       Account Firstname  Lastname              Balance
2014-10-09 151     Bruce      Wayne              $956119.66
2014-11-01 203     Samantha   Richardson           $2055.44
2014-11-04 501     Timmy      Bongo                   $7.95
2014-11-21 422     Henrietta  Throsby-Borashenko $277847.74
2014-12-13 123     Maree      Jones                 $346.22
2014-12-15 166     Chip       Stonesmith            $266.71
2014-12-28 300     Mary       Galoway              $1228.73
2014-12-30 888     Alexandria Cooper               $1299.82
2015-01-03 035     Thomas     Breakbone            $3422.02
2015-01-13 001     Clark      Kent                 $4530.00
#

```
> 1 votes

# Answer
## STATA 1506

Didn't try to golf it too much. I figured a statistical language would be better at this, but apparently.

```
set more off
while 1<2{
qui insheet using Bank.data,delim(" ")clear case
form A %-03.0f
form B %10.2f
form D %-10s
form F %-50s
form L %-50s
g K="$"+string(B,"%10.2f")
di"#",_r(q)
loc s: di %tdCCYY-NN-DD date(c(current_date),"DMY")
if word("$q",1)=="open"{
forv x=0/999{
egen c=anymatch(A),v(`x')
if c<1{
egen m=min(A)
cap expand 2 if A==m,gen(z)
replace A=`x' if A==m&z>0
replace B=0 if A==`x'
replace F=word("$q",2) if A==`x'
replace L=word("$q",3) if A==`x'
replace D="`s'" if A==`x'
di"`x'"
outsheet A-D using Bank.data,delim(" ")replace
continue, br
}
if `x'==999{
di"failed"
}
drop c
}
continue
}
if word("$q",1)=="report"{
ren B R
ren K Balance
if word("$q",2)=="Account"{
so A
l A-L B D,clean noo
}
else if word("$q",2)=="Date"{
so D
l D A-L B,clean noo
}
else if word("$q",2)=="Lastname"{
so L
l L A F B D,clean noo
}
else if word("$q",2)=="Balance"{
so R
l B A-L D,clean noo
}
else if word("$q",2)=="Firstname"{
so F
l F A L B D,clean noo
}
else{
di"failed"
}
continue
}
gen i=real(word("$q",2))
egen p=min(abs(A-i))
if p>0{
di"failed"
continue
}
if word("$q",1)=="close"{
egen c=count(i)
drop if A==i&B==0
qui cou
if c==r(N){
di"failed"
continue
}
}
if word("$q",1)=="print"{
drop Balance
ren K Balance
l A-L B D if A==i,noo clean ab(9)
continue
}
gen j=real(word("$q",3))
if word("$q",1)=="withdraw"{
replace B=B-j if A==i
egen c=min(B)
if c<0{
di"failed"
continue
}
}
if word("$q",1)=="deposit"{
replace B=B+j if A==i
}
replace D="`s'" if A==i
outsheet A-D using Bank.data,delim(" ")replace
}

```
> 1 votes

# Answer
## Batch - 1827

Batch is not built for this kind of thing.

```
@echo off&setLocal enableDelayedExpansion&set B=Bank.data&echo wscript.echo eval(wscript.arguments(0))>%temp%\eval1.vbs&set Z=goto :EOF&set V=call&set F=for /l %%a in (1,1,
:m
set C=-1&set D=%date:~-4%-%date:~-7,2%-%date:~-10,2%
for /f "tokens=1-5" %%a in (%B%)do set/aC+=1 &set !C!=%%a %%b %%c %%d %%e&set !C!n=%%a&set !C!f=%%b&set !C!s=%%c&set !C!b=%%d&set !C!d=%%e&set A=%%a&set/aA+=1
set/pI="#"
%V% :%I% 2>nul||echo failed&goto m
goto m
:open
echo %A% %1 %2 0.00 %D%>>%B%&echo %A%&%Z%
:close
echo !0!>%B%&%F%!C!)do if "!%%an!" NEQ "%1" (echo !%%a!>>%B%)else if !%%ab! GTR 0.00 echo failed & echo !%%a!>>%B%
%Z%
:deposit
%F%!C!)do if "!%%an!"=="%1" set p=%%a
%V% :c "!%p%b!+%2"
set %p%b=%r%&set %p%d=%D%&%V% :u
%Z%
:withdraw
%F%!C!)do if "!%%an!"=="%1" set p=%%a
%V% :c "!%p%b!-%2"&if "%r:~0,1%"=="-" echo failed&%Z%
set %p%b=%r%&set %p%d=%D%&%V% :u
%Z%
:report
for /l %%a in (1,1,50)do set H= !H!
for /l %%a in (0,1,!C!)do (
%V% :l !%%an!&set %%anl=!l!&if !l! GTR !tn! set/atn=!l!
%V% :l !%%af!&set %%afl=!l!&if !l! GTR !tf! set/atf=!l!
%V% :l !%%as!&set %%asl=!l!&if !l! GTR !ts! set/ats=!l!
%V% :l !%%ab!&set %%abl=!l!&if !l! GTR !tb! set/atb=!l!
)
for /l %%a in (0,1,!C!)do %V% :c "%tn%-!%%anl!"&set sn=!r:~0,-3!&%V% :t !sn!&set pn=!x!&%V% :c "%tf%-!%%afl!"&set sf=!r:~0,-3!&%V% :t !sf!&set pf=!x!&%V% :c "%ts%-!%%asl!"&set ss=!r:~0,-3!&%V% :t !ss!&set ps=!x!&%V% :c "%tb%-!%%abl!"&set sb=!r:~0,-3!&%V% :t !sb!&set pb=!x!&echo !%%an!!pn! !%%af!!pf! !%%as!!ps! !pb!$!%%ab! !%%ad!
%Z%
:l
set S=%1&for /f usebackq %%a in (`Powershell "'!S!'.Length"`)do set l=%%a
%Z%
:t
set x=!H:~0,%1!
%Z%
:u
echo !0!>%B%&%F%!C!)do echo !%%an! !%%af! !%%as! !%%ab! !%%ad!>>%B%&%Z%
:c
for /f %%a in ('cscript //nologo %temp%\eval1.vbs "round(%1,2)"')do set r=%%a
if "%r:~-3,1%" NEQ "." set r=%r%.00

```

Yet to implement Sort (within report), and Print functions.
> 1 votes

# Answer
# C# - 1952 1883

I will show some output when I get in tomorrow. For now, here's the submission:

```
using System;using System.Collections.Generic;using System.IO;using System.Linq;using S=System.String;using O=System.Func<dynamic,string,string>;class I{char[]c={' '};Action<string>w;Func<S,S,S,S,S,dynamic>n;Func<string>N;List<dynamic>T;private static void Main(string[]a){while(true){Console.Write("# ");new I().Parse(Console.ReadLine());}}I(){w=Console.WriteLine;n=(g,h,i,j,k)=>new{a=g,f=h,l=i,b=j,d=k};N=()=>DateTime.Now.ToString("yyyy-MM-dd");}List<dynamic>G(){return File.ReadAllLines("test.data").Select(l=>l.Split(c)).Select(ac=>n(ac[0],ac[1],ac[2],ac[3],ac[4])).ToList();}void W(){File.WriteAllLines("test.data",T.Select(a=>(S)(a.a+" "+a.f+" "+a.l+" "+a.b+" "+a.d)));}void Parse(string inp){var C=true;try{Func<object,float>v=Convert.ToSingle;Func<string,bool>s=string.IsNullOrEmpty;var i=inp.Split(c);T=G();Func<S,int>F=m=>T.IndexOf(T.FirstOrDefault(a=>a.a==m));C=!s(i[1]);var g=F(i[1]);switch(i[0]){case"open":if(C){int an=0;var cs="000";while(T.Any(A=>cs==A.a)){an++;cs=an.ToString("D3");}T.Add(n(cs,i[1],i[2],"0.00",N()));w(cs);}break;case"withdraw":case"deposit":var D=i[0]=="deposit";C=(D||v(T[g].b)>=v(i[2]));var ba=(v(T[g].b)+v(i[2])*(D?1:-1)).ToString("F");if(C)T[g]=n(T[g].a,T[g].f,T[g].l,ba,N());break;case"close":C=g>-1&&v(T[g].b)<=0;if(C)T.RemoveAt(g);break;case"report":case"print":var X=i[0]=="print";var B=1;O o=(x,p)=>((Type)x.GetType()).GetProperty(p).GetValue(x);O K=(k,j)=>{var r=(j=="b"?"$":"");var P=T.Max(_=>(o(_,j)).Length);return r==""?(o(k,j)).PadRight(P):((B<1?r:"")+(o(k,j))).PadLeft(P+1);};var q=i[1];Action<dynamic,S>U=(u,t)=>{S l=""; foreach(var h in t)l+=K(u,h.ToString())+" "; w(l);};q=q=="Account"?"a":q=="Firstname"?"f":q=="Lastname"?"l":q=="Balance"?"b":q=="Date"?"d":"a"; var V=(q+"afldb".Replace(q,""));U(T.First(),V);B=0;foreach(var M in(X?T.Skip(1).Take(1):T.Skip(1).OrderBy(df=>o(df,q))))U(M,V);break;}W();}catch{}if(!C)w("Failed");}}

```
> 1 votes

# Answer
**C# - 1870 1881 Bytes**

Abusing `using` aliases, `Action`, `Func`, exceptions for flow control and more. Was considering exploiting that "report" didn't specify how things should be sorted. Bank.data must use unix line breaks or this code will break.

Edited to fix a potential issue sorting by fields other than Date and Balance.

```
using System;using System.Collections.Generic;using System.IO;using System.Linq;using Ac=System.Action;using Cn=System.Console;using F1=System.Func<string,int>;using F2=System.Func<string>;using S=System.String;class P{static void Main(S[] args){S fn="Bank.data";List<S>ad=null;F1 L=(s)=>s.Length;F2 dt=()=>S.Format("{0:yyyy-MM-dd}",DateTime.Now);Func<S,S[]>sp=(s)=>s.Split(' ');Action<S,S>wl=(s,fm)=>Cn.WriteLine(S.Format(fm,sp(s)));Func<S,S>rs=(s)=>{var t=sp(s);t[3]="$"+t[3];return S.Join(" ",t);};F2 fs=()=>{int[]sz={7,9,8,7};ad.Skip(1).ToList().ForEach(b=>{for(int c=0;c<4;c++){sz[c]=Math.Max(sz[c],L(sp(rs(b))[c]));}});return"{0,-"+sz[0]+"} {1,-"+sz[1]+"} {2,-"+sz[2]+"} {3,"+sz[3]+"} {4,-10}";};F1 k=(s)=>sp(ad[0]).ToList().FindIndex(a=>a==s);Ac Sv=()=>File.WriteAllText(fn,S.Join("\n",ad));Ac Ld=()=>ad=File.ReadAllText(fn).Split('\n').ToList();Action<int,S>R=(r,a)=>{var s=sp(ad[r]);s[3]=S.Format("{0:#.00}",Convert.ToDouble(s[3])+Convert.ToDouble(a));s[4]=dt();ad[r]=S.Join(" ",s);};Ac f=()=>wl("failure","{0}");F1 ri=(n)=>{for(int w=1;w < ad.Count;w++){if(ad[w].StartsWith(n))return w;}return -1;};F2 nm=()=>{var s="";for(int i=1;i<1000;i++){s=S.Format("{0:000}",i);if (ri(s)<0)break;}return s;};for(;;){Cn.Write("# ");S i=Cn.ReadLine();var it=sp(i+" ");Ld();var n=ri(it[1]);it=sp(i);var a=new Dictionary<S,Ac>(){{"deposit",()=>R(n,it[2])},{"withdraw",()=>R(n,"-"+it[2])},{"close",()=>(sp(ad[n])[3]==".00"?()=>ad.RemoveAt(n):f)()},{"open",()=>{var nn=nm();ad.Add(S.Format("{0} {1} {2} .00 {3}",nn,it[1],it[2],dt()));wl(nn,"{0}");}},{"print",()=>{wl(ad[0],fs());wl(rs(ad[n]),fs());}},{"report",()=>{var ks=sp(fs()).ToList();var ki=k(it[1]);ks.Insert(0,ks[ki]);ks.RemoveAt(ki+1);var kf=S.Join(" ",ks);wl(ad[0],kf);ad.Skip(1).OrderBy(b=>(ki==3?new S('0',11-L(sp(b)[ki])):"")+sp(b)[ki]).ToList().ForEach(b=>wl(rs(b),kf));}}};try{a[it[0]]();Sv();}catch(Exception){f();}}}}

```

Output:

```
# report Balance
   Balance Account Firstname  Lastname           Date
     $7.95 501     Timmy      Bongo              2014-11-04
   $266.71 166     Chip       Stonesmith         2014-12-15
   $346.22 123     Maree      Jones              2014-12-13
   $893.00 105     William    Greene             2015-01-06
  $1228.73 300     Mary       Galoway            2014-12-28
  $1299.82 888     Alexandria Cooper             2014-12-30
  $2055.44 203     Samantha   Richardson         2014-11-01
  $3422.02 035     Thomas     Breakbone          2015-01-03
$277847.74 422     Henrietta  Throsby-Borashenko 2014-11-21
$956119.66 151     Bruce      Wayne              2014-10-09
# open Clark Kent
001
# print 001
Account Firstname  Lastname              Balance Date
001     Clark      Kent                     $.00 2015-02-03
# deposit 001 4530
# withdraw 105 893
# close 105
# report Date
Date       Account Firstname  Lastname              Balance
2014-10-09 151     Bruce      Wayne              $956119.66
2014-11-01 203     Samantha   Richardson           $2055.44
2014-11-04 501     Timmy      Bongo                   $7.95
2014-11-21 422     Henrietta  Throsby-Borashenko $277847.74
2014-12-13 123     Maree      Jones                 $346.22
2014-12-15 166     Chip       Stonesmith            $266.71
2014-12-28 300     Mary       Galoway              $1228.73
2014-12-30 888     Alexandria Cooper               $1299.82
2015-01-03 035     Thomas     Breakbone            $3422.02
2015-02-03 001     Clark      Kent                 $4530.00
#

```
> 1 votes

---
Tags: code-golf
---