title: Two-Many Outputs

text:
# Question
Title: Two-Many Outputs
## The Challenge

I present to you another spy vs. spy challenge pitting obfuscators versus crackers. In this case, however, the datum to be protected is not an input but an *output*.

The rules of the challenge are simple. Write a routine with the following specifications:

1. The routine may be written in any language but may not exceed 320 bytes.
2. The routine must accept three 32-bit signed integers as inputs. It can take the form of a function that accepts 3 arguments, a function that accepts a single 3-element array, or a complete program that reads 3 integers from any standard input.
3. The routine must output one signed 32-bit integer.
4. Over all possible inputs, the routine must output between 2 and 1000 (inclusive) unique values. The number of unique values a routine can output is called its *key*.

As an example, the C program

```
int foo( int i1, int i2, int i3 ) {
    return 20 + (i1^i2^i3) %5;
}

```

has a key of 9, since it (hopefully) can only output the nine values `16`,`17`,`18`,`19`,`20`,`21`,`22`,`23`, and `24`.

Some additional limitations are as follows:

5. The routine must be fully deterministic and time-invariant, returning identical outputs for identical inputs. The routine should make no call to pseudorandom number generators.
6. The routine may not rely on "hidden variables" such as data in files, system variables, or esoteric language features. For example, routines should generally not refer to constants unless the constants are clearly defined in the code itself. Routines that rely on compiler quirks, outputs from mathematically undefined operations, arithmetic errors, etc. are also strongly discouraged. When in doubt, please ask.
7. You (the coder) must know precisely how many unique outputs the routine can produce, and should be able to provide at least one input sequence that produces each output. (Since there can potentially be hundreds of unique outputs, this set would only ever be requested in the event your key is contested.)

Since this problem bares far less resemblance to classical encryption than the previous one, I expect it will be accessible to a broader audience.

The more creative, the better.

## The Scoring

The shortest non-cracked submission(s) per byte count will be declared the winner(s).

If there's any confusion, please feel free to ask or comment.

## The Counter-Challenge

All readers, including those who have submitted their own routines, are encouraged to "crack" submissions. A submission is cracked when its key is posted in the associated comments section. If a submission persists for 72 hours without being modified or cracked, it is considered "safe" and any subsequent success in cracking it will be ignored for sake of the contest.

Only one cracking attempt per submission per reader is permitted. For example, if I submit to user X: "your key is 20" and I'm wrong, user X will disclaim my guess as incorrect and I will no longer be able to submit additional guesses for that submission.

Cracked submissions are eliminated from contention (provided they are not "safe"). They should not be edited. If a reader wishes to submit a new routine, (s)he should do so in a separate answer.

A cracker's score is the number of submissions (either compliant or not) (s)he cracks. For crackers with identical counts, the ranking is determined by total byte count across all cracked submissions (the higher, the better).

The cracker(s) with the highest score(s) will be declared the winners along with the developers of the winning routines.

*Please do not crack your own submission.*

Best of luck. :)

# Leaderboard

**Last Updated Sept 2, 10:45 AM EST**

**Immovable Barriers (non-cracked submissions):**

1. CJam, 105 \[Dennis\]

**Unstoppable Forces (crackers):**

1. Dennis \[Java, 269; C, 58; Mathematica, 29\]
2. Martin Büttner \[Java, 245\]

# Answer
> 7 votes
# CJam, 105 bytes

```
1q~]4G#b2A#md"M-k^XM-WHM-n^GM-0%M-uwM-gM-^XeM-kM-^VO^Ph,M-^MM-^PM-qM-!M-8M-AM-OM-~tM-^FM-cM-h^AM-0M-0M-lM-@M-^[MF=M-^Z^SM-1M-KM-T2M-9M-UmSM-N
M-8M-^^M-n$4M-^M^SM-x M-OM-^@^?"256b@D#Y256#%2+md!A3#*)%)%

```

The above uses caret and M notation, since it contains unprintable character. After converting the byte stream into an integer (`256b`), the following code gets executed:

```
1q~]4G#b2A#md
12313030820310059479144347891900383683119627474072658988524821209446180284434934346766561958060381533656780340359503554566598728599799248566073353154035839
@D#Y256#%2+md!A3#*)%)%

```

You can try this version online in the CJam interpreter.

### How it works

This submission uses number theory instead of obfuscation. The program will return 0 for almost all inputs. From the few inputs that result in a non-zero output, a secret modulus is derived that is applied to the 10 least significant bits of the third integer.

The most efficient way of solving this challenge (that I can think of) would be factorizing the 512 bit integer, which I hope won't be achievable in 72 hours.

```
" Prepend 1 to the numbers read from STDIN and convert the resulting array into an integer
  (“N”) by considering them digits of a base 2**32 number.                                 ";

1q~]4G#

" Compute “N / 1024” and “N % 1024”.                                                       ";

2A#md

" Push a carefully selected 512 bit semi-prime (“S”).                                      ";

12313030820310059479144347891900383683119627474072658988524821209446180284434934346766561958060381533656780340359503554566598728599799248566073353154035839

" Compute P = (N / 1024) ** 13 % 2 ** 256 + 2.                                             ";

@D#Y256#%2+

" Compute “S / P” and “S % P”.                                                             ";

md

" Compute “M = (S / P) % (1000 * !(S % P) + 1) + 1”.

  “M” is the key if P is a divisor of S; otherwise, “M == 1”.                              ";

!A3#*)%)

" Compute the final output: “N % 1024 % M”.                                                ";

%

```

### Example run

```
$ base64 -d > outputs.cjam <<< MXF+XTRHI2IyQSNtZCLrGNdI7gewJfV355hl65ZPEGgsjZDxobjBz/50huPoAbCw7MCbTUY9mhOxy9QyudVtU84KuJ7uJDSNE/ggz4B/IjI1NmJARCNZMjU2IyUyK21kIUEzIyopJSkl
$ wc -c outputs.cjam
105 outputs.cjam
$ LANG=en_US cjam outputs.cjam < outputs.secret; echo
1
$ LANG=en_US cjam outputs.cjam <<< '1 2 3'; echo
0

```

# Answer
> 4 votes
# Java - 269

Thanks for everyone's patience, this should now be fixed.

shortened:

```
int a(int a,int b,int c){double d=180-360.0/(int)(Math.abs(Math.sin(a*60))*50+2),e=180-360.0/(int)(Math.abs(Math.cos(b*60))*50+2),f=180-360.0/(int)(Math.atan2(c*60, a*60)*51+2);if(Math.abs(d+e+f-360)<.1)return Integer.valueOf((int)d+""+(int)e+""+(int)f);else return 1;}

```

Not shortened:

```
int a(int a, int b, int c) {
    double d = 180 - 360.0 / (int) (Math.abs(Math.sin(a * 60)) * 50 + 2);
    double e = 180 - 360.0 / (int) (Math.abs(Math.cos(b * 60)) * 50 + 2);
    double f = 180 - 360.0 / (int) (Math.atan2(c * 60, a * 60) * 51 + 2);
    if (Math.abs(d + e + f - 360) < .1)
        return Integer.valueOf((int) d + "" + (int) e + "" + (int) f);
    else
        return 1;
}

```

# Answer
> 2 votes
## A Sampler

Not an official entry of course, and the character count is too high, but I figure if anyone wants a mind-numbing challenge, they can try to determine how many unique outputs the following function produces (given three inputs as described in the OP):

```
function z(y,_,$){M=[];N=[];O=[];C=1792814437;P=72;r=t=0;(f=function(a,k,L){if(k<a.length){for(L=a[k],a[k]=0;a[k]<L;a[k]++)f(a,k+1)}else
if(!t){f([P-1,P-1],0,++t);N=M;while(t<2*P){s=!(t&1);f([P,P,P,P],0,++t);r=r||(s?0:t);t&1&&(N=O);O=[]}}else
((t<2)&&(((d=P*a[0]+(P+1)*a[1]+P)<(P<<6))&&(M[d]=(((y^~_)>>a[0])+((_^~$)>>(a[0]-32)))&1),((a[1]<P-a[0])&&
(M[a[1]+(P+1)*a[0]]=(($^C)>>a[0]+16-a[1])&1))||1))||((t&1)&&((O[P*a[2]+a[3]]|=M[a[1]+P*a[2]]&N[P*a[0]+a[3]]&&
!(a[0]-a[1]))||1))||(s|=N[(a[0]+1)*a[1]+a[3]]);})([],0,0);return r;}

```

In fact, I'm so confident that it's uncrackable, I'll award anyone who cracks it the "Supreme Unstoppable Force of Nature Award".

Because really, they deserve it.

# Answer
> 2 votes
# Java - 245

### Cracked by Martin Büttner

```
int a(int[]_$){return $($($_(_$[0],0)))+$_(_$[1],1)*11+$($($_(_$[1+1],0)))*(1+1);}int $_(int $,int $_){int OO=0,o=1,O=1;for($=$<0?-$:$;++O*O<=$;OO+=$%O<1?O:0,o+=$%O<1?1:0,$/=$%O<1?O--:1);return $_>0?o:OO+$;}int $(int $){return(int)Math.sqrt($);}

```

Feed the input as an int array: `a(new int[]{1,2,3})`. I'm not expecting it to go 72 hours, but have fun with it.

Here it is with line breaks, to make it a bit more readable:

```
int a(int[]_$){return $($($_(_$[0],0)))+$_(_$[1],
1)*11+$($($_(_$[1+1],0)))*(1+1);}int $_(int $,int
$_){int OO=0,o=1,O=1;for($=$<0?-$:$;++O*O<=$;OO+=
$%O<1?O:0,o+=$%O<1?1:0,$/=$%O<1?O--:1);return $_>
0?o:OO+$;}int $(int $){return(int)Math.sqrt($);}

```

# Answer
> 2 votes
## C, 58 bytes (Cracked)

A simple one:

```
f(a,b,c){return(long long)a*b*c-0x1d21344f8479d61dLL?0:a;}

```

# Answer
> 1 votes
## Mathematica, 29 bytes, Key: 715, Cracked by Dennis

This is just a fixed version of my initial answer, which didn't work for non-positive inputs.

```
f=Plus@@Mod[NextPrime@#,240]&

```

Takes a list of integers like

```
f[{1,2,3}]

```

# Answer
> 0 votes
207 characters, in C/C++, not yet obfuscated:

```
int x(int a, int b, int c) {
    int d, e, f;
    for (int i=0; i!=1<<31; ++i) {
        d=10*(b-a);
        e=a*(28-c)-b;
        f=a*b-2.7*c;
        a += d;
        b += e;
        c += f;
    }
    return ((a%5+5)*10+(b%5+5))*10+c%5+5;
}

```

---
Tags: code-golf, obfuscation, cops-and-robbers
---


# Question
Title: programmers from all languages, write this with as few code as possible
i've been dabbling with a hypothetical language... now, i want to add a feature/mechanism that can easily format data in as few codes as possible.

