First code golf decathlon

Huzzah, first to complete all the tasks! \o/

Task 1, Perl, 32 bytes

$_=eval join"+",map$_**3,0..$_-1

+1 byte for the -p flag. Commentary: Perl is weird.


Task 2, CJam, 14 bytes

{_mp\)2mL_i=&}

My first CJam program!


Task 3, GolfScript, 8 bytes

~$.,(2/=

Eval STDIN input, sort, take length, decrement, divide by two, then take the item of the sorted array at that index.


Task 4, Python, 77 bytes

def f(i,d=''):
 while i:i,r=i/-2,i%2;i+=r<0;r+=2*(r<0);d=`r`+d
 return d or 0

Thanks to @mbomb007 for shaving off 24 (!) bytes, and to @Sp3000 for another 11.


Task 5, Java, 66 bytes

String f(){return"pneumonoultramicroscopicsilicovolcanoconiosis";}

Boring. Knocked out a verbose language here to save room for golfier languages later.


Task 6, Bash, 39 bytes

((`date +%j`<2))&&echo Happy New Year\!

Thanks to @manatwork for teaching me about %j, shaving off 10 bytes in the process.


Task 7, JavaScript, 148 bytes

a=[];Array(65).join('x').replace(/./g,function(){while(a.push(s=String.fromCharCode(13312+Math.random()*6582))&&a.indexOf(s)==s.length-1);return s})

Generate a string of 64 x's, then replace them all with a callback function that returns a random one of those characters if it isn't already in the array of used characters.


Task 8, Rust, 130 bytes

fn f(a:String,b:String)->bool{let mut c=b.chars();for x in a.chars(){match c.find(|&y|x==y){Some(_)=>(),None=>return false}};true}

Yes, Rust is very very bad at golfing.


Task 9, Ostrich, 18 bytes

{:n;'`\d+`{~n*}X~}

Version 0.7.0. Inspects the array, does a regex replace to change numbers to their multiplied versions, and then evals the resulting string again.


Task 10, Ruby, 58 bytes

->n{([' ______  '*n,'|      | '*n,' ()--() ~'*n]*$/).chop}

"\n" is one character longer than "{actual newline}", which is one character longer than $/. Thanks to @MartinBüttner for shaving off {indeterminate but large number} bytes with various tricks of black magic.


Task 1, 3var, 14 13 bytes

'><k*>#aa/>sp

(Esolang wiki page for 3var)

'                  R = n
 >                 A = n
  <k               B = n-1
    *              R = A*B = n(n-1)
     >             A = n(n-1)
      #aa          B = 2
         /         R = A/B = n(n-1)/2
          >s       A = (n(n-1)/2)^2
            p      Output A

Takes input via a code point, e.g. space is 32.

Thankfully all the operations we need to implement the formula n^2 (n-1)^2 / 4 are single chars (decrementing, multiplication and squaring), yet it takes 3 bytes to set B to 2 (reset-increment-increment).


Task 2, Retina, 38 33 bytes

^
1
^(..|.(..+)\2+|(.(..)+)\3*)$
<empty>

(Github repository for Retina)

Each line goes in a separate file, but you can test the above as is with the -s flag (replacing <empty> with nothing). Input should be unary with 1s, e.g. 1111111 for 7.

Here's what each regex substitution (specified by a pair of lines) does:

  1. Tack on an extra 1 to the front
  2. Replace anything of the form 2, 1 + composite or not power of 2 with nothing.

This adds an extra 1 to Mersenne primes, while every other number is obliterated.


Task 3, Racket, 71 bytes

#lang racket
(define(m x)(list-ref(sort x <)(quotient(-(length x)1)2)))

Lisp-like languages are just too wordy. Example run:

> (m `(1 3 4 2))
2

Task 4, ><>, 31 bytes

:?!v:2%:@-02-,
)?~\l1
!;n>l?

(Esolang wiki page for ><>)

The above is 28 bytes, and requires the -v flag in the Python interpreter for another 3 bytes, e.g. run like

$ py -3 fish.py negabinary.fish -v -137
10001011

The nice thing about ><> here is that we can calculate the digits one by one via modulo and division, which gives the digits in reverse order, perfect for printing off a stack.


Task 5, Parenthetic, 1448 1386 bytes

((()()())(()()()())((()())((()(())()))((()(())(())())((()(()))(()(())())((()(()))((())())((()()(()))((())()()()()()()()())((())()()()()()()()()()()()())))))))((()()())(()()())((()())((()(())()))((()()()())((()(()))(()(())())((())()()()()()()()()()()())))))((()(()))((()()())((())()()()()))((()()())((())()()))((()()()())((())()()()()))((()()())((())()()()()()()()()()))((()()())((())()))((()()())((())()()()))((()()())((())()()))((()()())((())()()()))((()()())((())()()()()()()()()()))((()()())((())))((()()())((())()()()()()()()()))((()()())((())()()()()()()))((()()()())((())))((()()())((())()))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()()()()))((()()())((())()()()))((()()())((())()()()()()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()()()))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()()()()()))((()()()())((())()()()()()()()()))((()()())((())))((()()()())((())()()()()()()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()()()()()()()()()))((()()())((())()()()))((()()())((())))((()()()())((())()()))((()()()())((())))((()()())((())()()))((()()())((())()()()))((()()()())((())()()))((()()())((())()()()))((()()())((())()()))((()()()())((())()()()()()()()()))((()()())((())()()()))((()()())((())()()()()()()()))((()()()())((())()()()()()()()()))((()()())((())()()()()()()())))

(Github repository for Parenthetic)

I have a CJam answer for this which is shorter than the string itself, but I can't use it so I thought I'd go the other way.

Python 3 generating code:

char97 = "((()()())(()()()())((()())((()(())()))((()(())(())())((()(()))(()(())())((()(()))((())())((()()(()))((())()()()()()()()())((())()()()()()()()()()()()())))))))"
char108 = "((()()())(()()())((()())((()(())()))((()()()())((()(()))(()(())())((())()()()()()()()()()()())))))"
open_str = "((()(()))"
close_str = ")"

target = "pneumonoultramicroscopicsilicovolcanoconiosis"
output = [char97, char108, open_str]

for c in target:
    if ord(c) >= 108:
        output.append("((()()())((())%s))"%("()"*(ord(c)-108)))
    else:
        output.append("((()()()())((())%s))"%("()"*(ord(c)-97)))

output.append(close_str)
print("".join(output))

Here's the corresponding Lisp-like code:

(define f (lambda (n) (char (+ n 97))))
(define g (lambda (n) (f (+ n 11))))

(+
   (g 4)  // p
   (g 2)  // n
   (f 4)  // e
   ...
)

Apparently it was okay to override define by naming g as ()(), which saved a lot of bytes.


Task 6, CJam, 26 bytes

XY]et1>>"Happy New Year!"*

Checks that the [month day] part of the local time array is less than [1, 2].


Task 7, Python, 73 bytes

from random import*
print(*map(chr,sample(range(13312,19894),64)),sep="")

Just a straightforward Python 3 implementation.


Task 8, Prelude, 46 41 bytes

?(?)#(#)?(v-(#)?)10)!
      ^      1 # (0

(Esolang wiki page for Prelude)

I think this works – it's probably still golfable, but it's my first time doing a non-trivial golf in Prelude. The input format is <needle>NUL<haystack>, where NUL is 0x00. This works best with NUMERIC_OUTPUT = True in the Python interpreter, since that'll make it output 1 or 0 as appropriate.

I chose Prelude because there's two properties which make it very nice for this task:

  • It is stack-based, so you can first read in the needle, then process the haystack one char at a time, and
  • Prelude's stack has an infinite number of 0s at the bottom, so you don't need to handle the case where the needle runs out of characters.

This would have been even better if Prelude had a NOT operator.

Here's the breakdown:

?(?)#    Read input up to the NUL, discarding the NUL afterwards

(#)      Move the needle to the second voice, effectively reversing the stack
 ^

?(...?)  Read haystack

  v-     Compare top needle char with haystack char by subtraction

  (#)    If equal, pop the needle char
   1 #

10)!     Output 1 if the top needle char is 0 (bottom of stack), 0 otherwise
(0

(-5 bytes thanks to @MartinBüttner)


Task 9, Mathematica, 4 bytes

#2#&

Something like 2 {{0, 1}, {1, 0}} is implicitly multiplication in Mathematica, so this just puts the arguments side-by-side.

As noted by @MartinButtner and @alephalpha, 1##& is another 4 byte answer. See the former for an explanation.


Task 10, Rail, 246 237 bytes

$'main'
 0/aima19-@
@------e<
         -(!!)()[ ][ ______ ]{f}[\n\]o()[ ][|      |]{f}[\n\]o()[~][ ()--() ]{f}#
$'f'                 #           #
 -(!x!)(!y!)(!!)()0g<  -(x)o()1g<  -(y)o()1s(y)(x){f}#
                     -/          -/

(Esolang wiki page for Rail)

I couldn't pass up the opportunity to do a train-related task in Rail :) The whitespace looks pretty golfable, but with branching taking up three lines it'll take a bit of work to compact.

Input is an integer via STDIN, but there needs to be an EOF. The top-left portion

 0/aima19-@
@------e<

is an atoi loop which converts the input to an integer while not EOF (checked by the e instruction).

The function f on the last three lines takes x, y, n, and outputs the string x n times, separated by y. The function is recursive, with n decrementing by one each time until it becomes zero. f is called three times, supplying different strings for each row. Weirdly, Rail allows variable names to be empty, which saves a few bytes.

Most of the bytes unfortunately come from (!x!), which pops the top of the stack and assigns it to variable x, and (x), which pushes x onto the stack. This is necessary because there's no duplicate operator in Rail, so (!x!)(x)(x) is the only way to copy the top of the stack.


Task 1, CJam, 7 bytes

q~,:+_*

I just wanted to get the (presumably) optimal CJam solution for this in. It makes use of the fact that the sum of the first n cubes is the square of the nth triangular number, which is itself the sum of the first n integers.

Test it here.


Task 4, Fission, 173 88 78 69 68 bytes

GitHub repository for Fission.

 /@\O/S@+>\
^{ }[<X/ @/;
,\?/@\J^X\
'M~\$ $
UK/W%@]  /
D
?\{\/
0'A Y

My second reasonably complicated Fission program. :)

The input format is a bit weird. To support negative inputs, the first character is expected to be either + or - to indicate the sign. The second character's byte value is then the magnitude of the input (since Fission can't natively read decimal integers). So if you want 111 you'd pass it +o on STDIN. And if you want -56 you pass it -8. In place of + and - you can use any character with a lower or higher character code, respectively. This can be helpful to pass in something like -n (which your echo might treat as an argument) as, e.g., 0n.

Let's look at how we can find the negabinary representation of a positive number. We want to compute the number from least to most significant bit (we'll push those bits on a stack and print them all at the end to get them in the right order). The first digit is then just the parity of the number, and we integer-divide the number by 2 to continue processing. The next digit is now negative (with value -2) - but it should be noted that this bit will be set whenever the 2-bit would be set in a normal binary number. The only difference is that we need to counter the -2 with positive higher valued digits. So what we do is this:

  • We determine the parity again - this is the next negabit - and divide by 2 as before.
  • If that digit was a 1, we increment the remaining number by 1 in order to counter-act the negative bit (the difference between a negabit and a bit is once the value of the next more-significant bit).

A great simplification of the code results from noticing that conditionally adding one here is equivalent to rounding the number up when integer dividing (if the discarded bit was 1, we increment the integer-divided result by 1).

Then, the next bit is just a positive value again so we can determine it normally. That means we want a loop that computes two bits at a time, alternating between rounding up and rounding down for the remaining number, but we want to enter the loop in the middle so we start with rounding down.

How can we handle negative integers? The problem is that Fission can't really do arbitrary arithmetic on negative integers, because masses are always non-negative. So one would have to do something really complicated like working with the magnitude and keeping track of the sign somewhere else. However, the negabinary representation of a negative number can be computed based on a related positive number:

If n is negative, compute the negabinary representation of n/2 (rounded up) and append the parity of n.

This is exactly the first step of our two-bit loop. So all we need to do is start the loop at a different point if the sign is negative.

Most of the savings from the 173 original bytes came from these insights which allowed me to compress three parity checks and a two-section loop into a single loop with a single parity check.

This post will get too long if I explain all the code in detail, but I'll point out a few sections to give the rough layout of the control flow, and you can puzzle out the details with the Fission reference.

 /@\
^{ }[
,\?/
'
U
D
?

Starting from the D, this reads a sign bit into the energy and the magnitude into the mass of an atom that ends up in the [ (going right). This sign bit will alternate after each pass through the parity check and will determine whether we retain the rounded down or rounded up half of the loop input.

     /S@+>\
    [<X/ @/
 \  @\J^X\
 M  $ $
 K  %@]  /

This is the loop which computes the individual bits and feeds the correct half into the next iteration. The S and the J are used to create a copy of the right half based on the current sign bit, the Xs do the copying. The > in the top right corner computes the actual bit which is then sent to the stack K to be retrieved later. I think the layout of the top right corner is pretty nifty and definitely worth studying in detail if you're interested in Fission.

The % is a switch which feeds the number back into the loop as long as it's greater than 0.

    O


 M~\
 K/W%

 \{\/
0'A Y

Once the number reaches 0 it's reflected down instead. This starts another loop which retrieves the bits from the stack, adds them to the character code of 0 and prints them with O. The program terminates once the stack is empty, because the control atom will end up being pushed on the stack (and afterwards there are no more moving atoms left).


Task 5, Prelude, 219 179 96 bytes

Esolangs page for Prelude.

Stack Snippet interpreter for Prelude.

29+129+716705-7607-05-4759+705-14129+05-18705-29+719+05-1507-19+39+449+767549+03-68(67+^+^+^++!)

This started out as a standard hand-crafted fixed-output Prelude program with three voices. After some chat with Sp3000 I decided to try a single voice. It turned out that this worked quite well, because it's much easier to reuse older letters. Then Dennis gave me a few hints and I found the current version: the idea is push all the offsets from the letter h onto the stack of a single voice in reverse order, and then just print them one at a time in a loop. h is chosen because there is no h in the string (which is important - otherwise the 0 offset would terminate the loop) and because it minimises the encoding of the offsets in terms of two-digit and negative offsets.

The offset encoding was generated with this CJam script.


Task 8, Mathematica, 28 bytes

LongestCommonSequence@##==#&

Yay for built-ins. (Mathematica's naming is a bit weird here... LongestCommonSubsequence finds the longest common substring while LongestCommonSequence finds the longest common subsequence.)


Task 9, J, 1 byte

*

Same as the APL and K answers, but it seems no one has taken J yet.


Task 10, Retina, 67 60 bytes

GitHub repository for Retina.

(.*).
 ______  $1<LF>|      | $1<LF> ()--() ~$1
+`(.{9})1
$1$1
~$
<empty>

Each line goes in a separate file, and <LF> should be replaced with a newline character and <empty> should be an empty file. You could also put all of this in a single file, and use the -s option, but that does not allow embedding of newline characters in place of <LF> yet. You could emulate that by doing something like

echo -n "111" | ./Retina -s train.ret | ./Retina -e "<LF>" -e "\n"

As the above example shows, input is expected to be unary. The idea of the code is to create three copies of the unary input (minus 1), each with a copy of the corresponding line. Then we repeatedly duplicate the last nine characters in front of a 1 until all the 1s are gone, thereby repeating the lines as necessary. Finally, we remove the extraneous trailing ~.