title: First code golf decathlon

text:
# Question
Title: First code golf decathlon
### Tasks

All competitors try to solve the following list of 10 tasks:

1. Read a positive integer **n** from input and return the sum of the cubes of the first **n** non-negative integers.

For input `1`, this should return `0`.
2. Read a positive integer **n** from input and return a truthy value if and only if **n** is a Mersenne prime.
3. Read a non-empty list of **n** integers from input and return their median.

If **n** is even, use the lesser of the two middle values.

For example, the median of `[1 4 3 2]` is `2`.
4. Read an integer (positive, negative or 0), or a string representation in base 10 or unary, from input and return its digits in negabinary, without leading zeroes (with the exception of input 0).

The output can be formatted in any convenient way (digits, array, string, etc.).

5. Return `pneumonoultramicroscopicsilicovolcanoconiosis`.
6. Check the current date and return `Happy New Year!` if appropriate according to the Gregorian calendar.
7. Pseudo-randomly select 64 unique assigned code points from the Unicode block CJK Unified Ideographs Extension-A (U+3400 – U+4DB5) and return the string of the corresponding characters.

All possible strings should have the same probability of getting selected.
8. Read two strings of printable ASCII characters from input and return a truthy value if and only if the character of the first string form a subsequence of the second string.

For example, `abc`, `axbxc` should return truthy and `bac`, `axbxc` should return falsy.

9. Read a multidimensional, rectangular array of integers and an integer **n** from input and return the modified array with all integers multiplied by **n**.

10. Read a non-negative integer **n** from input and return a chain of **n** train wagons, as shown below.

Example output for **n = 3**:

```
 ______   ______   ______
|      | |      | |      |
 ()--() ~ ()--() ~ ()--()

```

The output may be surrounded by any amount of whitespace as long as it looks like in the example.

### Clarifications

* **0** is neither positive nor negative.
* Trailing whitespace is always permitted in the output.
* Several pieces of input may be read in any consistent, convenient order.

### Rules

1. **No answer may solve two different tasks in the same programming language.**1
2. For each individual task, standard rules apply.

In particular, you can submit programs or functions with the usual I/O defaults, but cannot take advantage of these loopholes.

Task 5 is essentially a challenge, so hardcoding the output is not only allowed but expected.
3. Only one answer per user should be posted, containing at most one solution for each of the tasks.

Please format your answer as in the following example:

```
## Task 1, Python, 42 bytes

    <code goes here>

Explanation, I/O, required Python version, etc. go here.

---

## Task 7, C, 42 bytes

    <code goes here>

Explanation, I/O, required compiler (flags), etc. go here.

```

### Scoring

1. For every task you solve, you get one point.

**This means that you don't have to solve *all* tasks to participate.**
2. If your solution for the task **n** is the shortest one in that programming language, you get an additional point.
3. If your solution for the task **n** is the shortest one of all programming languages, you get an additional point.
4. The bonus points will be awarded only once for each task-language combination and each task, respectively.

As usual, if two solutions have the same byte count, posting time is the tie breaker.

If somebody outgolfs you later, you lose the bonus point(s) the other answerer earns.
5. You can golf submission, add/remove languages from your answer or swap the languages used for two tasks.

Any time somebody edits his answer, all answers are rescored.
6. Once you change languages for a task, you forfeit seniority.2

The answer with the highest score wins.3

### Per-task leaderboard

```
<style>body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</style><script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><table class=answer-list><thead><tr><td>Task<td>Author<td>Language<td>Score<tbody id=answers></table></div><table style=display:none><tbody id=answer-template><tr><td>{{TASK}}<td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}</table><script>function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function process(){answers.forEach(function(e){var s=e.body_markdown.split("\n").filter(function(e){return"#"==e[0]});s.forEach(function(s){var r=s.match(NUMBER_REG)[0],t=(s.match(SIZE_REG)||[0])[0],a=s.match(LANGUAGE_REG)[1],n=e.owner.display_name;entries.push({task:r,user:n,language:a,size:t})})}),entries.sort(function(e,s){var r=e.task-s.task;return r?r:e.size-s.size});for(var e=0;e<entries.length;e++){var s=jQuery("#answer-template").html();s=s.replace("{{TASK}}",entries[e].task).replace("{{NAME}}",entries[e].user).replace("{{LANGUAGE}}",entries[e].language).replace("{{SIZE}}",entries[e].size),s=jQuery(s),jQuery("#answers").append(s)}}var QUESTION_ID=52152,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*.*?,\s*\[*([^,\]]+)/,entries=[];</script>
```

### Combined leaderboard (2015-07-30 20:00 UTC)

```
User / Task      1 2 3 4 5 6 7 8 9 A   TOTAL   Tie breaker (if any)

DLosc            2 2 3 2 2 2 2 3 2 2      22
Sp3000           2 2 2 2 2 3 2 2 2 2      21
Doorknob         2 2 2 2 2 2 2 2 2 2      20
mathmandan       2 2 2 2 2 2 2 2 2 2      20   Combined byte count.
MickyT           2 2 2 2 2 2 1 2 2 2      19
Alex A.          2 1 2 2 2 2 1 2 2 2      18
Jacob            2 2 2 2 2 1 0 0 0 2      13
alephalpha       2 2 2 0 2 2 0 0 2 0      12
Martin Büttner   2 0 0 2 2 0 0 2 2 2      12   Combined byte count.
kirbyfan64sos    1 2 2 0 2 X 0 2 0 3      12   Per-language wins.
Maltysen         3 0 0 0 3 2 1 X 2 0      11
plannapus        2 2 0 0 2 2 0 2 0 2      10
jimmy23013       0 0 2 3 0 0 3 2 0 0      10   Solved tasks.
Tom              0 3 0 0 2 2 0 X 3 0      10   Combined byte count.
FryAmTheEggman   1 0 2 0 2 0 2 0 2 0       9
Vioz-            1 0 2 2 2 2 0 0 0 0       9   Combined byte count.
Toby Speight     2 0 0 0 2 2 0 0 0 2       8
Ismael Miguel    0 0 0 0 2 2 0 0 0 2       6
Pulga            0 2 2 0 0 0 0 0 0 2       6   Combined byte count.
flawr            2 0 2 0 0 0 0 0 0 0       4
manatwork        2 0 0 0 0 2 0 0 0 0       4   Combined byte count.
TheNumberOne     1 0 0 0 2 0 0 0 0 0       3

```

Tasks marked with `X` are present but invalid.

The combined leaderboard has been constructed by hand. Please tell me if there are any errors.

---

1 Languages count as different if they are not different versions of the same language, so there's only one JavaScript, one Python, and one TI-BASIC, but C, C++, Octave and MATLAB are four different languages.

2 If you solve task **n** using language **L** in **x** bytes, somebody else solves the same task in the same language with the same byte count, you change to language **M** and roll back your edit, the other answerer will keep the bonus point.

3 The number of points earned from scoring rules 1, 2 and 3 (in that order), the combined byte count of all solved tasks (lower is better) and, finally, the vote tally (higher is better) serve as tiebreakers.

# Answer
> 5 votes
## Task 1, GolfScript, 8 bytes

```
~,{+}*.*

```

Same idea as Martin's CJam answer.

---

## Task 2, QBasic, ~~74~~ 71 bytes

```
INPUT a
r=a>1
FOR i=2 TO a-1
r=r*(a MOD i)
NEXT
?r*((a\2AND a)=a\2)

```

Tested on QB64 with syntax expansion turned off.1 The bulk of the program tests whether the given number `a` is prime by taking `a` mod every number 2\<=`i`\<`a` and multiplying the results. The result is that `r` is 0 if the number is not prime, and nonzero otherwise. The last line uses bitwise `AND` with integer division by 2 to check whether the binary representation of `a` is all ones, i.e. `a` is of the form 2n-1. Multiplying this by `r` gives 0 (false) if a number is not a Mersenne prime and some nonzero (truthy) value otherwise. `?` is a shortcut for `PRINT`.

The largest Mersenne prime I tested, 8191, gives a result of `1.#INF`--which is still truthy! (I checked with an `IF` statement to make sure.)

1 This doesn't change the semantics of the program. If you type the above code into the standard DOS QBasic, it will be autoformatted with extra spaces, but it will run exactly the same.

---

## Task 3, Pyth, 6 bytes

```
ehc2SQ

```

Reads a Python-style list from stdin. The main magic here is the `c`hop operator: given an int and a list, it splits the list into n pieces. So `c2SQ` chops the sorted input list in half. Conveniently, when the length is odd, the first half is the bigger one, so the median is always the last element of the first half. This is the `e`nd of the `h`ead of the chop results.

---