now, i need to compare my hypothetical language feature with how it's going to be written in other languages. in particular, would it have lesser code? so i just decided i would have a sample problem and see how this is coded in different languages. problem is, i'm only familiar with C-like languages (C/C++, Java, C#, J#,.. ), Python and some Perl.

so could you guys help me out and write codes, as short as possible (no pseudo code) in different languages for the problem below. be as clever as you want and don't even think of efficiency. we're looking more of how we can describe what needs to be accomplished as short as possible. very declarative. or maybe there's already a languages that does this very well??

transform this:

```
((a0, a1, a2), (b0, b1, b2), (c0, c1, c2))

```

to this:

```
(a0, (b0, c0)), (a1, (b1, c1)), (a2, (b2, c2))

```

the parenthesization just denotes nested arrays or list, whichever way you want to look at it. also, there are no types, so don't have to worry about that.

# Answer
> 3 votes
## Python

The language feature you're describing is typically known as `zip`. Assuming the array is named `a`:

```
zip(a[0],zip(*a[1:]))

```

Sample usage:

```
a = (('a0', 'a1', 'a2'), ('b0', 'b1', 'b2'), ('c0', 'c1', 'c2'))
print zip(a[0],zip(*a[1:]))

```

Output:

```
[('a0', ('b0', 'c0')), ('a1', ('b1', 'c1')), ('a2', ('b2', 'c2'))]

```

If the last two values of each don't need to be in a list:

```
zip(*a)

```

would suffice.

# Answer
> 2 votes
# Python 3

I know you already have a Python answer, but here's some code that can be easily translated to other languages:

```
tup = [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]]
end = []

for j in range(len(tup[0])):
    end.append([tup[0][j]])
    end[j].append([])
    for i in range(1, len(tup)):
        end[j][1].append(tup[i][j])

```

...And since you've tagged this as I've golfed my code from 206 characters to 157:

```
t=[[a0,a1,a2],[b0,b1,b2],[c0,c1,c2]]
e=[];l=len;r=range
for j in r(l(t[0])):
 e.append([t[0][j]]);e[j].append([])
 for i in r(1,l(t)):e[j][1].append(t[i][j])

```

---
Tags: code-golf
---


title: Organise the Gregorian Church's Music

text:
# Question
Title: Organise the Gregorian Church's Music
The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system:

<sup>*Image by user gamerprinter at Cartographers' Guild.*</sup>

The Church needs to organise all the sheet music, so they have hired a medieval software engineer to write a program to organise it for them. You are the software engineer that has been hired. However, the compilation process in medieval times involves the program being written onto paper by a team of slow biblical scribes. To decrease the time it takes for the team of scribes to compile your code, you must make the program as small as possible.

The Church wants the chant music to be organised based off the musical scale they are written in. All of the Church's chant music is written in *Dorian scales*. Given the notes of a certain piece of music, your program will output the Dorian scale that it is in. Here, I will explain exactly what a Dorian scale is. If you already know, you may skip this section.

There are 12 possible notes in any melody. Here they are in order:

```
C C# D D# E F F# G G# A A# B

```

A *semitone* (represented using a `S`) is incrementing one step to the right, wrapping around (so a semitone up from B would be back to C). A *tone* (represented using a `T`) is two semitones. For instance, a semitone up from F# would be G. A tone up from F# would be G#.

To create a Dorian scale, we start from any note in the list, and then move up in the following pattern, listing the notes that we encounter:

```
T, S, T, T, T, S

```

An example. I start from A. The notes of my Dorian scale becomes:

```
A
B  (up a tone)
C  (up a semitone)
D  (up a tone)
E  (up a tone)
F# (up a tone)
G  (up a semitone)

```

The scale has the notes A, B, C, D, E, F#, and G. Because I started from A, we will call this the *Dorian scale in A*. There are therefore 12 different Dorian scales, each of which are named after the note that they started from. Each of them use the same pattern of tones and semitones, just starting from a different position. If my explanation is not coherent you may also consult Wikipedia.

The input of the program can be given from whatever is appropriate for your program (e.g. STDIN, command line argument, `raw_input()`). It may be not pre-initialised in a variable. The input will be a list of comma seperated notes, representing the melody of the piece. There may be repeated notes. There will always be enough different notes in the input to be able to decisively deduce the scale of the piece. An example input:

```
B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A

```

The output of the program should be the string `Dorian scale in X`, where X is the starting note of the scale. The output of the example input:

```
Dorian scale in B

```

Comparing this with the Dorian scale in B (`B C# D E F# G# A`) we see that all the notes of the melody are within this scale. The note C# is unused in this case. However there are sufficient notes to unambiguously identify B Dorian as the correct key. No other Dorian scale fits, because whatever other scale we try, there is always at least one note of the melody that does not belong to the scale.

This is code golf, so the entry with the shortest number of characters wins. Ask in the comments if you have questions.

# Answer
# CJam - 61

```
C,q',/f{"FCGDAEB"_5<'#f++:s@m<7<:A-!{"Dorian scale in "A3=}*}

```

Try it at http://cjam.aditsu.net/
> 3 votes

# Answer
# C, ~~171~~ 146

```
i,b;main(int c,char**v){for(;c=v[1][i];)b|=c/65<<c*2%7+v[1][++i]%2*7;for(i=12;i--;)b&(1016056>>i)||printf("Dorian scale in %c%c",65+i*3%7,(i<5)*35);}

```

Parsing strings in C is not that easy, so I went for a more mathematical approach.

I take advantage of the Circle of Fifths. If we arrange the notes in the following order based on counting up 7 semitones at a time (known as a "fifth"), we find that all the notes permitted in any given scale form a consecutive block of 7 notes and all the prohibited notes form a consecutive block of 5 notes.

```
F C G D A E B F# C# G# D# A#

```

(it's a circle, it wraps back around to `F` at the end.)

The position of a natural note in the above sequence can be calculated as `(ASCII code) * 2 % 7`. Then if the next character is odd (applies to `#` but not comma, space or zero byte) we add 7 to make it sharp. We store a bitmap of the notes that have been used.

The number `243` (binary `11111000`) corresponds to the notes prohibited in the scale of A# Dorian. I multiplied this by `(1<<12)+1=4097` to give the magic number `1016056`. This is rightshifted to check (by ANDing) if the melody contains prohibited notes for each of the 12 scales in turn. If the melody does not contain prohibited notes, the scale is printed.

For the output we need to print the scale name encoded in the reverse order to cycle of fifths above, remember we are going backwards because we are rightshifting.) The ASCII sequence `ADGCFBEADGCF` is generated by `65+i*3%7`. For the first five of these a sharp must also be printed.

**Ungolfed code**

```
i,b;
main(int c,char**v){
  for(;c=v[1][i];)                          //for each character in first commanline argument v[1]
                                               //if it is a letter (assume uppercase, ASCII 65 or over)
   b|=c/65<<c*2%7+v[1][++i]%2*7;               //convert to position in the circle of fifths.
                                               //Add 7 if the next character is odd (ASCII'#')
                                               //leftshift 1 by this number and OR this with the contents of b.

  for(i=12;i--;)b&(1016056>>i)||printf         //if melody includes no prohibited notes for the scale i, print
   ("Dorian scale in %c%c",65+i*3%7,(i<5)*35); //the scale letter, and a # (ASCII 35) if required, otherwise an ASCII 0.
}

```

Invalid input behaviour: If insufficient notes are supplied to unambiguously determine the scale, it will output all possible scales. If an impossible combination of notes is supplied, it will output nothing. Notes must be delimited by a comma (or other non-whitespace character with an even ASCII code \<= 64.) Spaces cannot be used as everything after the first space would be considered a different argument. ASCII codes \>64 will be interpreted as notes in the manner described.
> 9 votes

# Answer
## Haskell - 152

```
w=words
n=w"C C# D D# E F F# G G# A A# B"
f s="Dorian scale in "++[n!!i|i<-[0..11],all(`elem`[(n++n)!!(i+j)|j<-[0,2,3,5,7,9,10]])s]!!0
main=interact$f.w

```

### Ungolfed

```
type Note = String
type Scale = [Note]

notes :: [Note]
notes = words "C C# D D# E F F# G G# A A# B"

isScale :: Scale -> [Note] -> Bool
isScale scale notes = all (`elem` scale) notes

takeScale :: Int -> Scale
takeScale i = [(notes ++ notes) !! (i + j) | j <- [0, 2, 3, 5, 7, 9, 10]]

findScale :: [Note] -> Note
findScale xs = head [notes !! i | i <- [0..11], isScale (takeScale i) xs]

main = interact (("Dorian scale in "++) . findScale . words)

```
> 4 votes

# Answer
# Python 2 - 177 characters

It's not that short, but I find it the joy of Python to write multiple nested for loops in one line, even when not golfing. Unfortunately, I had to put the input statement on a separate line so that it would not execute more than once.

```
j=set(raw_input().split(','))
print"Dorian Scale in",[x for x in[["A A# B C C# D D# E F F# G G#".split()[(b+n)%12]for n in[0,2,3,5,7,9,10]]for b in range(12)]if j<set(x)][0][0]

```

I don't use Python 3, but I believe this is a rare instance when the print statement would not need more characters. Since `print` is a function there, I would be able to offset the need for parentheses with the use of the `*` list unpacking operator to replace the last `[0]`.
> 3 votes

# Answer
## Ruby - 132

```
12.times{|i|$*[0].split(?,)-(g=(0..6).map{|j|%w{C C# D D# E F F# G G# A A# B}[-i+=~(58>>j&1)]})==[]?(puts"Dorain scale in "+g[0]):g}

```

Input from command line args.
e.g. `ruby dorianscale.rb B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A`

Try it at: ideone
> 3 votes

# Answer
## Haskell - 140

Make use of the Circle of Fifths property introduced by @steveverrill. If we let `circle0 = words "C G D A E B F# C# G# D# A# F"` and `circle = circle0 ++ circle0`, then we can construct all scales by taking consecutive 7 notes in `circle`.

```
scales = [take 7 . drop i $ circle | i <- [0..11]]

```

In each scale constructed by this way, `scale !! 3`, the 4th element is the scale name.

### Code

```
w=words
n=w"C G D A E B F# C# G# D# A# F"
f s="Dorian scale in "++[x!!3|x<-[take 7.drop i$n++n|i<-[0..]],all(`elem`x)s]!!0
main=interact$f.w

```

### Ungolfed

```
type Note = String
type Scale = [Note]

notes :: [Note]
notes = words "C G D A E B F# C# G# D# A# F"

scales :: [Scale]
scales = [take 7 . drop i $ notes ++ notes | i <- [0..11]]

findScale :: [Note] -> Note
findScale xs = head [scale !! 3 | scale <- scales, all (`elem` scale) xs]

main = interact (("Dorian scale in "++) . findScale . words)

```
> 3 votes

# Answer
# Scala, ~~130~~ ~~128~~ 127

```
print("Dorian scale in "+(".#?".r findAllIn "FCGDAEBF#C#G#D#A#"*2 sliding(7)find{l=>args(0)split','forall(l contains _)}get 3))

```

Using the circle of fifths method. Input from command line args ie

```
scala dorianscale.scala B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A

```
> 2 votes

---
Tags: code-golf, music
---


title: Input a number and return day of week

text:
# Question
Title: Input a number and return day of week
Not restricted to any one programming language.

What I'm saying is you pass 1 to it and it returns Monday, 7 corresponds with sunday and so on.

I've managed a 146 byte statement in Java to do the same.

```
return (n<1?"invalid":(n<2?"monday":(n<3?"tuesday":(n<4?"wednesday":(n<5?"thursday":(n<6?"friday":(n<7?"saturday":(n<8?"sunday":"invalid"))))))));

```

Your program should:

* output full words (STDOUT)
* not crash if the input is less than 1 or greater than 7

# Answer
## Ruby, 69 or 38 bytes

Here is a simple way to improve your code (written in Ruby but it works similarly in Java):

```
n>0&&n<8?%w{Mon Tues Wednes Thurs Fri Satur Sun}[n-1]+"day":"Invalid"

```
* Combine the two invalid checks into one.
* Put all the days in an array and use `n` as an index.
* Factor out the common `day`.

You can make it even shorter if you import the names of the days of the week from a library, like Ruby's:

```
n>0&&n<8?Date::DAYNAMES[n%7]:"Invalid"

```

Note that now I don't decrement `n` but instead take it modulo 7 to map `7` to `0`. This is because `DAYNAMES` starts with Sunday.
> 8 votes

# Answer
## Bash: 47 bytes

Still no bash entry? I'm disappointed ...

```
case $1 in
    [1-7]) date -d "14-08-1$1" +%A
esac

```

It uses the days of the current week and simply substitutes the last digit (11-17 August 2014 -- 11 is Monday, 12 is Tuesday, etc.).
> 9 votes

# Answer
## Javascript, 95 88 bytes

```
x=prompt();alert("Invalid 0Mon0Tue0Wednes0Thurs0Fri0Satur0Sun".split(0)[x&~7?0:x]+"day")

```

7 in binary is 0111, meaning that you can shave off a few characters with a bitwise operation instead of `x>0&&x<8`.

Edit: Removed the `s` array with the help of edc65.
> 6 votes

# Answer
# Marbelous 192 191 185 181

```
}0
=1=2=3=4=5=6=7--
&1&2&3&4&5&6&7{0
&8////////////
4D6F6E547565735765646E65735468757273467269536174757253756E646179
&1&1&1&2&2&2&2&3&3&3&3&3&3&4&4&4&4&4&5&5&5&6&6&6&6&6&7&7&7&8&8&8

```

Non-zero exit code if the input is invalid

Usage:

```
# marbelous.py -r day-of-week.mbl 2
Tuesday

```
> 6 votes

# Answer
## C# - 26 Bytes

Expects the day to be stored inside `n`.
Does not crash, as expected.
Powered by LINQPad™

```
((DayOfWeek)(n%7)).Dump();

```

<sub> Special thanks to bmarks and Stephan Schinkel for byte saving and rule bending, respectively </sub>
> 5 votes

# Answer
## C#, 95 bytes

In C# you can do something like this:

```
return(i>7||i<0)?"invalid":new[]{"mon","tues","wednes","thurs","fri","satur","sun"}[i-1]+"day";

```
> 2 votes

# Answer
# Javascript 93 :(

```
q=prompt();alert(q<8&&q>0?'0mon0tues0wednes0thurs0fri0satur0sun'.split(0)[q]+'day':'invalid')

```
> 2 votes

# Answer
## T-SQL 36

```
SELECT DATENAME(w,@+6)WHERE(6+@)/7=1

```

Assumes the variable is stored in @. If it is an invalid input (@\>7 or @\<1), then it doesn't select anything.

Edit: Apparently a date can be a number. Removed 5 characters with that.

Edit 2: Based on the first edit. Since it's an int, I don't have to use DATEADD(); I can use normal addition instead.
> 2 votes

# Answer
# Extended BrainFuck: 104

```
{a))<(->>}+>,49-(-(-(-(-(-((-)<->>|"sun")<(->>|"satur"&a|"fri"&a|"thurs"&a|"wednes"&a|"tues"&a|"mon")|"day"

```

Ungolfed (Idiomatic)

```
{main
  :flag +
  :input

  $input &read_number -
  (-
   (-
    (-
     (-
      (-
       (        $input &reset  ; 7-9
                $flag  &reset
                |"sun" &reset )

        $flag ( &reset         ; 6
                |"satur" &reset  ))

       $flag (  &reset         ; 5
                |"fri" &reset    ))

      $flag (   &reset         ; 4
                |"thurs" &reset  ))

     $flag (    &reset         ; 3
                |"wednes" &reset ))

    $flag (     &reset         ; 2
                |"tues" &reset   ))

   $flag (      &reset         ; 1
                |"mon" &reset    )

   |"day"
}
{reset (-)}
{read_number , 48- }

;; call main
&main

```
> 2 votes

# Answer
# Mathematica ~~19~~ 16 bytes

```
DayName@{1,1,#}&

```

As Dr. Rebmu noted, January 1, 1 A.D. is a good place to start. It (presumably) fell on a Monday.

```
    DayName@{2014, 9, #} &[1]

```

> Monday
> 2 votes

# Answer
# Lua - 57 bytes

```
print(n>0 and n<8 and os.date("%A",9e4*(n+3))or"Invalid")

```

Lua has os.date() in it's standard library, and it has formatting. So you can pass a time (in this case "9e4\*(n+3)") and ask to return the "%A" format, which is the names of the days of the week. Also, very useful in Lua is "a and b or c". If a is true (in the code a is "n\>0 and n\<8") it returns b, if a is false (or nil) it returns c.
> 2 votes

# Answer
# Bash - 21 19

Assuming the input is in variable `D`:

```
date +%A -d$D"Jan1"

```

# HTML + PHP - 26

Let `$d` be an input text

```
<?=date('l',86400*(3+$d));

```

Timestamp 86400\*3 is the first Sunday from the start of UNIX world.

You can test it by executing:

```
<?php $d=3; ?>
<?=date('l',86400*(3+$d));

```
> 2 votes

# Answer
# Lua ~~134~~ ~~119~~ ~~115~~ ~~100~~ 98

```
q={"mon","tues","wednes","thurs","fri","satur","sun"}print(n<8 and n>0 and q[n].."day"or"invalid")

```

Basically the same thought MartinButtner had, except about ~~4.5~~ ~~4.1~~ ~~1.7~~ 1.4 times longer. Does assume `n` is stored as a variable elsewhere.
> 1 votes

# Answer
# Perl, 60 bytes

Something like this:

```
$x&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||die

```

If want to return a message instead and you're concerned about negative indexes you can use this one instead (8 more chars):

```
$x>0&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||"Invalid"

```
> 1 votes

# Answer
## Bash 74 48 + error message

A different approach since all other answers focus on storing the strings in some form.

```
read x;((0<x&&x<8))&&date -d2007010$x +%A||echo out of range

```
> 1 votes

# Answer
# Python (84)

```
lambda a:'imtwtfssnouehrauvneduitnadsnrdudladesaraiyasdydyd yda a    ay y    y'[a if 0<a<8 else 0::8]

```

I suppose it's an interesting sollution. It takes an idea from another answere I read somewhere (can't find it, I do know it was on this site, so if anyone knows feel free to tell me.) The string was generated with the following J program:

```
,|:>'invalid';'monday';'tuesday';'wednesday';'thursday';'friday';'saturday';'sunday'

```

Taking some subtle hints from this answer:

```
lambda a:' mtwtfssouehrauneduitn snr u   es r   s'[a::7]+'day'if 0<a<8 else'invalid'

```
> 1 votes

# Answer
# Befunge-93 (206 ~~208~~)

This one was fun to write. I'm sure it can be done in a better way, but… it works! =) Can be tried out here.

Would've been even shorter if the `#` would jump over entire strings rather than just the individual cell.

```
&1-    v
vv"Mon"># :# !_
> 1-    v
vv"Tues"># :# !_
> 1-      v
vv"Wednes"># :# !_
> 1-     v
vv"Thurs"># :# !_
> 1-   v
vv"Fri"># :# !_
> 1-     v
vv"Satur"># :# !_
> 1-   v
vv"Sun"># :# !_
>>:#,_"yad",,,@

```

The basic idea behind it: Get the number and keep decrementing it. Everytime we decrement it, the cursor moves to the right, wraps around and is sent one level lower. Once we hit zero, move to the left instead and push the (first part of the) day name. From then on, the cursor will move straight to the bottom where the string is printed and "day" is appended.

You can see how it works by using the "Step" feature in the link to the online interpreter.

*Edit:* I managed to shave two bytes off by doing `>:#,_` instead of `>,,,,,,`, which is pretter as well.
> 1 votes

# Answer
## Clojure - 99 chars

Plain and simple, despite my best (newbie) attempts:

```
(defn f[x](get{1"monday"2"tuesday"3"wednesday"4"thursday"5"friday"6"saturday"7"sunday"}x"invalid"))

```
> 1 votes

# Answer
# Perl, 54

From STDIN to STDOUT, no date functions, no crash.

```
print((a,Mon,Tues,Wednes,Thurs,Fri,Satur,Sun)[<>].day)

```
> 1 votes

# Answer
# JS: 58

Assuming n is already stored as a variable.

```
"0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day"

```

As an ES6 function (same assumptions): **67**

```
let d=n=>"0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day"

```

This will just print "day" for 0 and loops around for n \> 7
> 1 votes

# Answer
# Haskell - 62

Wraps around; `0` is Sunday, `8` is Monday, and so on.

```
words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day"

```

If printing to stdout is required (**68 bytes**, output is in double quotes):

```
print$words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day"

```
> 1 votes

# Answer
# **MATLAB : 33**

```
datestr(3:9,'dddd');ans(1:7==n,:)

```

# **MATLAB : 71**

```
{'mon';'tues';'wednes';'thurs';'fri';'satur';'sun'};[ans{1:7==2} 'day']

```

# **Haskell : 75**

```
g n=((++"day").last.take(abs n).words)"mon tues wednes thurs fri satur sun"

```

# **Haskell : 97**

```
f n=if elem n[1..7]then["mon","tues","wednes","thurs","fri","satur","sun"]!!n++"day"else"invalid"

```

# **Python 3.4.1 : 81**

```
'invalid mon tues wednes thurs fri satur sun'.split(' ')[n*(n in range(8))]+'day'

```
> 1 votes

# Answer
# PHP (56 bytes)

```
$d=1;echo$d>0&&$d<8?date('D',255600+$d*86400):'Invalid';

```
> 1 votes

# Answer
# LiveScript - 49

Returns `undefinedday` if the input is invalid. ;)

```
<[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day

```

If printing to stdout is required (**60 bytes**):

```
console.log<[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day

```
> 1 votes

# Answer
# Rebmu: 21 characters

```
pcSYSTEM/locale/daysA

```

To run:

```
>> rebmu/args {pcSYSTEM/locale/daysA} 1
== "Monday"

```

Invalid numbers will return "none".

```
>> rebmu/args {pcSYSTEM/locale/daysA} 8
== none

>> rebmu/args {pcSYSTEM/locale/daysA} 0
== none

```

For those unfamiliar with Rebmu, it uses case transitions to remove the need for spacing--within the limits of what's legally parseable. Rather than using a InitialCapsToBreak it uses CASEtransitionsTObreak, because that allows a different meaning to be ascribed to an initial run of capitals from if the initial initial run is lowercase.

So it is equivalent to the Rebol program `pick system/locale/days a`. (Rebmu by convention names its script parameter as "a").

Saves one character over `system/locale/days/(a)` :-)
> 1 votes

# Answer
## Java 8 - 69 64 chars

Here's an expression in Java 8, including the import. Now improved (thanks to Tomáš Dvořák):