## Task 4, CJam, 26 bytes

```
ri{_2%z\_0>\-2/_3$+?}h;]W%

```

This could be shortened, I suspect.

Algorithm:

* Read integer.
* Do while value is not 0:
    + Take abs(i%2). This is the next digit (negabit?).
    + Divide i by -2.
    + Iff i was nonpositive, add abs(i%2) to the result. This is to correct a corner case: 3 goes to -1, but -3 should go to 2, not 1.
* Drop the superfluous 0, collect the stack into an array, reverse and print.

The fact that it's a do-while loop takes care of the 0 case.

---

## Task 5, Bash, 50 bytes

```
echo pneumonoultramicroscopicsilicovolcanoconiosis

```

Not much to explain.

---

## Task 6, Python, 78 bytes

```
from datetime import*
d=date.today()
if d.day<2>d.month:print"Happy New Year!"

```

Requires Python 2. Python's chaining inequality operators can be nicely exploited here.

---

## Task 7, ActionScript, 82 bytes

```
x=""
while(x.length<64){c=chr(13312+random(6582));if(x.indexOf(c)<0)x+=c}
trace(x)

```

ActionScript is a member of the ECMAScript family. This code requires ActionScript 2--much better for code golf because I get to use deprecated functions like `chr` instead of version 3's `String.fromCharCode`!

Output is to the console pane:

---

## Task 8, Pip, ~~9~~ 19 bytes

The regex solution didn't quite work, so here's one with string operations instead.

```
Fcab@>:o&:(b@?c)+1o

```

Github repository for Pip.

Takes the two strings as command-line args. When `a` is a subsequence, outputs a positive integer (truthy); otherwise, the result is nil (falsy), which produces no output.

Explanation:

```
                     Cmdline args -> a,b; o = 1 (implicit)
Fca                  For each character in a:
           b@?c      Find character's index in b (nil if not found)
          (    )+1   Add 1; all possible indices except nil are now truthy
       o&:           Logical AND with o
   b@>:              Slice b to everything at index o and afterward (Python b=b[o:])
                     (If c wasn't found, b becomes nil, but we don't care at that point)
                  o  Auto-print o

```

---

## Task 9, Prolog (SWI), 68 bytes

```
m(L,N,R):-L=[H|T],m(H,N,I),m(T,N,U),R=[I|U];L=[],R=[];R is L*N.

```

Prolog is not usually at all competitive in code golf, so I'm pretty happy with this solution.

Defines a predicate `m` with input parameters `L` for the list and `N` for the number and output parameter `R`. The definition of `m` is a triple disjunction:

* If `L` can be unified with `[H|T]`, it is a list with at least one item in it. Call `m` recursively on the head and tail of that list, and put the results together again into a new list which is unified with `R`.
* If `L` can be unified with `[]`, unify `R` with `[]` as well.
* Otherwise, `L` is assumed to be a number; `L*N` is calculated and assigned to `R`.

Example run using `swipl` on Ubuntu:

```
dlosc@dlosc:~/golf$ swipl -qs arrayMult.prolog
?- m([1,2,3],5,R).
R = [5, 10, 15] .

?- m([[3,4],[5,6]],3,R).
R = [[9, 12], [15, 18]] .

?- m([[[1,2],[3,4]],[[5,6],[7,8]]],2,R).
R = [[[2, 4], [6, 8]], [[10, 12], [14, 16]]] .

```

---

## Task 10, C, ~~114~~ ~~112~~ 106 bytes

```
#define F;printf("\n");for(i=0;i<c;i++)printf(
i;t(c){F" ______  ")F"|      | ")F" ()--() ~");putchar(8);}

```

Tested with `gcc` on Ubuntu. Defines a function `t` that takes an integer argument. Uses three `for` loops to output, greatly condensed via macro abuse. Using the backspace character to erase a trailing `~` results in a rather odd whitespace pattern, but `The output may be surrounded by any amount of whitespace as long as it looks like in the example.`

Example run of `t(3)`:

```
dlosc@dlosc:~/golf$ ./a.out

 ______   ______   ______
|      | |      | |      |
 ()--() ~ ()--() ~ ()--() dlosc@dlosc:~/golf$

```

# Answer
> 17 votes
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.

# Answer
> 15 votes
## 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.

# Answer
> 13 votes
## 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 `X`s 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 `1`s are gone, thereby repeating the lines as necessary. Finally, we remove the extraneous trailing `~`.

# Answer
> 10 votes
Eh, I'll start out with a couple I guess. First time golfing.

## Task 1, Python, ~~38~~ 21 bytes

```
lambda n:(n*n-n)**2/4

```

Sum a list of all the cubes up to x. Changed expression thanks to xnor

## Task 2, TI-Basic 89, 244 bytes

```
Func
If iPart(log(x+1)/log(2))=log(x+1)/log(2) Then
 Return log(x+1)/log(2)
Else
 Return 0
EndIf
EndFunc
Func
If isPrime(x)=false
 Return 0
If ipart(log(x+1)/log(2))=log(log(x+1)/log(2)) Then
 Return log(x+1)/log(2)
Else
 Return 0
EndIf
EndFunc

```

Not 100% certain on this one, will test when I find new batteries for my calculator. isPrime is a builtin, ipart is integer part (2.3 -\>2)

## Task 3, Perl, ~~45~~ 34 Bytes

```
@n=sort{$a-$b}@ARGV;print$n[$#n/2]

```

perl file 1 2 3 4 --\> 2. Saved a couple of bytes thanks to @nutki. Printed rather than saving to variable then printing variable.

## Task 4, Ruby, ~~43~~ 40 bytes

```
x=2863311530
p ((gets.to_i+x)^x).to_s(2)

```

At least it works in 1.9, don't know about 1.8. In binary, '10'\*16 (or 2863311530) plus a number, xor with that 10101010... is the negbinary. Outputs a string representation with quotes (3 -\> "111" rather than 3 -\> 111). Can't find math to write x in less characters.

## Task 5, Malbolge, ~~682~~ 354 bytes

```
D'``_]>n<|49ixTfR@sbq<(^J\ljY!DVf#/yb`vu)(xwpunsrk1Rngfkd*hgfe^]#a`BA]\[TxRQVOTSLpJOHlL.DhHA@d>C<`#?>7<54X8165.R2r0/(L,%k)"F&}${zy?`_uts9Zvo5slkji/glkdcb(fed]b[!B^WVUyYXQ9UNrLKPIHl/.JCBGFE>bBA@"!7[;{z276/.R2r0)(-&J$j('~D${"y?w_utyxq7Xtmlkji/gf,MLbgf_dc\"`BA]\UyYXWP8NMLpPIHGLEiIHGF(>C<A@9]7<;:3W7w5.-210/(L,%k#('~}C{"y?`_uts9wpXn4rkpoh.lNMiha'eGF\[`_^W{h

```

Test online here Think this is as short as it'll go. Golfed as much as I could. Saved 300 bytes, so whee?

## Task 6, bash, ~~62~~ ~~50~~ 40 bytes

```
[ `date +%j`=1 ]&&echo 'Happy New Year!'

```

Found out about %j from another post.

## Task 10, Befunge-98, 121 Bytes

```
>&:>1-:" ____"v
   |,k8: '"__"<
   >a,$:>1-v
      > |
>' 8k,^ #
^|':k4 '|':<
v ',*25$<
>,:1-: ")(--)("v
^," ~"_@#,k6" "<

```

Changed to befunge-98. Old was Befunge-93, ~~227 157~~ 147 bytes. Used Fungi, written in Haskell for testing. Used the "do multiple times k" and adding single characters to the stack with '. I have a feeling it can be golfed down to 110 or less, but I've spent far too much time on this already...

# Answer
> 9 votes
First thing: task 6 technically does **NOT** count; I uploaded unc under an hour ago. However, I *almost* uploaded it this morning, but decided to write a test suite first. Idiot.

So, anyway, here goes!

Note that most unc things are intentionally backwards, so `&&` really means `||` and such, which is why some operations look weird (e.g. using `-` to calculate the cube).

## Task 1, Haskell, 21 bytes

```
f n=sum$map(^3)[0..n]

```

## Task 2, Hy, 135 bytes

```
(import math)(fn[n](and(if(and(not(% n 2))(> n 2))false(all(genexpr(% n i)[i(->> n(math.sqrt)int inc(range 3))])))(->> n dec(& n)not)))

```

## Task 3, Dart, 37 bytes

My first Dart function!

```
f(l){l.sort();return l[l.length~/2];}

```

## Task 5, INTERCAL, 1047 bytes

```
DO ,1 <- #46
DO ,1SUB#1 <- #242
DO ,1SUB#2 <- #152
DO ,1SUB#3 <- #208
PLEASE DO ,1SUB#4 <- #248
DO ,1SUB#5 <- #248
DO ,1SUB#6 <- #192
PLEASE DO ,1SUB#7 <- #128
DO ,1SUB#8 <- #128
DO ,1SUB#9 <- #72
PLEASE DO ,1SUB#10 <- #120
DO ,1SUB#11 <- #8
DO ,1SUB#12 <- #224
PLEASE DO ,1SUB#13 <- #200
DO ,1SUB#14 <- #208
DO ,1SUB#15 <- #32
PLEASE DO ,1SUB#16 <- #208
DO ,1SUB#17 <- #120
DO ,1SUB#18 <- #88
PLEASE DO ,1SUB#19 <- #40
DO ,1SUB#20 <- #8
DO ,1SUB#21 <- #208
PLEASE DO ,1SUB#22 <- #232
DO ,1SUB#23 <- #120
DO ,1SUB#24 <- #208
PLEASE DO ,1SUB#25 <- #248
DO ,1SUB#26 <- #56
DO ,1SUB#27 <- #96
PLEASE DO ,1SUB#28 <- #160
DO ,1SUB#29 <- #208
DO ,1SUB#30 <- #208
PLEASE DO ,1SUB#31 <- #136
DO ,1SUB#32 <- #120
DO ,1SUB#33 <- #192
PLEASE DO ,1SUB#34 <- #112
DO ,1SUB#35 <- #64
DO ,1SUB#36 <- #16
PLEASE DO ,1SUB#37 <- #128
DO ,1SUB#38 <- #48
DO ,1SUB#39 <- #208
PLEASE DO ,1SUB#40 <- #128
DO ,1SUB#41 <- #224
DO ,1SUB#42 <- #160
PLEASE DO ,1SUB#43 <- #40
DO ,1SUB#44 <- #56
DO ,1SUB#45 <- #200
PLEASE DO ,1SUB#46 <- #126
PLEASE DO READ OUT ,1
DO GIVE UP