```
import java.time.*;
return DayOfWeek.of((i>0&i<8)?i:1).name();

```

Simply prints `MONDAY` for bogus values of `i`
> 1 votes

# Answer
# Python - 87

I'm not seeing enough love for dict's .get() This one expects `a` to be the number

```
dict(enumerate("mon,tues,wednes,thurs,fri,satur,sun".split(","),1)).get(a,"bad ")+"day"

```
> 1 votes

# Answer
## Python, 95 bytes

```
"%day"%["mon","tues","wednes","thurs","fri","satur","sun"][n-1] if 0<n<8 else "invalid"

```
> 0 votes

# Answer
# Python 2, ~~84~~ ~~83~~ 64

Assuming n is already stored as a variable.

```
import calendar as c;print c.day_name[n-1]if 0<n<8 else'Invalid'

```
> 0 votes

# Answer
# Golfscript (50 ~~55~~)

Expects the input number to be on the stack.

```
" Mon Tues Wednes Thurs Fri Satur Sun"" "/\="day"+

```

or

```
("Mon Tues Wednes Thurs Fri Satur Sun"" "/\="day"+

```

or (for 51, but it's just fun)

```
"day Mon Tues Wednes Thurs Fri Satur Sun"" "/.@=\0=

```

The requirement "not crash" is pretty lenient. This will just print "day" for invalid input – which is not a crash, so it should be allowed.
> 0 votes

# Answer
# Cobra - 43

```
print if(0<n<8,(n%7)to DayOfWeek,'Invalid')

```
> 0 votes

# Answer
# R, 61

```
a=format(Sys.Date()+0:15,"%A");a[grep("^M",a)[1]+0:6][scan()]

```

`format(Sys.Date()+0:15,"%A")` outputs the day of the week of today and the 15 following days. `grep("^M",a)[1]+0:6` is the index of the first monday in that sequence and the six following days.

Usage:

```
> a=format(Sys.Date()+0:15,"%A");a[grep("^M",a)[1]+0:6][scan()]
1: 7
2:
Read 1 item
[1] "Sunday"
> a=format(Sys.Date()+0:15,"%A");a[grep("^M",a)[1]+0:6][scan()]
1: 4
2:
Read 1 item
[1] "Thursday"
> a=format(Sys.Date()+0:15,"%A");a[grep("^M",a)[1]+0:6][scan()]
1: 2
2:
Read 1 item
[1] "Tuesday"
> a=format(Sys.Date()+0:15,"%A");a[grep("^M",a)[1]+0:6][scan()]
1: 8
2:
Read 1 item
[1] NA

```
> 0 votes

# Answer
# CJam - 47 or 45

```
qi"Sun Mon Tues Wednes Thurs Fri Satur"S/="day"

```

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

If I can assume that the number is already on the stack, then the first 2 characters can be removed.
> 0 votes

# Answer
## C# - 28

According to your reference solution, this should be valid.

It assumes the input is stored in the variable `i` and outputs "Sunday", "Monday", etc for 0, 1, etc respectively.

If `i` is out of bounds (below 0 or above 7), `i` will be output. (This is valid because the program doesn't crash)

```
Console.Write((DayOfWeek)i);

```

If you actually want a working function, here is one using 48 bytes:

```
string f(int i){return((DayOfWeek)i)+"";}

```
> 0 votes

# Answer
# Python - ~~83~~ 76

```
from datetime import*
i=input()
if 0<i<8:print date(2013,7,i).strftime("%A")

```

July 2013 was the first month I found that had monday as its first day. Rest of this is quite self explanatory.
> 0 votes

# Answer
# Java 8, 48 chars

```
return n>0&n<8?DayOfWeek.of(n).name():"Invalid";

```

With java 8 comes new enum DayOfWeek, that provides non locale dependent data.

For java 7 and older, this should work good too (76 chars):

```
return n<1|n>7?"Invalid":DateFormatSymbols.getInstance().getWeekdays()[n+1];

```

And locale fixed variant (90 chars):

```
return <1|n>7?"Invalid":DateFormatSymbols.getInstance(Locale.ENGLISH).getWeekdays()[n+1];

```
> 0 votes

# Answer
## C, 81

Just for fun...

```
printf("%sday\n","Mon\0Tues\0Wednes\0Thurs\0Fri\0Satur\0Sun"+"  $)06:@"[n&7]-32);

```
> 0 votes

# Answer
# Java

Uses local language:

```
return i<1||i>7?"Error":new DateFormatSymbols().getWeekdays()[i];

```
> 0 votes

# Answer
## C, 117

Also just for fun...

```
d(n){for(char*p="\177MvT|WpF S\177oxh`a`t\026uze|d;n|eHrrspi\001d\001a\001y\001\n";
*p;p++)-*p++&1<<n-1&&putchar(*p);}

```

(I realize this isn't an obfuscation challenge. I just wanted to see how far a purely data-driven bit-test loop could be golfed.)

---

The un-golfed version:

```
void d(int n)
{
  char *p =
    "\177" "M"   "\166" "T"   "\174" "W"   "\160" "F"   "\040" "S"
    "\177" "o"   "\170" "h"   "\140" "a"   "\140" "t"   "\026" "u"
    "\172" "e"   "\174" "d"   "\073" "n"   "\174" "e"   "\110" "r"
    "\162" "s"   "\160" "i"   "\001" "d"   "\001" "a"   "\001" "y"
    "\001" "\n";

  for (; *p; p++)
    if (-(*(p++)) & (1<<(n-1)))
      putchar(*p);
}

```

Driver:

```
int main() { for (int n = 1; n <= 7; n++) d(n); }

```

Output:

```
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

```

---

How it works:

* The character string consists of a pairs of bit-flags and output characters.
* The even indexes are the bit-flags ('\177', 'v', '|', 'p', ' ', etc.) — but they are stored in ones-complement form to minimize the number of nonprintable ASCII values, which are expensive because they have to be encoded in octal.
* The odd indexes are the output characters ('M', 'T', 'W', 'F', 'S', 'o', 'h', 'a', etc.).
> 0 votes

# Answer
# Batch - 114 Bytes

```
@cmd/von/c"for %%a in (1Mon 2Tues 3Wednes 4Thur 5Fri 6Satur 7Sun)do @set a=%%a&if "!a:~0,1!"=="%1" echo !a:~1!day"

```

The first part `@cmd/von/c` is starting up a new cmd session - it uses the `/v` switch to enable delayed variable expansion, which saves adding in the lengthy `setLocal enableDelayedExpansion`. This way you only need to add the `@` symbol (to hide output) before the `cmd` command and in the middle of the for loop, instead of `@echo off` at the start of the script.
> 0 votes

# Answer
# PHP - 32

Day is given as `$i`

```
<?echo date('l',(($i+4)*86400));

```
> 0 votes

# Answer
# bash - 18

```
date +%A -d01010$1

```

Save it in a file, e.g. day.sh, then run

```
./day.sh 1 # output: Monday
./day.sh 2 # output: Tuesday
...

```
> 0 votes

# Answer
## R, 37

The obligatory hack solution with R.

```
weekdays(as.Date((paste0("1/1/",n))))

```

where the input is first stored as variable `n`. Turning this into a named function would be longer:

```
d=function(n) weekdays(as.Date((paste0("1/1/",n))))

```
> 0 votes

# Answer
## Javascript - 63

```
'0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun'.split(0)[prompt()]+'day'

```
> 0 votes

# Answer
# C# - 30

Since the provided example doesn't actually output, neither does this. Also I'm assuming we don't *have* to have an error message if the value is below 1 or over 7.

```
((DayOfWeek)(n%7)).ToString();

```

For an error message (47):

```
n<1|n>7?"Error":((DayOfWeek)(n%7)).ToString();

```

The reason for the `%7` is because `DayOfWeek` begins with Sunday.

Small cheat: `DayOfWeek` is contained in the System namespace, so if `using System;` isn't specified elsewhere (usually always is), you'd need to replace `DayOfWeek` with `System.DayOfWeek` -- an additional 7 characters.
> 0 votes

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


title: SPOF Picture Hanging

text:
# Question
Title: SPOF Picture Hanging
# Objective

I have a nice picture that I want to hang on my wall. And I want it to hang there in a spectacular way, so I chose to hang it on `n` nails where `n` is any positive integer.

But I'm also indecisive, so if I change my mind, I don't want a lot of trouble taking the picture down. Therefore, removing any one of the `n` nails should make the picture fall down. Did I mention that there is no friction in my house?

Can you help me?

# Rules

1. Your program must read the number `n` from stdin and print to stdout (or your language's equivalents).
2. The output must be the solution according to the output specification without any other trailing or leading characters. However, trailing whitespace and/or newlines is acceptable.
3. You must use *exactly* `n` nails.
4. Assuming a friction-less world, your solution must fulfill the following conditions:
    1. Hanging the picture as described by your solution, the picture must not fall down.
    2. If any one of the nails is removed, the picture must fall down.
5. Standard loopholes apply. In particular, you may not make requests to, e.g., the verification program to brute-force solutions.

Note that 4.2 already implies that all `n` nails must be involved.

# Output Specification

* All nails are named from left to right with the position they are in, starting at `1`.
* There are two fundamental ways to put the string around a nail: clockwise and counter-clockwise. We denote a clockwise step with `>` and a counter-clockwise step with `<`.
* Everytime the string is put around a nail, it comes out on top of the nails, so skipping nails means the string will go across the top of the intermediate nails.
* Every solution must start on nail `1` and end on nail `n`.
* The output must consist of a sequence of steps wherein a step is a combination fo the nail's name and the direction in which to put the string around it.

## Example Output

Here is an example output for `n=5` and `n=3`:

```
1>4<3<2>4>5<          # n=5, incorrect solution
1>2<1<2>3<2<1>2>1<3>  # n=3, correct solution

```

And here is a visual representation of the incorrect solution for `n=5` (awsumz gimp skillz)

The correct solution for `n=1` is simply `1>` or `1<`. For multiple nails, there can be different solutions. You must only output one since this is part of your score.

# Verification

You can verify whether a solution is correct here: www.airblader.de/verify.php.

It uses a GET request, so you can call it directly if you want. For example, if `foo` is a file containing a solution on each line, you can use

```
cat foo | while read line; do echo `wget -qO- "www.airblader.de/verify.php?solution=$line" | grep "Passed" | wc -l`; done

```

If you believe a solution is correct but the verifier marks it as incorrect, please let me know!

*Edit:* And if your output is so long that a GET request won't cut it, let me know and I'll make a POST request version. :)

# Scoring

This is code-golf. The score is the number of bytes of your source-code in UTF-8 encoding, e.g., use this tool. However, there is a potential bonus for every submission:

Run your program for all `n` in the range `[1..20]` and add the *length* of all outputs up to determine your *output score*. Subtract your output score from `6291370` to get the number of *bonus points* that you may deduct from your byte count to get your *overall score*. There is no penalty if your output score is higher than this number.

The submission with the lowest overall score wins. In the unlikely case of a tie, the tie breakers are in this order: higher bonus points, lower byte count, earlier submission date.

Please post both the individual parts (byte count, bonus points) of the score and the final score, e.g., "`LOLCODE (44 - 5 = 39)`".

# Answer
> 5 votes
## GolfScript (51 67 bytes + (7310 7150 - 6,291,370) = -6,284,153)

```
~,{.,({.,.[1]*{(\(@++}@((*1=/{C}%.~+2/-1%{~'<>'^}%*}{[~)'>']}if}:C~

```

This is based on Chris Lusby Taylor's\* recursive commutator construction, better expounded in Picture-Hanging Puzzles, Demaine et al., *Theory of Computing Systems* 54(4):531-550 (2014).

Outputs for the first 20 inputs:

```
1>
1>2<1<2>
1>2<1<2>3<2<1>2>1<3>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>
1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>
1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>13<12>13>12<9>10<9<10>11<10<9>10>9<11>12>13<12<13>11<9>10<9<10>11>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>11<10<9>10>9<11>13<12>13>12<11<9>10<9<10>11>10<9>10>9<12>13<12<13>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>15<13>14<13<14>15>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>15<14<13>14>13<15>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>15<13>14<13<14>15>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14>15<14<13>14>13<15>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>
1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9>17<16>17>16<14>15<14<15>16>17<16<17>15<14>15>14<10>11<10<11>13<12>13>12<11<10>11>10<12>13<12<13>14>15<14<15>17<16>17>16<15<14>15>14<16>17<16<17>13<12>13>12<10>11<10<11>12>13<12<13>11<10>11>10<9<8>9>8<6>7<6<7>8>9<8<9>7<6>7>6<1>2<1<2>3<2<1>2>1<3>5<4>5>4<3<1>2<1<2>3>2<1>2>1<4>5<4<5>6>7<6<7>9<8>9>8<7<6>7>6<8>9<8<9>5<4>5>4<1>2<1<2>3<2<1>2>1<3>4>5<4<5>3<1>2<1<2>3>2<1>2>1<10>11<10<11>13<12>13>12<11<10>11>10<12>13<12<13>17<16>17>16<14>15<14<15>16>17<16<17>15<14>15>14<13<12>13>12<10>11<10<11>12>13<12<13>11<10>11>10<14>15<14<15>17<16>17>16<15<14>15>14<16>17<16<17>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10>18<17>18>17<15>16<15<16>17>18<17<18>16<15>16>15<11>12<11<12>14<13>14>13<12<11>12>11<13>14<13<14>15>16<15<16>18<17>18>17<16<15>16>15<17>18<17<18>14<13>14>13<11>12<11<12>13>14<13<14>12<11>12>11<10<9>10>9<7>8<7<8>9>10<9<10>8<7>8>7<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7>8<7<8>10<9>10>9<8<7>8>7<9>10<9<10>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<11>12<11<12>14<13>14>13<12<11>12>11<13>14<13<14>18<17>18>17<15>16<15<16>17>18<17<18>16<15>16>15<14<13>14>13<11>12<11<12>13>14<13<14>12<11>12>11<15>16<15<16>18<17>18>17<16<15>16>15<17>18<17<18>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11>19<18>19>18<16>17<16<17>18>19<18<19>17<16>17>16<12>13<12<13>15<14>15>14<13<12>13>12<14>15<14<15>16>17<16<17>19<18>19>18<17<16>17>16<18>19<18<19>15<14>15>14<12>13<12<13>14>15<14<15>13<12>13>12<11<10>11>10<8>9<8<9>10>11<10<11>9<8>9>8<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>7<5>6<5<6>7>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>7<6<5>6>5<7>8>9<8<9>11<10>11>10<9<8>9>8<10>11<10<11>7<5>6<5<6>7>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>7<6<5>6>5<7>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<12>13<12<13>15<14>15>14<13<12>13>12<14>15<14<15>19<18>19>18<16>17<16<17>18>19<18<19>17<16>17>16<15<14>15>14<12>13<12<13>14>15<14<15>13<12>13>12<16>17<16<17>19<18>19>18<17<16>17>16<18>19<18<19>
1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>20<19>20>19<17>18<17<18>19>20<19<20>18<17>18>17<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>17>18<17<18>20<19>20>19<18<17>18>17<19>20<19<20>16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<12<11>12>11<9>10<9<10>11>12<11<12>10<9>10>9<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>9>10<9<10>12<11>12>11<10<9>10>9<11>12<11<12>8<7>8>7<5>6<5<6>7>8<7<8>6<5>6>5<1>2<1<2>4<3>4>3<2<1>2>1<3>4<3<4>5>6<5<6>8<7>8>7<6<5>6>5<7>8<7<8>4<3>4>3<1>2<1<2>3>4<3<4>2<1>2>1<13>14<13<14>16<15>16>15<14<13>14>13<15>16<15<16>20<19>20>19<17>18<17<18>19>20<19<20>18<17>18>17<16<15>16>15<13>14<13<14>15>16<15<16>14<13>14>13<17>18<17<18>20<19>20>19<18<17>18>17<19>20<19<20>

```

NB I think that the longer answers will fail the online test because it uses `GET` rather than `POST` and URLs are not guaranteed to be handled correctly if they're longer than 255 chars.

There are two tweaks on the standard construction:

1. In order to ensure that it finishes on the last nail, I actually form the commutator `[x_1, x_2^-1]` instead of `[x_1, x_2]`.
2. Following xnor's example, I don't split 50-50. It turns out that to balance it so the larger numbers are used less frequently\** the ideal split is according to A006165. I'm using David Wilson's observation to calculate it.

* No relation, as far as I'm aware.
\** Well, within the same recursive commutator approach. I'm not claiming to have solved the open problem of proving it optimal.

# Answer
> 4 votes
# Python 2 (208 bytes + (7230 - 6,291,370) = -6,283,932)

```
def f(a,b):
 if a<b+2:return[a]
 m=(a+b+1)/2
 while all(8*x!=2**len(bin(x))for x in[a-m,m-b]):m+=1
 A=f(a,m);B=f(m,b)
 return[-x for x in A+B][::-1]+B+A
print"1<1>"+"".join(`abs(x)`+"<>"[x>0]for x in f(input(),0))

```

The function `f` recursively makes an answer by combining half-solutions as A^{-1}\*B^{-1}\*A\*B, represents inverses by negation. `f(a,b)` is a solution for the numbers in the half-open interval `[a,b)`.

*Edit:* To comply with the requirement to start with `1` and end with `n`, I flipped the order to always end with `n` by using reversed intervals, and simply append `"1<1>"` to the beginning.

*Edit*: Saved 136 symbols in output by rounding the other way in picking intervals, causing intervals with larger numbers (and so likelier to have two digits) to be shorter.

*Edit*: Saved 100 symbols by splitting the intervals unevenly so the one with larger numbers is shorter. This doesn't lengthen the number of operations used as long as the lengths never cross powers of 2.

*Edit*: Reintroduced favorable rounding, -50 symbols, 2+ code chars.

Outputs for 1 through 20:

```
1<1>1>
1<1>1<2<1>2>
1<1>2<1<2>1>3<1<2<1>2>3>
1<1>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>
1<1>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>
1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>
1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>
1<1>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>
1<1>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9>
1<1>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10>
1<1>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11>
1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>
1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>13<12<13>12>11<10<9<10>9>11>9<10<9>10>12<13<12>13>10<9<10>9>11<9<10<9>10>11>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>11<10<9<10>9>11>9<10<9>10>13<12<13>12>10<9<10>9>11<9<10<9>10>11>12<13<12>13>
1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>14<13<14>13>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>13<14<13>14>
1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>15<14<13<14>13>15>13<14<13>14>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>15<13<14<13>14>15>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>15<14<13<14>13>15>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>14<13<14>13>15<13<14<13>14>15>
1<1>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>
1<1>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>17<16<17>16>15<14<15>14>16<17<16>17>14<15<14>15>13<12<13>12>11<10<11>10>12<13<12>13>10<11<10>11>15<14<15>14>17<16<17>16>14<15<14>15>16<17<16>17>11<10<11>10>13<12<13>12>10<11<10>11>12<13<12>13>5<4<5>4>3<2<1<2>1>3>1<2<1>2>4<5<4>5>2<1<2>1>3<1<2<1>2>3>9<8<9>8>7<6<7>6>8<9<8>9>6<7<6>7>3<2<1<2>1>3>1<2<1>2>5<4<5>4>2<1<2>1>3<1<2<1>2>3>4<5<4>5>7<6<7>6>9<8<9>8>6<7<6>7>8<9<8>9>13<12<13>12>11<10<11>10>12<13<12>13>10<11<10>11>17<16<17>16>15<14<15>14>16<17<16>17>14<15<14>15>11<10<11>10>13<12<13>12>10<11<10>11>12<13<12>13>15<14<15>14>17<16<17>16>14<15<14>15>16<17<16>17>
1<1>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>18<17<18>17>16<15<16>15>17<18<17>18>15<16<15>16>14<13<14>13>12<11<12>11>13<14<13>14>11<12<11>12>16<15<16>15>18<17<18>17>15<16<15>16>17<18<17>18>12<11<12>11>14<13<14>13>11<12<11>12>13<14<13>14>6<5<6>5>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>8<7<8>7>9<10<9>10>7<8<7>8>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>5<6<5>6>8<7<8>7>10<9<10>9>7<8<7>8>9<10<9>10>14<13<14>13>12<11<12>11>13<14<13>14>11<12<11>12>18<17<18>17>16<15<16>15>17<18<17>18>15<16<15>16>12<11<12>11>14<13<14>13>11<12<11>12>13<14<13>14>16<15<16>15>18<17<18>17>15<16<15>16>17<18<17>18>
1<1>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>19<18<19>18>17<16<17>16>18<19<18>19>16<17<16>17>15<14<15>14>13<12<13>12>14<15<14>15>12<13<12>13>17<16<17>16>19<18<19>18>16<17<16>17>18<19<18>19>13<12<13>12>15<14<15>14>12<13<12>13>14<15<14>15>7<6<5<6>5>7>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>7<5<6<5>6>7>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>11<10<11>10>9<8<9>8>10<11<10>11>8<9<8>9>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>7<6<5<6>5>7>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>7<5<6<5>6>7>9<8<9>8>11<10<11>10>8<9<8>9>10<11<10>11>15<14<15>14>13<12<13>12>14<15<14>15>12<13<12>13>19<18<19>18>17<16<17>16>18<19<18>19>16<17<16>17>13<12<13>12>15<14<15>14>12<13<12>13>14<15<14>15>17<16<17>16>19<18<19>18>16<17<16>17>18<19<18>19>
1<1>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>20<19<20>19>18<17<18>17>19<20<19>20>17<18<17>18>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>18<17<18>17>20<19<20>19>17<18<17>18>19<20<19>20>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>12<11<12>11>10<9<10>9>11<12<11>12>9<10<9>10>4<3<4>3>2<1<2>1>3<4<3>4>1<2<1>2>8<7<8>7>6<5<6>5>7<8<7>8>5<6<5>6>2<1<2>1>4<3<4>3>1<2<1>2>3<4<3>4>6<5<6>5>8<7<8>7>5<6<5>6>7<8<7>8>10<9<10>9>12<11<12>11>9<10<9>10>11<12<11>12>16<15<16>15>14<13<14>13>15<16<15>16>13<14<13>14>20<19<20>19>18<17<18>17>19<20<19>20>17<18<17>18>14<13<14>13>16<15<16>15>13<14<13>14>15<16<15>16>18<17<18>17>20<19<20>19>17<18<17>18>19<20<19>20>

```

# Answer
> 1 votes
# C - (199 bytes - 0) = 199

```
p,n,i;main(int x,char **a){for(n=atoi(a[x=i=1]);i<n;i++)x=x*2+2;int o[x];*o=1;for(x=2;n/x;o[++p]=-x++)for(o[i=(++p)]=x;i;o[++p]=-o[--i]);for(i=0;i<=p;printf("%d%s",abs(o[i]),(o[i]<0)?"<":">"),i++);}

```

**With line breaks:**

```
p,n,i;
main(int x,char **a)
{
    for(n=atoi(a[x=i=1]);i<n;i++)
        x=x*2+2;
    int o[x];
    *o=1;
    for(x=2;n/x;o[++p]=-x++)
        for(o[i=(++p)]=x;i;o[++p]=-o[--i]);
    for(i=0;i<=p;printf("%d%s",abs(o[i]),(o[i]<0)?"<":">"),i++);
}

```

Probably a fairly naive algorithm given that I don't know that much about knot theory. Basically just adds the next higher number, then reverses the whole instruction set to unwind it. This would likely much more concise in a language that handles sets better...

The total output length for `n` in the range `[1..20]` was 6,291,370 bytes of output (3,145,685 instructions). This was huge enough that I only posted sample outputs for `n` in the range `[1..10]`.

---
Tags: code-golf
---


title: Stack Exchange Stock Exchange ~ Revised

text:
# Question
Title: Stack Exchange Stock Exchange ~ Revised
# Background

You are all traders for a slightly less than reputable stock firm. You all are part of a group of traders who focus only on one specific stock.

Each hour each trader has a chance to Buy X stocks or Sell X stocks. There are 50 hours per round and 3 rounds per competition. At the end of all of the rounds the trader with the highest average value wins a trip to Jamaica!

# Gameplay

There are 3 rounds of 50 turns each.

Each trader begins the round with $5000 and **A random number of shares between 20 and 30** shares. The price of the shares starts at a random number between 10 and 150.

Each turn each trader can Buy any number of shares they can afford or Sell any number of shares they currently hold, each for the current price per share.

The price per share increases by a random number between 1 and 5 for each share bought and decreases by a random value between 2 and 6 for each share sold. The minimum price is $1.

It is important to note that all traders process their transactions at the same time, meaning that any trader buying/selling shares will not affect the price until the next turn.

The player with the highest average value at the end of the 3 rounds wins. Value is determined by taking the amount of money left over at the end of the round and adding the number of shares owned by the trader * closing market price.

# Arguments

Your program will be rerun at the start of each turn receiving the current market price, the trader's current amount of money and the number of shares owned by that trader.

Ex:

```
120 5000 0

```

# Output

Your trader program must output a letter corresponding to the action it would like to take followed by the quantity.

Ex:

```
B10 //Buy 10 shares

```

or

```
S3 //Sell 3 shares

```

The trader also has the option to not do anything that turn. That can be accomplished by outputting a W or any other command that is not 'B\>amnt\<' or 'S\>amnt\<'

# Submissions

Your program will be inside a 'players/\>your program name\<' directory:

```
+-- players
|   +-- BotNameFolder
|       +-- BotProgram

```

Please provide your code along with a command line argument to run it from inside the 'players' directory. For example the Test1 trader could be run with `java -cp "Test1" Test1`

# Additional Rules

Go ahead, shoot yourself EmoWolf, Idc.

No messing with anything outside of your BotNameFolder directory, feel free to create files in there though for persistent info throughout rounds / turns.

Do not intentionally create programs to crash the simulation.

I will accept multiple entries per user, as long as the entries act as seperate entities (No insider trading).

# Leaderboard

```
[java&-cp&"TestPlayer"&Test1]:$10027395221
[python&daydreamer/daydreamer.py]:$5000
[java&-cp&"DayTrader"&DayTrader]:$4713199930331196453

```

**I will try to update the leaderboard at least once a day**

# Controller

```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;

public class Controller {

    public static BigInteger marketValue = BigInteger.valueOf(100);
    public static BigInteger newValue = BigInteger.valueOf(100);

    public static final char BUY = 'B';
    public static final char SELL = 'S';

    public static final int MARKET_INDEX = 1;
    public static final int MONEY_INDEX = 2;
    public static final int SHARE_INDEX = 3;

    public static int numRunning = 0;
    public static final int MAX_RUNNING = 10;

    public static void main(String[] args){
        try {
            BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("resources/config")));

            int numRounds = Integer.parseInt(br1.readLine());
            int turnsPerRound = Integer.parseInt(br1.readLine());

            //Create the array of players
            List<String> players = new LinkedList<String>();
            String line1 = null;
            while((line1 = br1.readLine()) != null){
                players.add(line1);
            }
            BigInteger[] totalVals = new BigInteger[players.size()];
            for(int i = 0; i < totalVals.length; i++){
                totalVals[i] = BigInteger.valueOf(0);
            }
            br1.close();

            //Begin processing
            for(int round = 0; round < numRounds; round++){
                //Create players' shares and currency array
                Map<String,BigInteger[]> vals = new HashMap<String, BigInteger[]>();
                for(int i = 0; i < players.size(); i++){
                    vals.put(players.get(i), new BigInteger[]{BigInteger.valueOf(5000), BigInteger.valueOf(getRandInt(20,30))});
                }
                marketValue = BigInteger.valueOf(getRandInt(10,150));
                newValue = marketValue;
                for(int turn = 0; turn < turnsPerRound; turn++){
                    marketValue = newValue;
                    Queue<Object[]> processQueue = new LinkedList<Object[]>();
                    for(String playerKey : vals.keySet()){
                        BigInteger[] valSet = vals.get(playerKey);
                        String[] pkParts = playerKey.split("&");
                        String[] parts = new String[pkParts.length + 3];
                        for(int i = 0; i < pkParts.length; i++){
                            parts[i] = pkParts[i];
                        }
                        parts[pkParts.length] = marketValue + "";
                        parts[pkParts.length + 1] = valSet[0] + "";
                        parts[pkParts.length + 2] = valSet[1] + "";
                        processQueue.add(new Object[]{playerKey, parts});
                    }

                    while(!processQueue.isEmpty() || numRunning > 0){
                        if(numRunning < MAX_RUNNING && !processQueue.isEmpty()){
                            numRunning++;
                            Object[] o = processQueue.poll();
                            String pKey = (String)(o[0]);
                            String[] p = (String[])(o[1]);
                            try {
                                Process proc = new ProcessBuilder(p).directory(new File("resources/players").getAbsoluteFile()).start();
                                BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                                String line = br.readLine();
                                br.close();
                                switch(line.charAt(0)){
                                case BUY :
                                    BigInteger numShares = new BigInteger(line.substring(1).trim());
                                    if(numShares.multiply(marketValue).compareTo(vals.get(pKey)[0]) <= 0){
                                        BigInteger[] tempVals = vals.get(pKey);
                                        tempVals[0] = tempVals[0].subtract(numShares.multiply(marketValue));
                                        tempVals[1] = tempVals[1].add(numShares);
                                        vals.put(pKey, tempVals);
                                        newValue = newValue.add(numShares.multiply(BigInteger.valueOf(getRandInt(0,2))));
                                        if(newValue.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) >= 1){
                                            newValue = BigInteger.valueOf(Integer.MAX_VALUE - 1);
                                        }
                                    }
                                    break;
                                case SELL:
                                    BigInteger shares = new BigInteger(line.substring(1).trim());
                                    if(shares.compareTo(vals.get(pKey)[1]) <= 0){
                                        BigInteger[] tempVals = vals.get(pKey);
                                        tempVals[0] = tempVals[0].add(shares.multiply(marketValue));
                                        tempVals[1] = tempVals[1].subtract(shares);
                                        vals.put(pKey, tempVals);
                                        newValue = newValue.subtract(shares.multiply(BigInteger.valueOf(getRandInt(5,10))));
                                        if(newValue.compareTo(BigInteger.valueOf(1)) <= -1){
                                            newValue = BigInteger.valueOf(1);
                                        }
                                    }
                                    break;
                                }
                            } catch (Exception e) {
                                System.err.println("[" + pKey + "] threw error:");
                                e.printStackTrace();
                            } finally{
                                numRunning--;
                            }
                        }else{
                            try{
                                Thread.sleep(50);
                                continue;
                            }catch(InterruptedException e){
                                continue;
                            }
                        }
                    }
                    System.out.println("Turn " + turn + " over: " + marketValue);
                }
                System.out.println("End of round market value is: " + marketValue);
                int count = 0;
                for(String player : vals.keySet()){
                    totalVals[count] = totalVals[count].add(vals.get(player)[0].add(vals.get(player)[1].multiply(marketValue)));
                    count++;
                }
                newValue = BigInteger.valueOf(100);
            }
            for(int i = 0; i < players.size(); i++){
                System.out.println("[" + players.get(i) + "]:$" + (totalVals[i].divide(BigInteger.valueOf(numRounds))));
            }
        } catch (Exception e) {
            System.err.println("An exception occured while running the controller.");
            e.printStackTrace();
        }
    }
    public static Random r = new Random(new Date().getTime());
    public static int getRandInt(int min, int max){
        return r.nextInt(max - min) + min;
    }
}

```

***Compile this with `java Controller.java` and run from a directory containing a directory like below:***

```
+-- resources
|   +-- config
|   +-- players
|       +-- Player1Folder
|           +-- Player1Program
|       +-- Player2Folder
|           +-- Player2Program

```

The file `config` should look something like this:

```
3
50
java&-cp&"TestPlayer"&Test1
python&daydreamer/daydreamer.py
java&-cp&"DayTrader"&DayTrader

```

***First number is number of rounds, second number is turns per round, followed by the commands to run each player.***

# Replace spaces with ampersands! ('&')

~Let me know if I can improve the wording of this post at all, and happy trading!

# Answer
I present 'daydreamer', who is always asleep and forgets to buy or sell anything. He hopes that other players will have a net loss. Python code:

```
if __name__ == "__main__":
    print "W"

```

run with `python daydreamer\daydreamer.py 120 5000 0` or whatever values you want.

I will post a more serious answer later, this is just to get the ball rolling :)
> 18 votes

# Answer
# DayTrader

Updated for rule change made on 8/21/2014, where players now start with 20-30 shares.

Buys as much as possible, then sells as much as possible.

**Philosophy**

We hope that the below pattern will repeat itself over and over. Note that by adhering to this pattern, we also contribute to it.

* Everyone can only buy or hold on round one. The value can only increase, so we buy.
* Everyone can buy more, hold, or sell on round two. We don't expect many players to buy on round two, so we sell.

The pattern is crystal clear at the beginning. Value *will* increase after round one. It should decrease after round two. Beyond that, projections get fuzzy. I expect to do well in the early rounds, before the market stabilizes.

```
import java.math.BigInteger;

/**
 * Submission for http://codegolf.stackexchange.com/q/36515/18487
 * @author Rainbolt
 */
public class DayTrader {

    /**
     * @param args the command line arguments containing the current
     * market value, our current money, and our current shares
     */
    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);

        // If we have less than or equal to 30 shares, buy as much as possible
        if (myShares.compareTo(new BigInteger("30")) <= 0) {
            System.out.println("B" + myMoney.divide(marketValue).toString());
        // Otherwise, sell as much as possible
        } else {
            System.out.println("S" + myShares.toString());
        }
    }

}

```

Compile with `javac DayTrader.java`. Run with `java -cp "DayTrader" DayTrader`.
> 13 votes

# Answer
# Walt Disney - Python 3

Walt waits until the shares hit rock bottom and then buys as much as his money allows. Then, when the price soars, he sells them all.

Based upon Disney's strategy when he 'survived' through the Wall Street Crash. Unfortunately, my program cannot build theme parks... If only...

Run:

```
python3 waltdisney.py

```

Code:

```
from sys import argv
import os

price=int(argv[1])
money=int(argv[2])
share=int(argv[3])

if os.path.exists('./buyingprice.txt'):
    f = open('buyingprice.txt', 'r')
    buyingprice=int(f.read())
    f.close()
else:
    buyingprice=0

if share > 0:
    if price > buyingprice*10:
        print('S'+str(share))
    else:
        print('W')
elif money > 0:
    if buyingprice==0:
        print('B10')
        m=open('buyingprice.txt', 'w')
        m.write(str(price))
        m.close()
    elif price <= buyingprice:
        print('B'+str(int(money/price)))
        g=open('buyingprice.txt', 'w')
        g.write(str(price))
        g.close()
    else:
        print('W')

```
> 9 votes

# Answer
## Tommy

only knows what he has but is determined to risk everything on the market. If he can buy, he will. If he can't, he sells everything he has so he can next turn. (This will work well with extreme ones like DayTrader but will autocorrect if the value drops when he thinks it will grow.)

```
import java.math.BigInteger;

public class Tommy {
    public static void main(String[] args) {
        BigInteger Value = new BigInteger(args[0]);
        BigInteger Money = new BigInteger(args[1]);
        BigInteger Shares = new BigInteger(args[2]);

       if (Money.compareTo(Value)<1) {
           System.out.print("S" + Shares.toString());
       } else {
           System.out.print("B" + Money.divide(Value).toString());
       }
    }

}

```

## Golfscript

This is the same code but if prefered this. I wrote the java after in case the BigInteger thing was needed. Use whatever is easier.

```
2$2$>{@@;;"S"\}{;\/"B"\} if

```
> 8 votes

# Answer
## BuyAndHold - C

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

/* BuyAndHold
 * Code revised from OptoKopper's WaitForCrash.c
 */
int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);

    if (money >= share_price) {
        printf("B%lld\n", money / share_price);
    } else {
        printf("W\n");
    }

    return 0;
}

```

Compile with: gcc buyandhold.c -o buyandhold

Run it with ./buyandhold PRICE MONEY SHARES
> 6 votes

# Answer
**Alfred Pennyworth** \- Python 2

While I was out on patrol one night, Alfred tried to create a stock trading program without my knowing. He thought he could hide it from me, but I found it and figured out what it did. Because I'm Batman. Now I've decided to enter it into a competition to teach him a lesson.

Money is no object to Alfred because I'm REALLY rich, but he's still smart about his trading. When he's out of shares, he buys as many as he can afford, regardless of market price. Then he sells 10 (or all remaining) shares every time the market price is higher than the price it was purchased at.

```
import argparse

parser = argparse.ArgumentParser(description="This is a private matter, Master Bruce. Learn how to make your own bed and I will tell you.")
parser.add_argument("Stuff", type=int, nargs='+', help="You don't need to know, Master Bruce.")

args=parser.parse_args()
vals=[]
for x in args:
    vals.append(x)

a=vals[0]
b=vals[1]
c=vals[2]

if c==0:
    x=1
    while x*a<b:
        x+=1
    print "B"+str(x)
    with open("lastval.txt", w) as f:
        f.write(a)

else:
    lastval=next(open("lastval.txt"))
    if a>lastval:print "S10" if c>10 else "S"+str(c)
    else:print 'W'