```

## Task 6, unc, 157 bytes

```
!include>=fgQVb%U<=
!include>=gVZR%U<=
false lRNe[]<<gVZR_g t:=gVZR[5]:volatile gZ m:=-YbPNYgVZR[&t]:for[#m%gZ_Zba||m%gZ_ZQNl!=6]chgf[L'uNccl ARj LRNe#']:>>

```

## Task 8, rs, 42 bytes

```
#
+#(.)(.*) .*?\1/\1#\2
.*# .*$/1
[^1]+/0

```

Live demo.

## Task 10, Pyth, 46 bytes

```
jb(j*d2m+\ *\_6Qjdm"|      |"Qj\~m" ()--() "Q)

```

Live demo.

# Answer
> 8 votes
## Task 1, APL, 7 bytes

```
+/3*⍨⍳⎕

```

You can try it online using ngn/apl, though it will work with any APL implementation that defaults to a 0 index origin.

This cubes each integer from 0 to the input (`⍳⎕`) -1 by commuting () the arguments to the power operator (`*`). The resulting vector is reduced by summing (`+/`) and a scalar is returned.

---

## Task 2, Julia, 42 bytes

```
n->(isprime(n)&&int(log2(n+1))==log2(n+1))

```

This creates an anonymous function that accepts as integer as input and returns a boolean. To call it, give it a name, e.g. `f=n->...`.

First we use Julia's built-in function `isprime` to check whether `n` is prime. If it is, we check that `log2(n+1)` is an integer. If so, `n` can be written as `2^k-1` for some `k`, and thus `n` is a Mersenne prime.

---

## Task 3, ELI, 19 bytes

```
{f:x[<x][~.0.5*#x]}

```

This creates a monad `f` that returns the median of the input vector.

Ungolfed + explanation:

```
{f:         // Define a function f
 x[<x]      // Sort the input vector
 [          // Select the element at index...
 ~.0.5*#x   // ceiling of 0.5 * length(input)
]}

```

Examples:

```
    f 1 2 3 4
2
    f ?.!20   // Apply f to 20 random integers in 1..20
4

```

---

## Task 4, Octave, 39 bytes

```
@(n,x=2863311530)dec2bin(bitxor(n+x,x))

```

This creates a function handle that accepts an integer as input and returns the associated negabinary string. To call it, give it a name, e.g. `f=@...`, and run with `feval(f, <input>)`.

You can try it online.

---

## Task 5, CJam, 47 bytes

```
"pneumonoultramicroscopicsilicovolcanoconiosis"

```

The string is simply printed to STDOUT. You can try it online if you feel so inclined.

---

## Task 6, Windows Batch, 46 bytes

```
if "%date:~4,5%"=="01/01" echo Happy New Year!

```

The variable `%date%` contains the current date in the form `Thu 06/25/2015`. We can select the month and day by getting the substring of length 5 after skipping the first 4 characters: `%date:~4,5%`. From there we just check if it's January 1st and say Happy New Year if it is.

---

## Task 7, Pyth, 26 bytes

```
=Gr13312 19895FNU64pC.(.SG

```

First we assign `G` to the range 13312 through 19894 inclusive. Then we loop 64 times, and at each iteration we shuffle `G` (`.SG`), remove and return the last element (`.(`), and print its character representation (`pC`).

You can try it online.

---

## Task 8, Ruby, 36 bytes

```
def f(a,b)!b.tr("^"+a,"")[a].nil?end

```

This defines a function `f` which accepts two strings `a` and `b`, where `a` is the string to find within `b`.

Everything but the characters in `a` are removed from `b` using `.tr()` and we check whether the result contains `a` exactly using `[]`. This will return `nil` if the string isn't found, so we can get a boolean value by using `!` with `.nil?`.

---

## Task 9, R, 16 bytes

```
function(x,n)n*x

```

This creates an unnamed function object that accepts any kind of array or matrix `x` and an integer `n` and multiplies each element of `x` by `n`. If you'd like, you can try it online.

---

## Task 10, Python 3, 92 bytes

```
n=int(input())
l="\n"
w=" ()--() "
print(" ______  "*n+l+"|      | "*n+l+(w+"~")*(n-1)+w)

```

Pretty straightforward. You can try it online.

# Answer
> 7 votes
# Task 1, \>\<\>, 10 + 3 = 13 bytes

```
::*-:*4,n;

```

Run this using the official Python interpreter using the `-v` flag (at a cost of 3 bytes). This squares the quantity `(n - n*n)` and divides by `4`, which of course is equivalent to squaring `(n*n - n)` and dividing by `4`.

# Task 2, GAP, 63 62 bytes

```
b:=function(m)return[2]=AsSet(Factors(m+1))and IsPrime(m);end;

```

(Saved a space by writing the equality the other way around.)

# Task 3, R, 43 39 bytes

```
f=function(v)sort(v,d=T)[length(v)%/%2]

```

Thanks to Plannapus for the nice improvement!

# Task 4, Piet, 155 135 115 5\*19 = 95 codels

Test using this online interpreter, with codel size 13. Or use your preferred interpreter--let me know if you have one you like!

Making it output `0` instead of the empty string for input `0` was inconvenient. I used an if-then near the beginning to take care of this case; then a while-loop to calculate the digits in the nonzero case, and finally another while-loop at the end to output the digits from the stack.

Many thanks to Sp3000 for some very helpful comments, which helped me to save some codels!

# Task 5, Lua, 52 bytes

```
print"pneumonoultramicroscopicsilicovolcanoconiosis"

```

You can try it here.

# Task 6, LaTeX, 157 139 136 127 128 bytes

```
\documentclass{book}\begin{document}\count1=\day\multiply\count1 by\month
\ifcase\count1\or Happy New Year!\else~\fi\end{document}

```

If the product of the day and the month is `1`, print the message; otherwise, nothing. (New Year's Day is particularly convenient for this design: since the output we're looking for is `1`, we only need one `or` statement. The `n`th `or` statement specifies behavior for the value `n`.)

Note: my previous version was missing the line return, which was a mistake. (I did try to test this function, but to really test it properly might take a while...)

My original version used the `calc` package, which was much more convenient than my current version. Something to keep in mind for "real life"!

# Task 7, Ruby, 62 bytes

```
for r in Array(13312..19893).sample(64)
puts [r].pack('U*')end

```

# Task 8, JavaScript, 78 bytes

```
h=function(l,m){u=1+m.indexOf(l[0]);return(!l||u&&h(l.substr(1),m.substr(u)))}

```

Recursive solution, testing whether `l` is a substring of `m`. If `l` is empty, then the `!l` results in `true` and the function terminates. (In this case, `l[0]` is undefined, but JavaScript is OK with that.) Otherwise, it looks for the first instance of `l[0]` in `m`. If it doesn't find one, then `m.indexOf(l[0])` results in `-1` and so `u` results in `0` and the function terminates.

Otherwise, it strips off the first entry of `l` and the first `u` entries of `m` and continues checking.

# Task 9, Python, 72 60 bytes

```
def i(a,n):
 try:return[i(c,n)for c in a]
 except:return n*a

```

Drills down to the "lowest level", where `a` isn't a list anymore, just an integer, then carries out the multiplication.

Many thanks to Dennis for saving me 12 bytes!

# Task 10, Groovy, 81 bytes

```
def j(n){(' ------  '*n+'\n'+'|      | '*n+'\n'+' ()--() ~'*n).substring(0,27*n)}

```

Try it here. I originally tried to implement something like Python's `.join()` method for strings, which puts strings together with a particular "linking string" (like the linkages between train cars). But that cost a lot more than it saved.

*I hope I haven't run afoul of any conventions for acceptable answers in these various languages, but please let me know if I have.*

**Thank you to Dennis for a fantastic challenge!**

# Answer
> 6 votes
## Task 1, Pyth, 5 bytes

```
s^R3Q

```

Takes number from stdin. Thanks @Jakube for pointing out the useless `U`.

## Task 6, javascript, 56 bytes

```
if(Date().slice(4,10)=="Jan 01")alert("Happy New Year!")

```

## Task 7, CJam, 16 bytes

```
6581,mr64<'㐀f+

```

Generates range, shuffles, picks first 64, and maps addition of start value and converting to character. 14 chars, 16 bytes.

## Task 8, Octave, 23 bytes

```
@(x,y)intersect(x,y)==x

```

Defines anonymous function.

## Task 5, PHP, 45 bytes

```
pneumonoultramicroscopicsilicovolcanoconiosis

```

No compression, just prints.

## Task 9, APL 1 byte

```
 ×

```

The same as the K answer.

# Answer
> 6 votes
## Task 1, R, ~~21~~ 19 bytes

```
sum((1:scan()-1)^3)

```

Fairly straight forward. Input from STDIN.

## Task 2, Perl, ~~40~~ 66 bytes

```
$a=log(<>+1)/log(2)+1;print$a==int($a)&&(1x$a)!~/^1?$|^(11+?)\1+$/

```

Added a prime checker (Abigails prime number checker regex)

## Task 3, PARI/GP, ~~24~~ 22 bytes

```
m(v)=vecsort(v)[#v\2];

```

First time I touched this. Might have to learn a bit more of it.

## Task 4, T-SQL, 235 bytes

```
CREATE FUNCTION D(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT @/-2+(IIF(@%-2<0,1,0))D,CAST(ABS(@%-2) AS VARCHAR(MAX))M UNION ALL SELECT D/-2+(IIF(D%-2<0,1,0)),CAST(ABS(D%-2)AS VARCHAR(MAX))+M FROM R WHERE D<>0)SELECT M FROM R WHERE D=0

```

Inline table function using recursive CTE. Very large, but fun to do.

To use

```
SELECT * FROM D(18)
M
------
10110

```

## Task 5, GAP, 48 bytes

```
"pneumonoultramicroscopicsilicovolcanoconiosis";

```

## Task 6, Excel, ~~51~~ 48 bytes

```
=IF(TEXT(NOW(),"md")="11","Happy New Year!","")

```

Thanks to @Bond for the 3 bytes.

## Task 7, Python 2.6, ~~98~~ ~~93~~ 85 bytes

```
from random import*
l=range(13312,19893)
shuffle(l)
print ''.join(map(unichr,l[:64]))

```

This is the first time I've tried to do anything in Python, so could be lots better. Thanks @Dennis and @Jacob for the great tips

## Task 8, TCL, 57 bytes

```
proc m {a b} {string match [regsub -all (.) $a *\\1]* $b}

```

Shame that removing whitespace kills this

## Task 9, Pike, 53 bytes

```
mixed m(array(array(int))a,int n){return(a[*])[*]*n;}

```

A function that returns the multiplied array

## Task 10, Powershell, 88 bytes

```
Function t($n){Foreach($s in "  ______ "," |      |","~ ()--() "){($s*$n).Substring(1)}}

```

A Powershell function. I think I can shortened it a bit, but here it is at the moment.

And finally finished :)

# Answer
> 4 votes
# Task 2, J, 10 bytes

```
1&p:*/@,#:

```

Prepends a boolean 0 or 1 if the input is prime to its binary representation, then takes the product. Works on the current version of J.

---

# Task 5, HTML, 45 bytes

```
pneumonoultramicroscopicsilicovolcanoconiosis

```

---

# Task 6, fish, 53 bytes

```
test 0101 = (date '+%d%m');and echo 'Happy New Year!'

```

Based on the bash answer.

---

# Task 8, APL, 12 bytes

```
{(⍳⍴⍺)≡⍋⍵⍳⍺}

```

This is a function expression. It compares the order of characters found in the larger string with what would be expected if they were sorted.

---

# Task 9, K, 1 byte

```
*

```

Should work in any version. Arithmetic operations distribute over arrays.

# Answer
> 4 votes
## Task 1, Ruby, 40 bytes

```
def f n;(0..n-1).inject{|a,b|a+b**3};end

```

First time ever writing anything in Ruby. Tested with ruby 1.8.7.

---

## Task 2, R, 50 bytes

```
n=scan();p=log(n+1,2);!p%%1&sum(!n%%2:n,!p%%2:p)<3

```

Computes `p`, check if it is an integer, and if n and p are primes.

---

## Task 5, PostgreSQL, 54 bytes

```
SELECT'pneumonoultramicroscopicsilicovolcanoconiosis';

```

---

## Task 6, Lua, 55 bytes

```
print(os.date("%j")=="001" and "Happy New Year!" or "")

```

---

## Task 8, Python, 65 bytes

```
import re;f=lambda s,S:bool(re.search(re.sub(r'(.)',r'\1.*',s),S))

```

Usage:

```
>>> import re;f=lambda s,S:bool(re.search(re.sub(r'(.)',r'\1.*',s),S))
>>> f('abc','axbxcx')
True
>>> f('bac','axbxcx')
False
>>> f('abc','axdxcx')
False
>>> f('abc','abc')
True

```

---

## Task 10, Julia, 73 bytes

```
f(n)=print(" ______  "^n*"\n"*"|      | "^n*"\n"*(" ()--() ~"^n)[1:9n-1])

```

Thanks to @AlexA. for helping shortening this code! Example of outputs:

```
julia> f(0)

julia> f(1)
 ______
|      |
 ()--()

julia> f(2)
 ______   ______
|      | |      |
 ()--() ~ ()--()

julia> f(3)
 ______   ______   ______
|      | |      | |      |
 ()--() ~ ()--() ~ ()--()

```

# Answer
> 3 votes
## Task 1, Haskell, 17 bytes

```
f x=(x*(x-1)/2)^2

```

---

## Task 2, Mathematica, 30 bytes

```
PrimeQ@#&&Mod[Log2[#+1],1]==0&

```

---

## Task 3, JavaScript, 46 bytes

```
function(x){return x.sort()[0|(x.length-1)/2]}

```

---

## Task 5, MATLAB, 47 bytes

```
'pneumonoultramicroscopicsilicovolcanoconiosis'

```

---

## Task 6, Ruby, 56 bytes

```
print Time.now.to_s[5,5]=="01-01"?"Happy New Year!":""

```

---

## Task 7, Python, 106 bytes (indenting with `\t`)

```
from random import*
s=''
while len(s)<64:
    c=unichr(randint(0x3400,0x4DB5))
    if c not in s:
        s+=c
print s

```

Note that straightforward usage of `list(set(s))` does **not** work here as this will cause a non-uniform probability distribution in the space of **all possible strings** due to re-ordering of list members.

---

# Answer
> 3 votes
## Task 1, Python, 35 Bytes

```
lambda x:sum(_**3for _ in range(x))

```

## Task 3, CJam, 9 Bytes

```
q~$_,(2/=

```

## Task 4, JavaScript, ~~55~~ 53 Bytes

```
function(n){s=0xAAAAAAAA;return((n+s)^s).toString(2)}

```

## Task 5, Pyth, 46 Bytes

```
"pneumonoultramicroscopicsilicovolcanoconiosis

```

## Task 6, C#, 65 Bytes

```
string c(){return DateTime.Now.DayOfYear<2?"Happy New Year!":"";}

```

# Answer
> 3 votes
## Task 1, Haskell, 15 bytes

```
f n=(n*n-n)^2/4

```

## Task 2, Julia, 28 bytes

```
n->(isprime(n)&&ispow2(n+1))

```

## Task 3, Octave, 30 bytes

```
@(x)sort(x)(ceil(length(x)/2))

```

## Task 5, Yacas, 45 bytes

```
pneumonoultramicroscopicsilicovolcanoconiosis

```

## Task 6, Mathematica, 46 bytes

```
If[DateList[][[{2,3}]]=={1,1},Happy New Year!]

```

## Task 9, PARI/GP, 10 bytes

```
(n,a)->n*a

```

# Answer
> 3 votes
## Task 2, x86 masm, 40 bytes

```
C7 45 FC FF FF 07 00 B9
00 00 00 00 B8 02 00 00
00 D3 E0 3B 45 FC 7D 03
41 EB F1 B8 02 00 00 00
D3 E0 48 3B 45 FC 75 13

```

(excluding header, MessageBox, etc - only relevant bytes)

```
include     \masm32\include\user32.inc
includelib  \masm32\lib\user32.lib

.data
    ClassName   db "Mersenne Prime Found",0
.data?

.code
start proc
    LOCAL IsMersenne: DWORD
    mov IsMersenne, 524287 ; put number to test in this input
    mov ecx, 0
l00p:
    mov eax, 2
    shl eax, cl
    cmp eax, IsMersenne
    jge br3ak
    inc ecx
    jmp l00p
br3ak:
    mov eax,2
    shl eax, cl
    dec eax
    cmp eax, IsMersenne
    jnz n0pr1me
    invoke MessageBox, 0, addr ClassName, addr ClassName, 40h
n0pr1me:
    ret
start endp
end start

```

---

## Task 3, C, 136 bytes

```
#include<stdio.h>
int C(void*A,void*B){return(*(int*)A-*(int*)B);}
main(){int S=4;int A[]={3,1,2,4};qsort(A,S,4,C);printf("%i",A[((S&1)?S:S-1)/2]);}

```

Compile using `gcc -o Prime main.c`

---

## Task 10, C++, 478 bytes

```
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void D(int Z){int L=9,i,X=0;const char*A=" ______  ";const char*B="|      | ";const char* C = " ()--() ~ ";char*P=(char*)malloc(27*Z+5);for(i=0;i<Z-1;i++){if(!i){memcpy(P,A,L);X+=L;}memcpy(&P[X],A,L);X+=L;if(i==Z-2){memcpy(&P[X],"\n",1);X++;}}for(i=0;i<Z;i++){memcpy(&P[X],B,L);X+=L;if(i==Z-1){memcpy(&P[X],"\n",1);X++;}}for(i=0;i<Z;i++){memcpy(&P[X],C,L);X+=L;if(i==Z-1)P[X-1]='\0';}printf("%s\n",P);free(P);}
main(){D(15);}

```

Compile using `g++ -o Trucks main.cpp`

C & C++ can be shortened but it'd add compiler error. Don't know the exact rules so I tried to leave code w/no compiler errors.

# Answer
> 3 votes
## Task 3, Clip, 13 bytes

```
gHk[tivt}l`sk

```

Another version:

```
gHkci`v``l`sk

```

The ``` seemed to cost too much.

## Task 4, KSFTgolf, 16 bytes

```
g:]2%:)-2/:;xgpc

```

The interpreter is here. I'm not sure what I am doing... It will print the negabinary and then crash.

There is a bug in the interpreter. Or I'll be able to golf it down to 12 bytes using built-in base conversion (but it only work with positive integers):

```
2*02-ba'Z=;x

```

Original CJam version:

```
qi{_1&_@^-2/}h;]W%

```

I tried Pip, Ostrich, Clip and Burlesque to find out if there is an esolang with built-in negabinary. None of them worked. KSFTgolf used `numpy`, which seemed to have some convienent weird behavior when the base is negative. But it's not easy to make it work with non-positive numbers.

## Task 7, CJam, 15 bytes

```
'䶶,DAm<>mr64<

```

## Task 8, APL, 21 bytes

```
∨/↑{⍺∧0,2∧/∨\⍵}/⌽⍞=↓⍞

```

Try it online.

# Answer
> 2 votes
## Task 1, Cjam, 7 bytes

```
q~,:+_*

```

Edit: Just noticed martin posted this before me. I'll try something else...

## Task 3, Python, 30 bytes

```
lambda l:sorted(l)[~-len(l)/2]

```

Python 2.

## Task 5, ///, 45 bytes

```
pneumonoultramicroscopicsilicovolcanoconiosis

```

/// will just echo something without any `/` characters.

## Task 7, Pyth, 19 bytes

```
s>64.SmC+13312d6582

```

Program. Please tell me if I mucked up the maths. Try it here

## Task 9, Octave, 9 bytes

```
@(a,n)a*n

```

Anonymous function handle. Octave automatically does this with matrix * scalar.

# Answer
> 2 votes
## Task 1, jq, 24 bytes

```
[range(1;.)|.*.*.]|add+0

```

## Task 6, PostgreSQL, 54 bytes

```
select'Happy New Year!'where'001'=to_char(now(),'DDD')

```

# Answer
> 2 votes
I haven't found time to attempt them all, but here's a start

# Task 1, dc, 8 bytes

```
d1+*d*4/

```

Input and output to top of stack, as per `dc` convention.

# Task 5, Emacs Lisp, 46 bytes

```
'pneumonoultramicroscopicsilicovolcanoconiosis

```

Abuse of the rules:

```
grep 'pn.*v' /usr/*/*/brit*-large

```

The best I could manage by unpacking from compressed form was 55, in Perl:

```
unpack("H45",'uïFVóÙ¤¼g°0Æö<¥le°°')=~y/0-9bdf/i-v/r

```

(non-printable chars above get garbled by SE, but as it's not actually my answer, I'm not fixing it)

# Task 6, SQL, 54 bytes

```
SELECT IF(now()LIKE'%-01-0_%','Happy New Year!','Hi');

```

I consider the first ten days of January to be 'appropriate' days for this greeting, but you can adjust to taste. The `now() LIKE` construct works out shorter than extracting day-of-year with `DATE_FORMAT(now(),'%j')`.

# Task 10, sed, 58 bytes

```
s/./ ()--() ~/g;s/.$//;h;y/()-~/___ /;p;g;y/ ()-~/|    /;G

```

Input in unary.

# Answer
> 1 votes
## Task 1, CJam, 10 bytes

```
li,{3#}%:+

```

Try Here

## Task 5, Retina, 46 bytes

```
<empty>
pneumonoultramicroscopicsilicovolcanoconiosis

```

# Answer
> 1 votes
# Task 5, MarioGolf, 50 bytes

This was a language I've developed for some time.

The current version has enough functionality to allow to run this challenge.

```
Y|<pneumonoultramicroscopicsilicovolcanoconiosis|O

```

You can try it online on http://htmlpreview.github.io/?https://raw.githubusercontent.com/ismael-miguel/mariogolf/master/js/testpage.html#c:Y|\<pneumonoultramicroscopicsilicovolcanoconiosis|O

Currently, the development is stopped and the implementation is incomplete.

The latest commit was on 13th March 2015.

# Task 6, PHP, 37 bytes

This one is really easy, and fun!

```
<?=date(jn)==11?'Happy New Year!':'';

```

# Task 10, Javascript, 121 byes

Yeah, not so golfed...

But it does the job!

```
console.log((' ______  '.repeat(i=prompt()))+'\n'+('|      | '.repeat(i))+'\n'+(' ()--() ~'.repeat(i).replace(/~$/,'')));

```

Try it:

```
//Required to show the console messages on the document
console._RELAY_TO_DOC = true;

console.log((' ______  '.repeat(i=prompt()))+'\n '+('|      | '.repeat(i))+'\n '+(' ()--() ~'.repeat(i).replace(/~$/,'')));
```

```

```

The code won't display well in the stack snippet due to it starting with `"` in the output. Adicional spaces were added to compensate it.

The original code can be executed on Chrome's console without any problem, and the output will be the expected.

# Answer
> 1 votes
# Task 1, Octave, 15 bytes

```
@(n)(n^2-n)^2/4

```

EDIT: I thought I added this but it seems I forgot to save: This uses the fact that `sum(1^3+2^3+3^3+...+n^3) = sum(1+2+3+...+n)^2 = [n*(n+1)/2]^2`

# Task 3, Javascript, 24 bytes

```
x=>x.sort()[x.length>>1]

```

# Answer
> 1 votes
Okay, let's get the easy stuff done first:

## Task 5, ASP, 45 bytes

```
pneumonoultramicroscopicsilicovolcanoconiosis

```

## Task 6, JavaScript, 46 bytes

```
/an 01/.test(Date())&&alert("Happy New Year!")

```

# Answer
> 1 votes
# Task 1, VBA, 126 bytes

```
Function f(n As Integer)
    Dim i As Integer
    For i = 0 To n - 1
        f = f + i ^ 3
        Next i
End Function

```

I haven't got a clue how to golf in VBA. I didn't type a single space, VBA automatically insert whitespaces. `=f(5)` in a cell in Excel will display 100.

# Task 2, Octave, 32 Bytes

```
@(n)isprime(n)&~mod(log2(n+1),1)

```

# Task 5, Golfscript, 47 bytes

```
"pneumonoultramicroscopicsilicovolcanoconiosis"

```

# Task 9, MATLAB, 9 bytes

```
@(A,n)A*n

```

Well, it's a start...

---
Tags: code-challenge, string, ascii-art, array, multiple-holes
---


title: It's super effective!

text:
# Question
Title: It's super effective!
In Pokémon there are 18 types:

```
Normal    Fighting  Flying  Poison  Ground  Rock
Bug       Ghost     Steel   Fire    Water   Grass
Electric  Psychic   Ice     Dragon  Dark    Fairy

```

A Pokémon can have single or dual typing. For example, Pikachu is `Electric`, and Tyranitar is `Rock/Dark`. The order of the types does not matter. A Pokémon can't have the same type twice. An attacking move has exactly one of the above 18 types.

* Some Pokémon types are weak to a certain type of attack. For example, a `Fire` Pokémon is weak against `Water` attacks. This gives a damage multiplier of 2.
* Some Pokémon types are resistant to a certain type of attack. For example, a `Rock` Pokémon is resistant against a `Normal` attack. This gives a damage multiplier of 0.5.
* Some Pokémon types are immune to a certain type of attack. For example, a `Flying` Pokémon is immune against a `Ground` attack. This gives a damage multiplier of 0.

A pokemon can be doubly weak, doubly resistant or any other combination against an attacking type. Multiply the multipliers to get a total effectiveness.

Write a program or function that given a move type and a Pokémon typing outputs the total damage multiplier of the attack. **A Pokémon typing is always written either as `A` or `A/B`, where `A` and `B` are distinct types from the list above. You must accept the Pokémon typing in this format.** Other than this restriction you may take input in any reasonable manner. An example input format that acceptable is:

```
"Ice", "Dragon/Flying"

```

But this is unacceptable:

```
["Ice", ["Dragon", "Flying"]]

```

Your output must be exactly one of the following strings, followed by an optional trailing newline:

```
0x    0.25x    0.5x    1x    2x    4x

```

# Examples

```
Ground, Fire -> 2x
Normal, Rock/Dragon -> 0.5x
Fighting, Ghost/Steel -> 0x
Steel, Water/Steel -> 0.25x
Ice, Dragon/Flying -> 4x
Water, Ground/Water -> 1x
Ghost, Ghost -> 2x

```

# Type effectiveness

For a human-friendly type chart I'd like to refer you to Gamepedia. To make the golfing process a bit faster I'll give you a compressed computer-friendly matrix of effectiveness. Divide every number by two to get the true multiplier (1 -\> 0.5, 4 -\> 2):

```
              Defending type
               (same order)

   Normal   222221201222222222
   Fighting 421124104222214241
A  Flying   242221421224122222
t  Poison   222111210224222224
t  Ground   220424124421422222
a  Rock     214212421422224222
c  Bug      211122211124242241
k  Ghost    022222242222242212
i  Steel    222224221112124224
n  Fire     222221424114224122
g  Water    222244222411222122
   Grass    221144121141222122
T  Electric 224202222241122122
y  Psychic  242422221222212202
p  Ice      224242221114221422
e  Dragon   222222221222222420
   Dark     212222242222242211
   Fairy    242122221122222442

```

---

Shortest code in bytes wins.

# Answer
> 16 votes
# Pyth - ~~246~~ ~~245~~ 188 bytes

Encodes the matrix with base compression, will probably use modular indexing/hashing for the matrix indices but right now I haven't done anything fancy with those.

```
Lxc"NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"3<b3.F"{:g}x"*Fm@@c19cR2KXjC"
©ªªå´êÛ©æ¶ª©Y+ªº;oªnz®©Z»*«ªºj«¥fëª×ª¯«Z¥ö]©ªâªÖ»ªj*î¥zzªªj«ªº«¥¹ªZ«ë¥ª¾"4]3]4yzydcw\/

```

Test Suite.

# Answer
> 17 votes
# Java, ~~663 639~~ 582 bytes

```
String f(String...a){float d=1;for(String B:a[1].split("/"))d*=("222221201222222222421124104222214241242221421224122222222111210224222224220424124421422222214212421422224222211122211124242241022222242222242212222224221112124224222221424114224122222244222411222122221144121141222122224202222241122122242422221222212202224242221114221422222222221222222420212222242222242211242122221122222442".charAt(g(a[0])*18+g(B))-48)*.5;return(d+"x").replace(".0","");}int g(String a){int i=0;for(;i<18;i++)if(a.contains("N,gh,ly,oi,ou,ck,B,ho,S,re,W,G,E,P,I,g,k,y".split(",")[i]))break;return i;}

```

There's a simple lookup table that takes much of the room. It just finds the correct types and multiplies it out. Call it like this:

```
f("Water","Ground/Fire")

```

With some line breaks it looks like this:

```
String f(String...a){
    float d=1;
    for(String B:a[1].split("/"))
        d*=("222221201222222222421124104222214241242221421224122222222111210224222224220424124421422222214212421422224222211122211124242241022222242222242212222224221112124224222221424114224122222244222411222122221144121141222122224202222241122122242422221222212202224242221114221422222222221222222420212222242222242211242122221122222442"
                .charAt(g(a[0])*18+g(B))-48)*.5;
    return(d+"x").replace(".0","");
}

int g(String a){
    int i=0;
    for(;i<18;i++)
        if(a.contains("N,gh,ly,oi,ou,ck,B,ho,S,re,W,G,E,P,I,g,k,y".split(",")[i]))
            break;
    return i;
}

```

# Answer
> 9 votes
## JavaScript (ES6), 287

I haven't seen a good compression of the types, so here's one.

```
(a,b)=>b.split('/').reduce((j,p)=>j*[0,.5,1,2][parseInt("kjwhcgnj2xd6elihtlneemw82duxijsazl3sh4iz5akjmlmsqds06xf1sbb8d0rl1nu7a2kjwi3mykjwlbpmk1up4mzl1iuenedor0bdmkjwmpk6rhcg4h3en3pew5".substr((g=x=>[..."BWSEIRNulkcDPotyeG"].findIndex(c=>x.match(c)))(a)*7,7),36).toString(4)[g(p)]],1)+'x'

```

Ungolfed:

```
(a,b)=>{
  // keys is a list of letters found in the types of attacks/defenses
  keys = [..."BWSEIRNulkcDPotyeG"];

  // getIndex is a single case statement.
  // it checks each of keys, one-by-one, falling through until we've found the proper index
  getIndex=x=>keys.findIndex(c=>x.match(c));

  // encodedValues is a list, indexed by `keys`, where each value is 7-characters.
  encodedValues = "kjwhcgnj2xd6elihtlneemw82duxijsazl3sh4iz5akjmlmsqds06xf1sbb8d0rl1nu7a2kjwi3mykjwlbpmk1up4mzl1iuenedor0bdmkjwmpk6rhcg4h3en3pew5";

  // the 7-character value (e.g., B=0="kjwhcgn", W=1="j2xd6el") were created by
  // turning base4 values into base36, so let's turn this back into a string the same way
  valuesForAttack = parseInt(encodedValues.substr(getIndex(a)*7,7),36).toString(4);

  // valuesForAttack is indexed by defenseType.  The value will be 0..3, depending on the multiplier

  // let's get an array of the multipliers and reduce...
  multiplier = b.split('/').reduce((oldMultiplier,defenseType)=>oldMultiplier * [0,.5,1,2][valuesForAttack[getIndex(defenseType)]],1);

  return multiplier+'x';
}

```

Oh, and here's my chart (keeping in mind it's ordered so that a letter won't match any words listed below it):

```
"Bug" => "B",
"Water" => "W",
"Steel" => "S",
"Electric" => "E",
"Ice" => "I",
"Rock" => "R",
"Normal" => "N",
"Ground" => "u",
"Flying" => "l",
"Dark" => "k",
"Psychic" => "c",
"Dragon" => "D",
"Poison" => "P",
"Ghost" => "o",
"Fighting" => "t",
"Fairy" => "y",
"Fire" => "e",
"Grass" => "G"

```

# Answer
> 9 votes
# Pikalang, 868068 bytes

This was just too good of an idea to skip. (Thanks, mbomb007.)

It's basically a sub-optimal lookup table. I first encode each type as

```
((first_char + second_char * 2 + third_char * 3) mod 256) - 0x3c

```

This results in unique representations for each type. The empty type (when the defending pokemon has only a single type) is encoded as `0x00`.

After that I just use a mess of `if-else` equivalents to check all the ~5800 combinations.

## Code

Stack Exchange didn't allow me to post the code as a whole, so here's it gzipped + base64'd.

```
[encoded data, 13092 characters]

```

## Example

Apparently the official Pikalang interpreter is not ready yet, but since it's a trivial Brainfuck substitution, I tested it using a Brainfuck interpreter.

```
$ base64 -d supereff.pokeball.gz.b64 > supereff.pokeball.gz
$ gunzip supereff.pokeball.gz
$ pikalang supereff.pokeball
Normal
Rock/Dragon
0.5x

```

Input is newline-separated and requires an additional trailing newline.

The program uses the memory location -1, so if your interpreter disallows going off the left side of the tape, prepend the code with a `pipi` or a `>` (for Pikalang and Brainfuck, respectively).

# Brainfuck, 193708

Here's the same program in Brainfuck (also gzipped + base64'd).

```
[encoded data, 6124 characters]

```

The program contains four parts:

1. The input. Reading the types and calculating their identifiers.
2. The text generation. Generating strings for each of the possible outputs.
3. The lookup table. This part was computer-generated (see below). Moves the pointer to the correct result.
4. The output. Just printing the result.

## Main program structure

```
,>,[-<++>],[-<+++>] read first type id
++++++[-<---------->] subtract 3c
+[,----------] skip until newline
>,>,[-<++>],[-<+++>] read second type id
++++++[-<---------->] subtract 3c
>- set @LOOPFLAG@ to get into loop
[
 >-< set @CHARFLAG@
 <,---------- get character; newline is 00 slash is 25
 [ was not newline
  ------------------------------------- slash is now 00
  [ was not slash
   >>+<< reset @CHARFLAG@
   [-] clear character
  ]
 ]
 >>[ was newline or slash (@CHARFLAG@ set)
  <+>+ reset @LOOPFLAG@ and @CHARFLAG@
 ]<
]
,>,[-<++>],[-<+++>] read third type id
<[->+>+<<]>[-<+>] copy third to @CHARFLAG@
>[ if @CHARFLAG@ is set
 [-] clear @CHARFLAG@
 <++++++[-<---------->]> subtract 3c from third
]<
++++++++[- do 8 times
 >++++++ put a 0 here
 >+++++++++++++++ put an x here
 >>++++++ put a 0 here
 >++++++ put a 0 here
 >++++++ put a 0 here
 >+++++++ put a 8 here
 >+++++++++++++++ put an x here
 >>++++++ put a 0 here
 >++++++ put a 0 here
 >+++++++ put a 8 here
 >+++++++++++++++ put an x here
 >>++++++ put a 0 here
 >+++++++++++++++ put an x here
 >>++++++ put a 0 here
 >+++++++++++++++ put an x here
 >>++++++ put a 0 here
 >+++++++++++++++ put an x here
 <<<<<<<<<<<<<<<<<<<<<< go back
]
>>>>>-- change 0 to dot
>++ change 0 to 2
>--- change 8 to 5
>>>>-- change 0 to dot
>--- change 8 to 5
>>>+ change 0 to 1
>>>++ change 0 to 2
>>>++++ change 0 to 4
<<<<<<<<<<<<<<<<<<<<<< go back
(lookup table here)
>[.>] print result

```

Here's the script that generates the lookup table:

```
typemap = [[int(value, 16), name] for value, name in [
    ["00", "(Nothing)"],
    ["02", "Ice"],
    ["07", "Fairy"],
    ["0f", "Dragon"],
    ["10", "Electric"],
    ["11", "Fighting"],
    ["12", "Grass"],
    ["1d", "Rock"],
    ["20", "Dark"],
    ["25", "Bug"],
    ["28", "Ghost"],
    ["2d", "Poison"],
    ["2e", "Steel"],
    ["32", "Fire"],
    ["39", "Water"],
    ["3c", "Ground"],
    ["46", "Normal"],
    ["4d", "Flying"],
    ["65", "Psychic"]
]]
multipliers = {
    0: 5,
    0.25: 8,
    0.5: 14,
    1: 19,
    2: 22,
    4: 25
}
types = [
    "Normal", "Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel",
    "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark", "Fairy"
]
results = [
    [2, 2, 2, 2, 2, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],
    [4, 2, 1, 1, 2, 4, 1, 0, 4, 2, 2, 2, 2, 1, 4, 2, 4, 1],
    [2, 4, 2, 2, 2, 1, 4, 2, 1, 2, 2, 4, 1, 2, 2, 2, 2, 2],
    [2, 2, 2, 1, 1, 1, 2, 1, 0, 2, 2, 4, 2, 2, 2, 2, 2, 4],
    [2, 2, 0, 4, 2, 4, 1, 2, 4, 4, 2, 1, 4, 2, 2, 2, 2, 2],
    [2, 1, 4, 2, 1, 2, 4, 2, 1, 4, 2, 2, 2, 2, 4, 2, 2, 2],
    [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 4, 2, 4, 2, 2, 4, 1],
    [0, 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2, 1, 2],
    [2, 2, 2, 2, 2, 4, 2, 2, 1, 1, 1, 2, 1, 2, 4, 2, 2, 4],
    [2, 2, 2, 2, 2, 1, 4, 2, 4, 1, 1, 4, 2, 2, 4, 1, 2, 2],
    [2, 2, 2, 2, 4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 2, 1, 2, 2],
    [2, 2, 1, 1, 4, 4, 1, 2, 1, 1, 4, 1, 2, 2, 2, 1, 2, 2],
    [2, 2, 4, 2, 0, 2, 2, 2, 2, 2, 4, 1, 1, 2, 2, 1, 2, 2],
    [2, 4, 2, 4, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 0, 2],
    [2, 2, 4, 2, 4, 2, 2, 2, 1, 1, 1, 4, 2, 2, 1, 4, 2, 2],
    [2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 4, 2, 0],
    [2, 1, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2, 1, 1],
    [2, 4, 2, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 4, 4, 2]
]
def getMultiplier(first, second, third):
    id1 = types.index(first)
    id2 = types.index(second)
    if third in types:
        id3 = types.index(third)
        return results[id1][id2] * results[id1][id3] / 4;
    else:
        return results[id1][id2] / 2

def genFirstType(second, third, remain, removed):
    mul = getMultiplier(remain[0][1], second, third)
    if len(remain) == 1:
        result = "[ first is not " + removed[1] + "\n"
        result += "thus first must be " + remain[0][1] + "\n"
        result += ">" * (multipliers[mul] - 1) + "[-]-> " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n"
        result += "]\n"
        return result
    elif not removed:
        result = "<<" + "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n"
        result += genFirstType(second, third, remain[1:], remain[0])
        result += "<+[ first is " + remain[0][1] + "\n"
        result += ">" * multipliers[mul] + "[-] " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n"
        result += "]->\n"
        return result
    else:
        result = "[ first is not " + removed[1] + "\n"
        result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n"
        result += genFirstType(second, third, remain[1:], remain[0])
        result += "<+[ first is " + remain[0][1] + "\n"
        result += ">" * multipliers[mul] + "[-] " + str(mul).replace(".", "").rstrip("0") + "x multiplier\n"
        result += "]->\n"
        result += "]\n"
        return result
def genSecondType(third, remain, removed):
    if len(remain) == 1:
        result = "[ second is not " + removed[1] + "\n"
        result += "thus second must be " + remain[0][1] + "\n"
        result += genFirstType(remain[0][1], third, typemap[1:], False)
        result += "]\n"
        return result
    elif not removed:
        result = "<<" + "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n"
        result += genSecondType(third, remain[1:], remain[0])
        result += "<+[-> second is " + remain[0][1] + "\n"
        result += genFirstType(remain[0][1], third, typemap[1:], False)
        result += "<+]->\n"
        return result
    else:
        result = "[ second is not " + removed[1] + "\n"
        result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n"
        result += genSecondType(third, remain[1:], remain[0])
        result += "<+[-> second is " + remain[0][1] + "\n"
        result += genFirstType(remain[0][1], third, typemap[1:], False)
        result += "<+]->\n"
        result += "]\n"
        return result
def genThirdType(remain, removed):
    if len(remain) == 1:
        result = "[ third is not " + removed[1] + "\n"
        result += "thus third must be " + remain[0][1] + "\n"
        result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False)
        result += "]\n"
        return result
    elif not removed:
        result = "-" * remain[0][0] + " " + remain[0][1] + " is now 00\n"
        result += genThirdType(remain[1:], remain[0])
        result += "<+[-> third is " + remain[0][1] + "\n"
        result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False)
        result += "<+]->\n"
        return result
    else:
        result = "[ third is not " + removed[1] + "\n"
        result += "-" * (remain[0][0] - removed[0]) + " " + remain[0][1] + " is now 00\n"
        result += genThirdType(remain[1:], remain[0])
        result += "<+[-> third is " + remain[0][1] + "\n"
        result += genSecondType(remain[0][1], [item for item in typemap[1:] if item[1] != remain[0][1]], False)
        result += "<+]->\n"
        result += "]\n"
        return result
def genLookup():
    return genThirdType(typemap, False)

def compact(code):
    import re
    return re.sub(r"[^+\-<>\[\],.]", "", code)
def golfStep(code):
    return code.replace("><", "").replace("<>", "").replace("+-", "").replace("-+", "")
def golf(code):
    previous = golfStep(code)
    while previous != code:
        previous, code = code, golfStep(code)
    return code

if __name__ == "__main__":
    import sys
    result = genLookup()
    if "-g" in sys.argv:
        print(golf(compact(result)))
    elif "-c" in sys.argv:
        print(compact(result))
    else:
        print(result)

```

BTW, this answer takes 29817 bytes. :)

# Answer
> 5 votes
## C++14, ~~420~~ 416

```
#include<iostream>
#include<string>
std::string m,t,n="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai";int i;int main(){std::cin>>m>>t;auto k=[](auto y){return(i=6*n.find(m.substr(0,3))+n.find(y.substr(0,3))/3,i="J:2JJJ;YQJV>N:;ZIJJ5&ZJZ*[Y;KJVF;KZJ6I6YN>HJNJNFJZ:EYZJ:[UZIJ^J7JI:]9=JIZBJ>IINK:JFBZN:U:KJJ:JJ+FJNJN6NI:IJO"[i/3]-32>>i%3*2&3,i+i/3)/2.;};std::cout<<k(t)*((i=t.find(47)+1)?k(t.substr(i)):1)<<"x";}

```

Input should be to stdin and be in the form `Normal, Rock/Dragon`

Live version.

With some whitespace:

```
#include<iostream>
#include<string>
std::string m, t, n = "NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai";
int i;
int main(){
    std::cin >> m >> t;
    auto k = [](auto y){
        return(i = 6 * n.find(m.substr(0, 3)) + n.find(y.substr(0, 3)) / 3
            , i = "J:2JJJ;YQJV>N:;ZIJJ5&ZJZ*[Y;KJVF;KZJ6I6YN>HJNJNFJZ:EYZJ:[UZI"
            "J^J7JI:]9=JIZBJ>IINK:JFBZN:U:KJJ:JJ+FJNJN6NI:IJO"[i / 3] - 32 >> i % 3 * 2 & 3
            , i + i / 3) / 2.;
    };
    std::cout << k(t)*((i = t.find(47) + 1) ? k(t.substr(i)) : 1) << "x";
}

```

# Answer
> 3 votes
# Lua, ~~758~~ ~~661~~ 633 bytes

```
m={"222221201222222222","421124104222214241","242221421224122222","222111210224222224","220424124421422222","214212421422224222","211122211124242241","022222242222242212","222224221112124224","222221424114224122","222244222411222122","221144121141222122","224202222241122122","242422221222212202","224242221114221422","222222221222222420","212222242222242211","242122221122222442"}s="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"function f(a,d)z=string.sub n=tonumber _,r=s:find(z(a,1,3))r=r/3g,_,c=0,s:find(z(d,1,3))c=c/3p=d:find("/")or 0 e=m[r]_,g=s:find(z(d,p+1,p+3))g=g/3r=n(z(e,c,c))/2r=r*n(z(e,g,g))/2print(r.."x")end

```

Ungolfed:

```
m={"222221201222222222","421124104222214241","242221421224122222","222111210224222224","220424124421422222","214212421422224222","211122211124242241","022222242222242212","222224221112124224","222221424114224122","222244222411222122","221144121141222122","224202222241122122","242422221222212202","224242221114221422","222222221222222420","212222242222242211","242122221122222442"}
s="NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai"
function f(a,d)
    z=string.sub
    n=tonumber
    _,r=s:find(z(a,1,3))
    r=r/3
    g,_,c=0,s:find(z(d,1,3))
    c=c/3
    p=d:find("/") or 0
    e=m[r]
    _,g=s:find(z(d,p+1,p+3))
    g=g/3
    r=n(z(e,c,c))/2
    r=r*n(z(e,g,g))/2
    print(r.."x")
end

```

Call it with `f("Grass","Water/Flying")`

# Answer
> 3 votes
## Tcl, 382

```
proc p a\ d [zlib i ...361 bytes...]

```

The script contains compressed data including non-UTF-8 bytes. Here is the exact script encoded in base 64:

```
cHJvYyBwIGFcIGQgW3psaWIgaSDFU7FugzAQ/ZU3pEuGlljqwlilibpUUVw7dEBc
Zo7jghUHI9uREiH+vUDA2NCqY2SJXDt87969XDvb5dkaXCTfSp+oxUN2QWKZjOPm
L1dlHC9RLetEnmiJPRJTSmGxOOApRSVFceAXVNVcbsOKHp/bb28nq0ZFeswtTm4+
SJBPhkiDX7nYEBmYSVijw6489l5Jx3/Dj0pIj47GWp0lXh2fN6w9R5FcdHasP1dE
HH7oMVxupkRmfpfn+lx298NOHXOADmbqKXcT9NDE1Se/dDFiRybiT7rb+Sunm1xb
0J1fwceOM/JcIoEfBaz+HVx0XHt0XjCROa/T587wvxPx7+dU4TS/wdQ1Emk41SxH
9d4+NomNyHIrilxmG3ltzU5cdKNcbmy1OhcHfCh2xMs5wzZXxuLTct6maI4varlu
YNQYvErOrBZcZlw7c2V5Y98Yx1rTrCFaU1x9xIZcblx9rbGg6Z0F7NM6TdMfXQ==

```

Uses the `zlib` command for compression.

# Answer
> 2 votes
# Python 3 - 362

```
k,*l=['rm gh yi is ou ck g os ee re te as ec yc e ag rk ir'.split().index(x[2:4])for x in input().replace('/',' ').split()]
s=[[0,0.5,1,2][[(ord(m)-40)//4**q%4 for m in'RB:RRRCaYR^FVBCbQRR=.bRb2caCSR^NCSbR>Q>aVFPRVRVNRbBMabRBc]bQRfR?RQBeAERQbJRFQQVSBRNJbVB]BSRRBRR3NRVRV>VQBQRW'for q in(0,1,2)][k*18+z]]for z in l]
v=s[0]*(s[1:]or[1])[0]
print(str(v//1+v%1)+'x')

```

Input format is the move type and the Pokemon type, separated by spaces. For example `Fire Grass`, or `Water Steel/Electric`.

The table is stored is a string where each character's index is in the range 40 to 103 and represents 3 type combinations. The list of types is stored as the 3rd and 4th (if it exists) characters of each type, which are compared to the 3rd and 4th characters of each entered type.

# Answer
> 1 votes
## PHP, 426

```
eval('f('.fgets(STDIN).');');
function f($a,$d){
    $x=1;$r=array_fill_keys(explode('/',$d),$a);
    while(list($d,$a)=each($r)) {
        $x*=substr(gmp_strval(gmp_init('26gXl6oUL8Ekoey31DRp2k1Jq85b0G3f1PsFPfEnL1P6Bxh4vSloX8zWWa4XPBAGavHMKLgaGhPp2JPA3qQI3L9kkQ4kSHvu2vm76aLpJmu6TV8qcPTO0hchrLRh6G9',62),5),n($a)*18+n($d),1)/2;
    }
    echo$x.'x';
}
function n($p){return strpos('NorFigFlyPoiGroRocBugGhoSteFirWatGraElePsyIceDraDarFai',substr($p,0,3))/3;}

```

Sample input:

```
"Ground", "Fire"
"Normal", "Rock/Dragon"
"Fighting", "Ghost/Steel"
"Steel", "Water/Steel"
"Ice", "Dragon/Flying"
"Water", "Ground/Water"
"Ghost", "Ghost"

```

Sample output:

```
2x
0.5x
0x
0.25x
4x
1x
2x

```

---
Tags: code-golf
---