```

Run with: `python GoAwayMasterBruce.py <args>`
> 6 votes

# Answer
## NaiveBot

NaiveBot is new to all this "stock market" hooplah. He just assumes that when the price is going up he should buy, and when the price goes down he should sell. But he's no sap, he's got a trick up his sleeve! He only ever buys half of what he can afford, and only ever sells half of what he has.

No more living in a box under the freeway for NaiveBot!

```
<?php
$cur = array('price' => $argv[1], 'funds' => $argv[2], 'shares' => $argv[3]);

$cachefile = 'cache.json';
if( ! file_exists($cachefile) ) { $cache = array(); }
else { $cache = json_decode(file_get_contents($cachefile), true); }

// determine action
if( empty($cache) ) {
    $action = 'buy'; // always buy on first turn
} else if( $cur['price'] > $cache[count($cache)-1]['price'] ) {
    $action = 'buy';
} else if( $cur['price'] < $cache[count($cache)-1]['price'] ) {
    $action = 'sell';
} else {
    $action = 'hold';
}

// determine volume
if( $action == 'hold' ) {
    $volume = 0;
} else if( $action == 'buy' ) {
    // spend half my money on shares!
    $volume = floor(($cur['funds']/2)/$cur['price']);
} else if( $action == 'sell' ) {
    // sell half my shares!
    $volume = floor($cur['shares']/2);
}

// do a thing!
if( $action == 'hold' ) { echo 'W'; }
else if( $action == 'buy' ) { echo "B $volume"; }
else { echo "S $volume"; }
echo "\n";

$cache[] = $cur;
if( count($cache) == 50 ) { unlink($cachefile); } // wipe cache on last turn
else { file_put_contents($cachefile,json_encode($cache)); } // write cache

```

Run with `php Naivebot.php $1 $2 $3`, makes a `cache.json` in its current folder.
> 5 votes

# Answer
# Profit - Haskell

1. Wait until the price is 1/maxValue
2. Buy/Sell everything
3. ????
4. PROFIT!!!

---

```
import System.Environment (getArgs)

main = putStrLn . trade . map read =<< getArgs

trade :: [Integer] -> String
trade [p,m,s] -- not intended
  | p == 1 = "B" ++ (show m)
  | p == (fromIntegral $ (maxBound::Int) - 1) = "S" ++ (show s)
  | otherwise = "W"

```

Compile with `ghc profit.hs` and run with `./profit price money stock`.

If it is not efficient enough, add `-O3` flag, although it probably is overkill :D

---

## Edit:

"optimised", now sells everything when the price is equal to `Integer.MAX_VALUE`.
> 5 votes

# Answer
## WaitForCrash

EDIT: fixed flaw in concept

EDIT: now using long long int

This is my first try. It behaves really simple and keeps one share to distinguish if it is the first round or a later one. In the first round nothing can be lost, so it buys shares. If it has shares it sells them. If eventually share prices drop to 10, it will buy again.

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

int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);
    long long int shares_owned = strtoll(argv[3], NULL, 0);

    if(shares_owned > 1) {
        printf("S%lld\n", shares_owned - 1);
    } else if (shares_owned == 0 || share_price == 10) {
        printf("B%lld\n", money / share_price);
    } else {
        printf("W\n");
    }

    return 0;
}

```

compile with: `gcc waitforcrash.c -o waitforcrash`

run it as `./waitforcrash PRICE MONEY SHARES`
> 4 votes

# Answer
## Earthquaker

Alternates between buying everything and selling everything (but one). It doesn't really aim to win as much as it does disrupt everyone else.

```
using System;
using System.IO;

namespace Earthquaker
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 3)
                return;

            int stockPrice = int.Parse(args[0]);
            int money = int.Parse(args[1]);
            int stocks = int.Parse(args[2]);

            bool shouldBuy = true;

            if (stocks != 0)
            {
                StreamReader sr = new StreamReader("brain.txt");
                if (sr.ReadLine() == "B")
                    shouldBuy = false;
                else
                    shouldBuy = true;
                sr.Close();
            }

            if (shouldBuy)
                Console.Write("B" + (money / stockPrice));
            else
                Console.Write("S" + (stocks - 1));

            StreamWriter sw = new StreamWriter("brain.txt", false);
            sw.Write(shouldBuy ? 'B' : 'S');
            sw.Close();
        }
    }
}

```

Compile with `csc Earthquaker.cs`. Run with `Earthquaker`.
> 3 votes

# Answer
# MonkeyTrader (in JAVA)

There's a saying that monkeys are good traders. I make the proof. Decisions between "buy" and "sell" are totally random.

```
import java.math.BigInteger;
import java.util.Random;

public class MonkeyTrader {
    /**
     * @param args the command line arguments containing the current
     * market value, our current money, and our current shares
     */
    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);
        Random random=new Random();

        switch (random.nextInt(2)) {
        case 0:
            System.out.println("B" + myMoney.divide(marketValue));
            break;
        case 1:
            System.out.println("S" + myShares);
            break;
        }
    }
}

```
> 3 votes

# Answer
# IntelliTrader

1st round he will sell his shares if they're a good price: $80 or more. Then he will sell off if the price is the same or better than the last price he sold at, buy if the price is the same or lower than the last price he bought at.

IntelliTrader.java

```
import java.io.*;
import java.math.BigInteger;
import java.util.Properties;

public class IntelliTrader {

    private static final String ROUND_NUM = "roundNum";
    private static final String LAST_BUY = "lastBuy";
    private static final String LAST_SELL = "lastSell";
    private static final String FILE = "IntelliTrader/memory.txt";

    private Properties memory;
    private int roundNum;

    private IntelliTrader(Properties memory) {
        this.memory = memory;
        roundNum = new Integer(memory.getProperty(ROUND_NUM, "0"));
    }

    public String evaluate(BigInteger market, BigInteger money, BigInteger shares) {
        String command = "W";
        if (roundNum == 0) {
            if (market.intValue() > 80) {
                command = sell(market, shares);
            } else {
                command = buy(market, money);
            }
        } else {
            if (market.compareTo(new BigInteger(memory.getProperty(LAST_SELL, "0"))) >= 0) {
                command = sell(market, shares);
            } else if (market.compareTo(new BigInteger(memory.getProperty(LAST_BUY, "999999999"))) <= 0) {
                command = buy(market, money);
            }
        }
        return command;
    }

    private String buy(BigInteger cost, BigInteger money) {
        memory.setProperty(LAST_BUY, cost.toString());
        return "B" + money.divide(cost).toString();
    }

    private String sell(BigInteger cost, BigInteger shares) {
        memory.setProperty(LAST_SELL, cost.toString());
        return "S"+shares.toString();
    }

    public static void main(String[] args) {
        BigInteger marketValue = new BigInteger(args[0]);
        BigInteger myMoney = new BigInteger(args[1]);
        BigInteger myShares = new BigInteger(args[2]);

        Properties memory = new Properties();
        try {
            memory.load(new FileReader(FILE));
        } catch (IOException e) {
            //ignore, file probably doesn't exist yet
        }

        int roundNum = new Integer(memory.getProperty(ROUND_NUM, "0"));
        if (roundNum > 49) {
            roundNum = 0;
            memory.setProperty(ROUND_NUM, "0");
            memory.setProperty(LAST_BUY, "0");
            memory.setProperty(LAST_SELL, "0");
        }

        IntelliTrader it = new IntelliTrader(memory);
        String command = it.evaluate(marketValue, myMoney, myShares);
        System.out.println(command);

        roundNum++;
        memory.setProperty(ROUND_NUM, ""+roundNum);
        try {
            memory.store(new FileWriter(FILE), "IntelliTrader memory properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

```

Compile with **javac IntelliTrader**. Run with **java -cp "IntelliTrader" IntelliTrader**
> 3 votes

# Answer
## LeesonLearnt v1.1 (Java, conservative)

Since the rule change means that we now start with some shares, there's no longer a guaranteed best first move, so I've simplified this by removing the special case for the first turn.

```
import java.math.BigInteger;

public class LeesonLearnt {
    private static final BigInteger THRESHOLD = new BigInteger("100");

    public static void main(String[] args){
        BigInteger price = new BigInteger(args[0]);
        BigInteger capital = new BigInteger(args[1]);
        BigInteger shareholding = new BigInteger(args[2]);

        BigInteger affordable = capital.divide(price);

        // In the long run, the shares will probably lose all their value.
        // But if they're cheap, buying them will pump them and they can be sold at a profit.
        // The target amount of our value held in shares varies exponentially with their price.
        BigInteger targetShareholding = price.compareTo(THRESHOLD) > 0
            ? BigInteger.ZERO
            : affordable.add(shareholding).shiftRight(price.intValue() - 1);
        if (targetShareholding.compareTo(shareholding) <= 0) {
            System.out.println("S" + shareholding.subtract(targetShareholding));
        }
        else {
            BigInteger diff = targetShareholding.subtract(shareholding);
            System.out.println("B" + diff.min(affordable));
        }
    }
}

```

Invoke as

```
java -cp LeesonLearnt LeesonLearnt <price> <capital> <shareholding>

```
> 2 votes

# Answer
# theAnswerOfLifeIs42.py

My program loves the number 42

The rule is simple: I can either buy 42 stock or sell 42 stock.

```
import sys
price, money, shares = [int(arg) for arg in sys.argv[1:]]

if money>42*price:
 print "B 42"
else:
 print "S 42"

```
> 2 votes

# Answer
# Ol' Timer - Fortran 77

This old man is going to waste away his pension after sixty years of working as an office clerk. During his old age, however, he became quite blind, so he can only see he first number of each argument, so he estimates the price. His method is similar to that of Walt's, except Ol' Timer is a little more careless.

Because of the problems with the Fortran printing, I've written a Python program which will help. The program takes the arguments supplied and pipes them through to the Fortran program. Then, the Python program reformats the output to the expected format.

### Compile:

```
gfortran oltimer.for -o oltimer.exe

```

### Run:

```
python3 assistant.py [arg1] [arg2] [arg3]

```

### Python Assistant Code:

```
from subprocess import Popen, PIPE
import sys, re

ret = Popen('./oltimer.exe '+sys.argv[1]+' '+sys.argv[2]+' '+sys.argv[3], stdout=PIPE, shell=True).communicate()[0].decode('utf-8')
value=re.findall(r'\d+',ret)

if 'W' in ret:
     print('W')

elif 'B' in ret:
     print('B'+str(value[0]))

elif 'S' in ret:
     print('S'+str(value[0]))

```

### FORTRAN Main Code:

```
      PROGRAM OLTIMER
C DEFINE VARIABLES
          INTEGER :: PRICE
          INTEGER :: STOCK
          INTEGER :: MONEY
          INTEGER :: INTBUFFER
          CHARACTER :: BUFFER
C GET CMD ARGUMENTS & CONVERT TO INT
          CALL getarg(1, BUFFER)
          READ (BUFFER, '(i10)') PRICE
          CALL getarg(2, BUFFER)
          READ (BUFFER, '(i10)') MONEY
          CALL getarg(3, BUFFER)
          READ (BUFFER, '(i10)') STOCK
C EVALUATE SITUTATION AND MAKE DECISION
          IF (PRICE.LT.5) THEN
            IF (MONEY.GT.0) THEN
                INTBUFFER=(MONEY*50)/(5-PRICE)
                PRINT*,'B',INTBUFFER
            ELSE
                PRINT*,'W'
            END IF
          ELSE
            IF (PRICE.GT.9) THEN
                IF (STOCK.GT.0) THEN
                    INTBUFFER=STOCK/(PRICE-9)
                    PRINT*,'S',INTBUFFER
                ELSE
                    PRINT*,'W'
                END IF
            ELSE
                PRINT*,'W'
            END IF
          END IF
      END PROGRAM

```
> 1 votes

# Answer
## Dollar Cost Averager - Python 3

This strategy attempts to use dollar cost averaging by buying (as close as it can to) a fixed amount of money (arbitrarily set at 150 so that it'll probably use up most of its money by the end) each turn.

```
import sys
price, money, shares = [int(arg) for arg in sys.argv[1:]]
target_per_day = 150
buy = round(min(target_per_day, money) / price)
if buy * price > money:
    buy -= 1
if buy > 0:
    print("B" + str(buy))
else:
    print("W")

```
> 1 votes

# Answer
## Cash Is King - Python 2 or 3

This guy is very pessimistic about the stock market. He'd rather keep his money in cash where he can keep it safe under his mattress.

```
import sys
shares = int(sys.argv[3])
if shares > 0:
    print("S" + str(shares))
else:
    print("W")

```
> 1 votes

# Answer
**Slow and Steady**

As long as it has money, it buys $165 worth of shares. Otherwise it sells all of its shares to get more money, to buy more shares. On the 50th round it makes sure to sell all shares, because in the end we want cash.

```
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SlowAndSteady{
    public static void main(String[] args) {
        BigInteger price = new BigInteger(args[0]);
        BigInteger cash= new BigInteger(args[1]);
        long shares= Long.parseLong(args[2]);
        BigInteger number = new BigInteger("165");
        String count = "0";

        try {
            count = new String(Files.readAllBytes(Paths.get("counter.txt")));
        } catch (IOException e) {

        }

        int c = Integer.parseInt(count)+1;

        if (c >= 50)
        {
            System.out.println("S" + shares);
            c=0;
        }

        else if(cash.compareTo(number) > 0)     System.out.println("B" + (number.divide(price)));

        else System.out.println("S" + shares);

        try {
            Writer wr = new FileWriter("counter.txt");
            wr.write(Integer.toString(c));
            wr.close();
        } catch (IOException e) {
        }
   }
}

```

Compile with javac SlowAndSteady.java. Run with java -cp "SlowAndSteady" SlowAndSteady. Counter should reset between rounds, but if the file is deleted, it will also work.
> 1 votes

# Answer
# Time is Right - Python 3

I got bored so I wrote another entrant...

This young entrepeneur lives his life by the clock. When the time is right, he makes a decision. He also annoyingly uses French out of context... ;)

## Run:

```
python3 timeisright.py [arg1] [arg2] [arg3]

```

## Code:

```
import sys, time

price = int(sys.argv[1])
money = int(sys.argv[2])
shares = int(sys.argv[3])

lheure = int(time.time())

if lheure % 3 == 0:
    print('S'+str(int(shares/4)))
elif lheure % 3 == 1:
    print('B'+str(int(money/4*price)))
else:
    print('W')

```
> 1 votes

# Answer
# BuyHighSellLow

Tracks the market history and buys when the price low and sells when it's high.

```
import sys

storage = 'BuyHighSellLow'
turn = 0
turns = 50
max_start_price = 150
limit = 0.25

price = int(sys.argv[1])
money = int(sys.argv[2])
shares = int(sys.argv[3])

# Calculate average price
with open(storage+'/history', mode='a') as f:
            pass # Create file if it doesn't exist
with open(storage+'/history', mode='r') as f:
    values = list((int(line) for line in f))
    turn = len(values) + 1
    if turn > turns: turn = 1
    if turn == 1:
            average = max_start_price + 1
            turn = 1
    else:
            average = sum((value / turn for value in values))

# Buy low and sell high
if price < average:
    print('B' + str(int(limit * money / price)))
elif price > average:
    print('S' + str(int(limit * shares)))
else:
    print('W')

# Save history
if turn == 1: mode='w'
else: mode = 'a'
with open(storage+'/history', mode=mode) as f:
    print(price, file=f)

```

Run with:

```
python3 BuyHighSellLow/buyhighselllow.py

```
> 1 votes

# Answer
# Test1 Trader

```
public class Test1 {

    public static void main(String[] args){
        int marketValue = Integer.parseInt(args[0]);
        int myMoney = Integer.parseInt(args[1]);
        int myShares = Integer.parseInt(args[2]);

        //Buy 10 if we don't have any.
        if(myShares <= 0){
            System.out.println("B10");
        }else{
            System.out.println("S1");
        }
    }
}

```

Compile with `javac Test1.java` run with `java -cp "Test1" Test1`
> 0 votes

# Answer
# Hedgehog - python2.7

*This is mostly to reserve the name*

```
from __future__ import print_function
from sys import argv

storage = 'prices.txt'
price,cash,shares = map(long, argv[1:])
turn = 1
buy = lambda x: print('B%d' % long(x))
sell = lambda x: print('S%d' % long(x))
cashtoshares = lambda c: long(c/price)
TURN,PRICE,CASH,SHARES=range(4)

try:
    data = [map(long, line.split()) for line in open(storage)]
    if data:
        turn = data[-1][TURN] + 1
except IOError:
    pass
with open(storage, 'a') as pricelist:
    pricelist.write('%d %d %d %d\n' % (turn, price, cash, shares))

if turn == 1:
    buy(cashtoshares(cash)) # convert all cash into shares
elif price == 1:
    buy(cashtoshares(cash)) # cannot buy at a better deal
elif price < 10:
    buy(cashtoshares(cash/2))
elif shares < 10:
    buy(cashtoshares(cash/2))
else:
    sell(shares/2)

```

Run as

```
python hedgehog.py PRICE CASH SHARES

```
> 0 votes

# Answer
## BuyAndSell - C

Similar but not a duplicate of Tommy. Alternates between panic buying as much as possible and selling everything. Almost a duplicate of Earthquaker which retains one share while BuyAndSell sells all shares. BuyAndSell takes no action when it has no shares to sell but hasn't got enough money to buy one share.

```
/* BuyAndSell
 * Code revised from OptoKopper's WaitForCrash.c and my BuyAndHold.c
 * Alternates between buying as many shares as possible and selling everything
 * Run it as ./buyandsell PRICE MONEY SHARES
 */
int main(int argc, char *argv[]) {
    long long int share_price = strtoll(argv[1], NULL, 0);
    long long int money = strtoll(argv[2], NULL, 0);
    long long int shares = strtoll(argv[3], NULL, 0);

    if (money >= share_price) {
        printf("B%lld\n", money / share_price);
    } else {
        if (money == 0) {
            printf("S%lld\n", shares);
        } else {
            printf("W\n");
        }
    }

    return 0;
}

```

Compile with "gcc buyandsell.c -o buyandsell"

Run as "./buyandsell PRICE MONEY SHARES
> 0 votes

# Answer
# Gorge Soros

```
price = ARGV.shift
money = ARGV.shift
stock = ARGV.shift
if price*10<money
  puts "B10"
else
  puts "S#{stock}"
end

```

Buys slowly, than sells everything in an attempt to crash the market.

Run with:`Soros.rb price money stock`
> 0 votes

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