title: Loops and Loops and Loops

text:
# Question
Title: Loops and Loops and Loops
# The Challenge

Create a function that, when given an input of ASCII art (directing a path that may eventually loop), outputs the length of the loop (if there is one) and the length of the "tail" leading into the loop in one of the forms below.

---

# Input

Your input must be passed to a function. Below is an example of a simple input.

```
# --> # --> #
      ^     |
      |     |
      |     v
      # <-- #

```

You could visualize the above blocks like this

The "tail" is one item, while the loop is four long.

A more difficult one:

```
            # --> # --> #
            ^           |
            |           |
            |           v
      # --> # <-- #     # --> #
      ^           ^           |
      |           |           |
      |           |           v
# --> #           # <-- # <-- #

```

---

# Output

You must output through STDOUT or your language's closest alternative.

Your two output integers should be the length of the tail and the length of the loop. This output can be in two forms.

1. a space-delimited string: `"2 10"`
2. an array of integers: `[2, 10]`

---

# Rules

* Every block, or `#`, will only have a *single path away* from itself.
* Every arrow is two line segments and one head.
* The starting block will always be in the leftmost column.
* The input will never be just a loop.

---

# Example

```
# --> # --> # --> #
^     ^           |
|     |           |
|     |           v
#     # <-- # <-- #

```

This one has a tail length of 2 and a loop length of 6. Below, the tail and loop are separated.

### Tail

```
# -->
^
|
|
#

```

### Loop

```
# --> # --> #
^           |
|           |
|           v
# <-- # <-- #

```

The correct outputs are `[2, 6]` and `"2 6"`.

If the input is *only a tail*, the loop length is zero.

```
# --> # --> # --> #
                  |
                  |
                  v
        <-- # <-- #

```

The correct outputs for the above input are `[6, 0]` and `"6 0"`

# Answer
# JavaScript (ES6), 221 ~~229~~

A function with the input as a parameter, output as a string via popup window (alert).

Scan repeatedly the input:
at each step

* remove the end of the tail
* count the remaining '#'

When there is not more tail to remove, the number of the steps so far is the size of the tail and the number of remaining '# is the size of the loop.

All the newlines inside backticks are significant and counted

Test running the snippet below with Firefox (not Chrome, as it does not support `...`)

```
F=s=>{s=`

${s}

`.split`
`.map(r=>[...r]);for(t=0,f=1;f;)s.map((r,y)=>r.map((c,x)=>c=='#'&&((r[x+2]+r[x-2]+s[y-1][x]+s[y+1][x]).match`[v<>^]`?++l:t+=(f=r[x-4]=r[x+4]=s[y-3][x]=s[y+3][x]=r[x]=1))),f=l=0);alert(t+' '+l)}

// Less golfed
U=s=>{
  s=`\n\n\n${s}\n\n\n`.split`\n`.map(r=>[...r])
  t=0
  do {
    f=l=0
    s.forEach((r,y) => {
      r.forEach((c,x) => {
        if (c == '#')
        {
          if (!(r[x+2] == '<' || r[x-2] == '>' || s[y-1][x] == 'v' || s[y+1][x] == '^'))
            t+=(f=r[x-4]=r[x+4]=s[y-3][x]=s[y+3][x]=r[x]=1)
          else
            ++l
        }
      })
    })
  } while(f)
  alert(t+' '+l)
}

//Test

// Redefine console.log
alert=(...x)=>O.innerHTML+=x+'\n'

test=[`
# --> # --> #
      ^     |
      |     |
      |     v
      # <-- #`
,`
            # --> # --> #
            ^           |
            |           |
            |           v
      # --> # <-- #     # --> #
      ^           ^           |
      |           |           |
      |           |           v
# --> #           # <-- # <-- #`
,`
# --> # --> # --> #
^     ^           |
|     |           |
|     |           v
#     # <-- # <-- #`
]

test.forEach(t=>(alert(t),F(t)))
```

```
<pre id=O></pre>
```
> 11 votes

# Answer
# Ruby, ~~287~~ 278 bytes

```
->i{n={}
g=->x{n[x]||=[0,p]}
t=y=0
i.lines{|l|x=0
l.chars{|c|x+=1
'><'[c]&&(r=c.ord-61;s,d=[y,x-4*r],[y,x+2*r])
'^v'[c]&&(r=c<?_?1:-1;s,d=[y+r*3,x],[y-r,x])
s&&(g[s][1]=g[d])[0]+=1}
y+=1}
c,*_,s=n.values.sort_by{|v|v[0]}
l=n.size
s[0]>1?((t+=1;c=c[1])while c!=s):t=l-=1
[t,l-t]}

```

Try it here.

This builds a hash (dictionary) of nodes. For each node, the number of incoming connections and the (possibly null) next node are stored.

Finally:

* If there is no node with 2 incoming connections (meaning no loop), return 0 for the tail and the number of existing nodes for the loop.
* Otherwise, start iterating from the node with 0 incoming connections (start) via next-\>...-\>next until the node with 2 incoming connections (loop start) is reached. Return the appropriate counts.

The readable version of the code is available here.
> 8 votes

# Answer
# Ruby, 276

```
->s{a=k=w=s.index(r='
')*2+2
s=r*w+s+r*w
(s.size).times{|i|s[i,2]=='
#'&&(s[3+j=i+1]+s[j+w]+s[j-w]).strip.size<2&&(a=[j]
d=0
loop{("|-|-"[d])+?#=~/#{s[k=j+[-w,3,w,-3][d]]}/?(a.include?(k)&&break;a<<(j=k);d-=1):d=(d+1)%4}
)}
u=a.size
v=a.index(k)
t=(u-v)/4*2
print u/2-t," ",t}

```
> 2 votes

---
Tags: code-golf, ascii-art, graph-theory
---


title: Implement a Moore State Machine

text:
# Question
Title: Implement a Moore State Machine
This challenge is a slightly different kind of Code Golf challenge. Rather than coding to match IO, you code to match an interface.

### Background

Finite state machines are very useful design models for modeling event-based programming. A state machine is defined by a set of states and tranitions between them. The machine can be in one and only one state at any given time: the *current state*. Naturally, the machine has an *initial state*. When an event occurs, it may change it's state to another state; this is called a *transition*. A Moore machine is simply a FSM which can produce output; each state can produce an output.

For example, consider the following state machine which models a turnstile:

The `Locked` state is the initial state of the machine. Whenever the turnstile is `Push`ed from this state, we do nothing (go back to the `Locked` state). However, if we receive a `Coin`, we transition to the `Un-locked` state. Extra `Coin`s do nothing, but a `Push` puts us back into the `Locked` state. It's not explicitly stated, but this FSM does have output: the `Locked` state has an output that tells the turnstile to lock it's arms, wheras the `Un-locked` state has an output that allows the turnstile to turn.

### Task

You must implement a state machine class. This means that only languages with objects can compete. If there is an accepted alternative to objects in your language, that is valid (e.g. C can use structs with member functions). You must be able to access the functions of the object via `obj.function` or `obj->function` or whatever the accessor character for your language is. You are allowed to use a state machine library if it exists for your language, but you aren't allowed to use a class from the library "as your own" (don't just point at a premade class and say that that's your solution).

You must implement the following methods with exactly the specified names and signatures. However, you may capitalize the first letter or switch to `snake_case` (e.g. `mapOutput`, `MapOutput`, or `map_output` are all valid). Additionally, you may take an explicit *this* parameter as the first parameter:

* `map(State from, Event event, State to)` Defines a transition from `from` to `to` on the event `event`. If `from` and `event` have both been previously passed to this method before, you may do anything at all.
* `mapOutput(State state, Output output)` Assigns the given output to the given state. If `state` has been previously passed to this method before, you may do anything at all.
* `processEvent(Event event)` Advances the state machine according to the transitions defined via `map`. Basically, if the current state of the state machine is `from`, then `event` sets the current state to the state defined by a previously called `map(from, event, to)`. Throws an exception or fails violently if there is no mapping for the current state and given event.
* `getOutput()` Gets the output for the current state, as defined via `mapOutput`. Returns `null` or equivalent if there is no output defined for the given state. This may be an `Optional` type or similar if your language has one.
* Some sort of initial-state setting. This may be done in the constructor for your class, you may require `State` to have a default constructor, or you may provide some other way of setting the initial state.

The idea of `State`, `Event`, and `Output` is that they are generic types. You don't have to support generics per se, but this means that the user of your state machine will only pass in the type `State` for states, the type `Event` for events, and the type `Output` for outputs. However, the state machine is expected to be "generic" in that it should be possible to use any type as a `State`, any type as an `Event`, and any type as an `Output`.

Additionally, you map implement the `map` and `mapOutput` methods in a separate builder class, but I don't foresee that saving any bytes.

## Test cases

Note: don't trust my code. It's untested. It's intended mostly to give an idea of what you state machine will be used like

Java, classname `StateMachine`, initial-state passed via constructor:

```
// States are ints, Events are chars, Outputs are ints
StateMachine machine = new StateMachine(0);
machine.map(0, '0', 1);
machine.map(0, '1', 2);
machine.map(0, '2', 3);
machine.map(1, '3', 0);
machine.map(1, '4', 2);
machine.map(2, '5', 0);
machine.map(2, '6', 1);
machine.map(2, '7', 2);
machine.mapOutput(1, 1);
machine.mapOutput(2, 10);
machine.mapOutput(3, 0);

// At this point, there should be absolutely no errors at all.
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('0'); // Don't count on reference equality here...
System.out.println(machine.getOutput()); // Should output `1`
machine.processEvent('4');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('7');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('6');
System.out.println(machine.getOutput()); // Should output `1`
machine.processEvent('3');
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('1');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('5');
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('2');
System.out.println(machine.getOutput()); // Should output `0`
// Now any calls to processEvent should cause an exception to be thrown.
machine.processEvent('0'); // Throws an exception or crashes the program.

```

Ruby, classname `SM`, initial-state through `attr_writer` on `i`:

```
sm = SM.new
sm.i = :init # All states will be symbols in this case.
[
  [:init, [], :init],
  [:init, [1], :state1],
  [:init, [2, 3], :state2],
  [:state1, [], :init],
  [:state1, [1], :state1],
  [:state1, [2, 3], :state2],
  [:state2, [], :init],
  [:state2, [1], :state1],
  [:state2, [2, 3], :state2]
].each { |from, trigger, to| sm.map(from, trigger, to) }
sm.mapOutput(:state1, [1])
sm.mapOutput(:state2, [[2, 3], 4, 5])

p sm.getOutput # => nil
sm.processEvent []
p sm.getOutput # => nil
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent []
p sm.getOutput # => nil
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent []
p sm.getOutput # => nil

```

Note that even though there are only a few test cases, you must support arbitrary input to these functions.

# Answer
> 1 votes
# JavaScript (ES6), ~~132 125 121~~ 109

```
M=c=>(s={},r={},{map:(f,e,t)=>s[f+e]=t,mapOutput:(s,o)=>r[s]=o,processEvent:e=>c=s[c+e],getOutput:x=>r[c]})

```

*Thanks to edc65 for his suggestion of avoiding the full-fledged constructor approach!*

Here's a test snippet that works in Chrome and Firefox:

```
M=c=>(s={},r={},{map:(f,e,t)=>s[f+e]=t,mapOutput:(s,o)=>r[s]=o,processEvent:e=>c=s[c+e],getOutput:x=>r[c]})

var sm = M('Locked');

var output = '';
var print = t => { output += t + "\n"; }

print(sm.getOutput() || 'not defined (there are no outputs currently defined)');

sm.map('Locked', 'Coin', 'Unlocked');
sm.map('Unlocked', 'Coin', 'Unlocked');
sm.map('Unlocked', 'Push', 'Locked');
sm.map('Locked', 'Push', 'Locked');

sm.mapOutput('Locked', 'Insert coin!');
sm.mapOutput('Unlocked', 'You can pass now.');

function event(name){
  print(' >> ' + name);
  sm.processEvent(name);
}

print(sm.getOutput());
event('Push');
print(sm.getOutput());
event('Coin');
print(sm.getOutput());
event('Coin');
print(sm.getOutput());
event('Push');
print(sm.getOutput());

alert(output);
```

# Answer
> 1 votes
# OCaml, 217

This is an anonymous function which takes the initial state as its sole parameter and returns a newly constructed object. The function/object are polymorphic in the state, event, and output types.

```
fun i->Hashtbl.(object
val o=create 9
val t=create 9
val mutable s=i
method map a b c=add t(a,b)c
method mapOutput a b=add o a b
method getOutput=try Some(find o s)with _->None
method processEvent e=s<-find t(s,e)end)

```

For a 200+-byte program, there seemed to be remarkably few opportunities for golfing.

Example usage:

```
let k =
fun i->Hashtbl.(object
val o=create 9
val t=create 9
val mutable s=i
method map a b c=add t(a,b)c
method mapOutput a b=add o a b
method getOutput=try Some(find o s)with _->None
method processEvent e=s<-find t(s,e)end)
;;

let pr optint = match optint with
    | Some x -> Printf.printf "%d\n" x
    | None -> Printf.printf "None\n" ;;

let machine = k 0;;

machine#map 0  '0'  1 ;;
machine#map 0  '1'  2 ;;
machine#map 0  '2'  3 ;;
machine#map 1  '3'  0 ;;
machine#map 1  '4'  2 ;;
machine#map 2  '5'  0 ;;
machine#map 2  '6'  1 ;;
machine#map 2  '7'  2 ;;
machine#mapOutput 1 1 ;;
machine#mapOutput 2 10 ;;
machine#mapOutput 3 0 ;;
pr machine#getOutput ;;
machine#processEvent '0' ;;
pr machine#getOutput ;;
machine#processEvent '4' ;;
pr machine#getOutput ;;
machine#processEvent '7' ;;
pr machine#getOutput ;;
machine#processEvent '6' ;;
pr machine#getOutput ;;
machine#processEvent '3' ;;
pr machine#getOutput ;;
machine#processEvent '1' ;;
pr machine#getOutput ;;
machine#processEvent '5' ;;
pr machine#getOutput ;;
machine#processEvent '2' ;;
pr machine#getOutput ;;
(* causes exception *)
machine#processEvent '0'

```

# Answer
> 1 votes
# C# (LinqPad) 318 Bytes

### Golfed Version

```
class S<T,K> where K:Hashtable,new(){public T c;K m=new K(),o=new K();public void Map(T f,char e,T t){if(!m.Contains(f))m.Add(f,new K());((K)m[f]).Add(e,t);}public void MapOutput(int t,object r){o.Add(t,r);}public void ProcessEvent(char e){c=(T)((K)m[c])[e];}public object GetOutput(){return o.Contains(c)?o[c]:null;}}

```

### Ungolfed Version

```
class S<T,K> where K:Hashtable,new()
{
    public T c;
    K m=new K(),o=new K();
    public void Map(T f,char e,T t){if(!m.Contains(f))m.Add(f,new K());((K)m[f]).Add(e,t);}
    public void MapOutput(int t,object r){o.Add(t,r);}
    public void ProcessEvent(char e){c=(T)((K)m[c])[e];}
    public object GetOutput(){return o.Contains(c)?o[c]:null;}
}

```

### Initialization:

```
var m = new S<int,Hashtable>();

```

### Setting initial State:

```
m.c = 0 // or whatever

```

If you don't use it in LinqPad you've got to add another "using System.Collections;" in front (+25 Bytes)

# Answer
> 0 votes
# Ruby, 174 bytes

```
class M
def initialize i
@c=@i=i
@s={}
@o={}
end
def map f,e,t
@s[[f,e]]=t
end
def mapOutput s,o
@o[s]=o
end
def processEvent e
@c=@s[[@c,e]]
end
def getOutput
@o[@c]
end
end

```

I think the code is pretty self-explanatory. This challenge is not challenging in Ruby.

---
Tags: code-golf
---


title: Let us play the ocarina

text:
# Question
Title: Let us play the ocarina
As we all know, the Zelda series are one of the best game series ever made. In honor of that, let us play some songs on the ocarina.

## Challenge:

Write a program which, given a song, outputs the score to stdout for that particular song.

## Input:

The song which you will have to output the score of will be given by a unique three character combination as seen below:

```
zel - Zelda's Lullaby
sas - Saria's Song
eps - Epona's Song
sos - Sun's Song
sot - Song of Time
sst - Song of Storms

```

**Bonus songs, -7 % each:**

```
mof - Minuet of Forest
bof - Bolero of Fire
sow - Serenade of Water
nos - Nocturne of Shadow
ros - Requiem of Spirit
pol - Prelude of Light

```

**Bonus song 2, -8 %:**

```
scs - Scarecrow's song

```

As we all know, the Scarecrow's song is a song you compose yourself. This song needs to have eight notes. Output a score you compose yourself which is different from all the other scores.

If you decide to include all songs, it will total to a -50 % bonus to your byte score.

## Output:

The notes in the output are symbolized by the following characters:

```
^
<
>
V
A

```

Output a score on the following format:

```
-^-^-^-^-^-^-^-^-
-<-<-<-<-<-<-<-<-
->->->->->->->->-
-V-V-V-V-V-V-V-V-
-A-A-A-A-A-A-A-A-

```

Only one note per column is allowed. For simplicity's sake I've added another row to the original four rows.

Each note correspond to a different row:

```
^: ----------------
<: ----------------
>: ----------------
V: ----------------
A: ----------------

```

Output shall be written to stdout. Trailing newlines are allowed.

## Examples:

**Input (Zelda's Lullaby):**

```
zel

```

**Output:**

```
---^-----^-------
-<-----<---------
----->----->-----
-----------------
-----------------

```

**Input (Bolero of Fire):**

```
bof

```

**Output:**

```
-----------------
-----------------
--------->--->---
-V---V-----V---V-
---A---A---------

```

**Note cheat sheet:**

```
zel
<^><^>
sas
V><V><
eps
^<>^<>
sos
>V^>V^
sot
>AV>AV
sst
AV^AV^
mof
A^<><>
bof
VAVA>V>V
sow
AV>><
nos
<>>A<>V
ros
AVA>VA
pol
^>^><^

```

Since we play the ocarina code golf, the shortest program in bytes wins!

## Song references:

http://www.thonky.com/ocarina-of-time/ocarina-songs

http://www.zeldadungeon.net/Zelda05-ocarina-of-time-ocarina-songs.php

# Answer
# Pyth, 56.5 (113 bytes − 6 × 7% − 8%)

```
VtJ" ^<>VA"+K\-sm+?qNdNKK@LJj@jC"þØí§V^G¤×¹z1«bëë¶ñRõr¤çM"1391423xcs@LGjC"cc0Á:xqç÷\rS  Íó×º:9"lG3z6

```

It contains unprintable characters, so here is a reversible `xxd` hexdump:

```
0000000: 5674 4a22 205e 3c3e 5641 222b 4b5c 2d73  VtJ" ^<>VA"+K\-s
0000010: 6d2b 3f71 4e64 4e4b 4b40 4c4a 6a40 6a43  m+?qNdNKK@LJj@jC
0000020: 2207 fe85 d880 ed0e a756 5e47 8ba4 d7b9  "........V^G....
0000030: 7a9e 0531 ab1b 62eb ebb6 f112 52f5 72a4  z..1..b.....R.r.
0000040: e74d 2231 3339 3134 3233 7863 7340 4c47  .M"1391423xcs@LG
0000050: 6a43 229a 6317 6330 c13a 9278 71e7 10f7  jC".c.c0.:.xq...
0000060: 5c72 5309 87cd f3d7 ba3a 3922 6c47 337a  \rS......:9"lG3z
0000070: 36                                       6

```

You can also try it online.

## Explanation

I store the songs in base-6 numbers, re-encoded to base 1391423 and then base 256 to save space. I had to choose base 6 since some of the songs start with `^`, and numbers can't really start with a 0 after decoding.

```
  J" ^<>VA"                                                      save characters in J
 t                                                               discard the space
V                                                                loop over all characters
                               C"..."                            parse base256 string (songs) to int
                              j      1391423                     convert to base 1391423 (separate songs)
                                                   C"..."        parse base256 string (codes) to int
                                                  j      lG      convert to base-26
                                               @LG               replace indices by corresponding letters
                                              s                  concatenate
                                             c             3     chop to 3-character codes
                                            x               z    find index of input code
                             @                                   get correct song
                            j                                6   convert to base 6
                         @LJ                                     replace indices by corresponding ^<>VA
                m                                                map d over the above
                  ?qNdNK                                         take the current character if at its row,
                                                                 otherwise a dash
                 +      K                                        add a dash
               s                                                 concatenate
           +K\-                                                  add a dash and print

```
> 8 votes

# Answer
# Funciton, 4322 − 50% = 2161

Not really trying to golf here. Going more for the beauty angle. I think the main program looks really neat, a perfect rectangular box tucked away on the right.

As always, you can get a better rendering by executing `$('pre').css('line-height',1)` in your browser console.

```
                 ┌─────────────────────────┐
               ┌─┴─╖                     ┌─┴─╖
      ┌────────┤ · ╟─────────────────────┤ · ╟─────────────┐    ╔═════════╗   ╔════╗  ╔════╗
      │        ╘═╤═╝     ╔═════════╗     ╘═╤═╝ ╓───╖       │    ║ 1257283 ║ ┌─╢ 40 ║  ║ 25 ║
      │          │       ║ 2097151 ║       ├───╢ ʫ ╟───┐   │    ║ 6456094 ║ │ ╚════╝  ╚══╤═╝
    ┌─┴─╖        │       ╚════╤════╝     ┌─┴─╖ ╙─┬─╜ ┌─┴─╖ │    ║ 8219021 ║ │  ┌───╖   ┌─┴─╖
┌───┤ · ╟────────┴────┐       └─────┬────┤ · ╟───┴───┤ · ╟─┤    ║ 4660190 ║ └──┤ × ╟───┤ % ║
│   ╘═╤═╝             │            ┌┴┐   ╘═╤═╝       ╘═╤═╝ │    ╚════════╤╝    ╘═╤═╝   ╘═╤═╝
│     │               │            └┬┘     │           │   │    ╔═══╗  ┌─┴─╖  ┌──┴─╖   ╔═╧═╗
│     │  ╔═══╗ ┌────╖ │           ┌─┴─╖ ┌┐ │           │   │    ║ 8 ╟──┤ ʫ ╟──┤ >> ║   ║   ║
│     │  ║ 1 ╟─┤ >> ╟─┘       ┌───┤ ? ╟─┤├─┤           │   │    ╚═══╝  ╘═╤═╝  ╘══╤═╝   ╚═══╝
│     │  ╚═══╝ ╘══╤═╝         │   ╘═╤═╝ └┘ │           │   │    ╔════════════════╧═════════╗
│     │         ┌─┴─╖ ┌───╖ ┌─┴─╖ ┌─┴─╖  ╔═╧═╗         │   │    ║ 609678112368778425678534 ║
│   ┌─┴─────────┤ ʫ ╟─┤ ‼ ╟─┤ · ╟─┤ ‼ ║  ║ 1 ║         │   │    ║ 616189712722605554111376 ║
│   │           ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝  ╚═══╝         │   │    ║ 461573643915077926310571 ║
│   │             │     │     │   ╔═╧══╗               │   │    ║ 355541007599150245813976 ║
│   │   ╔══════╗  │     │     └───╢ 45 ║               │   │    ║ 426564826002362964111793 ║
│   │   ║ 2097 ║  │   ┌─┴─╖ ┌───╖ ╚════╝               │   │    ║ 714054902293682079346275 ║
│   │   ║ 1565 ║  └───┤ · ╟─┤ ♭ ╟─┐                    │   │    ║ 663973372550500581508544 ║
│   │   ╚═╤════╝      ╘═╤═╝ ╘═══╝ ├────────────────────┘   │    ║ 874263187322344354338195 ║
│   │   ┌─┴─╖         ┌─┴─╖       │                        │    ║ 642609790172899326178321 ║
│   │   │ ‼ ╟─────────┤ ? ╟───────┘                        │    ║ 071643306454414932126243 ║
│   │   ╘═╤═╝         ╘═╤═╝                                │    ║ 308860823981077902637848 ║
│ ┌─┴─╖ ┌─┴─╖ ╔═══╗   ┌─┴─╖                                │    ║ 322657399386789617074176 ║
└─┤ · ╟─┤ ʫ ╟─╢ 8 ║ ┌─┤ ? ╟────────────────────────────────┘    ╚══════════════════════════╝
  ╘═╤═╝ ╘═╤═╝ ╚═══╝ │ ╘═╤═╝
    │ ┌───┴╖ ╔════╗ │ ╔═══╗
    └─┤ >> ╟─╢ 21 ║ └─╢ 0 ║
      ╘════╝ ╚════╝   ╚═══╝

```

Continuing in the tradition of giving Funciton functions names consisting of a single, strange, rarely-used Unicode character, I thought about what could best represent this challenge, and it occurred to me that *Link* and *Zelda* (or, if you want, *Legend* of *Zelda*) give you *LZ*, so the lower-case digraph ʫ (U+02AB, ʟᴀᴛɪɴ sᴍᴀʟʟ ʟᴇᴛᴛᴇʀ ʟᴢ ᴅɪɢʀᴀᴘʜ) seems appropriate.

# Explanation

As explained in the esolangs article, the Funciton program receives the input encoded as what I would call “UTF-21”, but as a single humongous integer. If I wanted to use this number as a key to a hashmap (dictionary, associative array), I’d need a hash function that satisfies two criteria: one, it’s simple enough to implement in Funciton, and two, all of the 13 expected input strings give a different hash value. The simplest hash function I could think of was `input % m` for some value of `m`. Therefore, I tried `m` = 13, 14, 15, etc. until I got to the smallest integer for which all the hash values are unique. Turns out this number is 25.

The hash values are:

```
zel =  6
sas = 19
eps = 10
sos = 22
sot =  1
sst =  9
mof = 14
bof =  3
sow = 13
nos = 17
ros = 21
pol = 16
scs = 23

```

We encode each song by having one bit represent the presence or absence of a note. For example, Zelda's Lullaby would be encoded as follows:

```
---^-----^------- = 01001000
-<-----<--------- = 10010000
----->----->----- = 00100100
----------------- = 00000000
----------------- = 00000000

```

except that the bits are in the opposite order; the top left cell is in the least significant bit. This means every song is 40 bits long.

We thus create a (moderately sparse) hash table by taking a 40×25 = 1000-bit number and placing the bit pattern for each song in the right place according to its hash value. The monstrous number in the program is exactly this hash table.

Here’s what each of the remaining numbers mean:

* `45` = `0x2D` is the Unicode for `-`.
* `1257283645609482190214660190`: This is the string `^<>VA` in UTF-21. In hindsight I could have used 7 bits per character here, making the number shorter, but UTF-21 is so deeply traditional in Funciton that it simply didn’t occur to me.
* `2097151` = `0x1FFFFF` = (1 \<\< 21) − 1. Used to get the first character from the above string.
* `20971565`: This is the string `-\n`, which is appended to the end of each line.
    + It may seem curious that this number and the previous look so similar, but if you think about it, it’s because we’re using decimal and the Unicode for `\n` happens to be 10. That last number is (10 \<\< 21) + 45.

The program now proceeds as follows:

* The main program calls `ʫ` with the following 3 parameters:
    + *B*: The hash table, shifted right by 40 bits times the hash value of the input. The song we want to output is now in the 40 least significant bits.
    + *c*: The string `^<>VA`.
    + *a*: The number 8.
* In each iteration of `ʫ`,
    + if *c* is not empty,
        - if *a* is not zero, look at the bottom bit of *B*. Output `-`, followed by another `-` if it is zero or the first character of *c* otherwise. Shift right *B* by one to remove one bit and decrement *a*.
        - if *a* is zero, output `-\n`, then chop off the first character from *c* and start another loop with *a* = 8.
    + if *c* is empty, we are done.
> 43 votes

# Answer
# Python 2, 143.5 (287 bytes - 50%)

```
i='^<>VA'
u=dict(zel="<^>"*2,sas="V><"*2,eps="^<>"*2,sos=">V^"*2,sot=">AV"*2,sst="AV^"*2,mof="A^<><>",bof="VAVA>V>V",sow="AV>><",nos="<>>A<>V",ros="AVA>VA",pol="^>^><^",scs="<"*8)[raw_input()]
r=[17*['-']for _ in[1]*5]
x=0
for g in u:r[i.find(g)][x*2+1]=g;x+=1
for h in r:print''.join(h)

```

The grid is generated with dashes; then indexed and replaced with notes.
> 11 votes

# Answer
# Perl 5, 125 (~~320~~ ~~260~~ 250 Bytes -6x7% bonus songs -8% scarecrow song)

Yay, finally an opportunity to experiment with that Perlish hash syntax.

```
$_=pop;@B={qw(zel <^><^> sas V><V>< eps ^<>^<> sos >V^>V^ sot >AV>AV sst AV^AV^ mof A^<><> bof VAVA>V>V sow AV>>< nos <>>A<>V ros AVA>VA pol ^>^><^ scs <^V>>V^<)}->{$_}=~/./g;map{@L=('-')x17;for$i(0..@B){$L[1+2*$i]=$_,if$B[$i]eq$_}say@L}qw(^ < > V A)

```

### Test

```
$ perl -M5.010 ocarina.pl scs
---^---------^---
-<-------------<-
------->->-------
-----V-----V-----
-----------------

```
> 7 votes

# Answer
# Perl, 75 (150 bytes - 50%)

```
#!perl -nl
$i=vec~$_,0,32;print+qw(- - ^ < > V A)[0,map{vec('w2$$W4F4w7DeweTFwR$Ew$C2wVdeVe3cw4B#EEVVwC5Tw44bwR&e',$i/480%15*8-$_,4)==$.&&$.,0}1..8]while$.++<6

```

Counting the shebang as 2, input is taken from stdin.

**Sample usage**

```
$ echo zel | perl zelda.pl
---^-----^-------
-<-----<---------
----->----->-----
-----------------
-----------------

$ echo bof | perl zelda.pl
-----------------
-----------------
--------->--->---
-V---V-----V---V-
---A---A---------

$ echo scs | perl zelda.pl
-----------------
---<-<-<---------
-----------------
-----------V-V---
-A-------A-----A-

```
> 5 votes

# Answer
# PHP: 130 bytes (260 ~~270~~ ~~279~~ bytes − 6 × 7% − 8%)

Thanks to Ismael Miguel and Blackhole for some great ideas to save more bytes!

```
<?php $f=str_split;for($z='*^<>VA';++$i<6;print"-
")foreach($f(base_convert(substr(current(preg_grep("/^$argv[1]/",$f(bofttmmeps8jf0mofvff0nosfnfopol99d0rosyxt0sasrgk0scs8m8msosm9p0sotnry0sowylc0sstybp0zeldk90,7))),-4),36,6),1)as$c)echo$i-$c?'--':'-'.$z[$c-0];

```

After the `print"-`, this is a literal insertion of a carriage return. It may translate to two bytes in Windows.

All bonus songs including the Scarecrow's song are included.

Each song is represented in seven bytes of code. I like the new scoring because with the old scoring I would have gained just one meager bonus point overall!

The recent edits make PHP generate a lot of warnings, so to keep things nice and tidy, those are diverted to `/dev/null`.

Save as `zelda.php` and run on the command line:

```
$ php zelda.php zel 2> /dev/null
---^-----^-------
-<-----<---------
----->----->-----
-----------------
-----------------

$ php zelda.php bof 2> /dev/null
-----------------
-----------------
--------->--->---
-V---V-----V---V-
---A---A---------

$ php zelda.php scs 2> /dev/null
-^-------^-------
---<-------<-----
----->------->---
-------V-------V-
-----------------

```
> 4 votes

# Answer
# Python 3 - 138.5 (~~292~~ ~~280~~ 277 bytes - 50%)

Shaved a few bytes off the current Python leader while doing the print-as-you-go method rather than the replace method.

Try Online

```
s=dict(zel="<^><^>",sas="V><V><",eps="^<>^<>",sos=">V^>V^",sot=">AV>AV",sst="AV^AV^",mof="A^<><>",bof="VAVA>V>V",sow="AV>><",nos="<>>A<>V",ros="AVA>VA",pol="^>^><^",scs="AV><^AV>")[input()]
s+=" "*8
for c in "^<>VA":
 o="-"
 for x in range(8):o+=["--",c+"-"][s[x]==c]
 print(o)

```

Run:

```
> python3 loz.py
bof [return]

```

Output:

```
-----------------
-----------------
--------->--->---
-V---V-----V---V-
---A---A---------

```
> 4 votes

# Answer
# Haskell, 344 - 50% = 172 bytes

```
import Data.List
s"zel"=82
s"sas"=69
s"eps"=86
s"sos"=48
s"sot"=128
s"sst"=50
z"mof"=11055
z"bof"=373854
z"sow"=1720
z"nos"=73217
z"ros"= -12730
z"pol"=4791
z"scs"=304236
z n=s n*126
p n|n*n== -n="   "|0<1="A^<>V"!!(n`mod`5):p(n`div`5)
o=putStr.unlines.transpose.(l:).concatMap(\c->[map(e c)"^<>VA",l]).take 8.p.z
e c d|c==d=c|0<1='-'
l="-----"

```

`o` does the job.

Thought I could beat Python by using these encodings (took me a long time .\_.), but no. They don't really save a lot of bytes yet. Any suggestions?

Yes, that is a minus in front of the encoding for `"ros"`. Thats because its 'sheet' ends with the character that means `0` in my base-5, because this negative trick wouldn't work for the 'easy songs' encoded by doubling what's encoded in `s`. Unless you use `quot` maybe, but then you can't handle `p (-1)` specially, since `quot (-5) = 0`, so the negativity would vanish. Whatever.
> 4 votes

# Answer
# Ruby, rev 1, 192 - 50% = 96

Golfing includes:

removal of whitespace between groups of letters in the magic string (and revision of the denominator at the end of the line to `/4`.) Removal of some other unnecessary whitespace.

conversion of the escape sequences into single characters (stack exchange will not display them, so I have put `?` as a placeholder)

redefinition of `g` as a single string containing five runs of 17 `-` followed by newlines, instead of an array of five strings of 17 `-`

```
s=gets.chop
s[?s<=>s[0]]=''
n=("owEkrswuns=;gcsbfbYuze33as&&es77os??otaast??mf?9pl
?"=~/#{s}/)/4
g=(?-*17+'
')*5
(n<4? n+5:6).times{|i|x=$'[i/3].ord/5**(i%3)%5;g[x*18+i*2+1]='^<>VA'[x]}
puts g

```

# Ruby, rev 0, 223 - 50% = 111.5 (ungolfed)

The input code is reduced to 2 letters. If it begins with an `s`, the `s` is deleted, if it begins with a letter after `s` (only applicable to `zel` the last letter is deleted, and if it begins with a letter before `s` the middle letter is deleted.

The magic string (which in the ungolfed version contains spaces for clarity) contains the 2-letter codes followed by the music data. It is searched using the match operator `=~` which returns the position in the string.

There is exactly one song each of 5, 7, and 8 notes (plus scs which also has 8 notes.) These, along with one arbitrary 6-note song `ros` are bundled at the beginning of the magic string so that the value of `n` given by the position in the string can be used to calculate the number of notes to play. `cs` is squeezed in before `bf`, and with the truncation when the number in `n` is rounded down we just get away with the correct calculation for both. After the fourth cluster, all songs have 6 notes so if `n` is large the number of notes is reduced to a default of 6.

An array of `-` is set up for output and the notes are substituted in one by one. The required music data is extracted from the variable `$'` which contains the part of the original magic string to the right of the match. In this way, irrelevant data is ignored.

The notes are encoded 3 at a time into the magic string, just after the relevant 2-letter song code. They are extracted with division by `5**(i%3)` and a character in `g` is updated accordingly. At the end of the program `g` is printed.

```
s=gets.chop
s[?s<=>s[0]]=''
n=("owEk rswu ns=;g csbfbYu ze33 as&& es77 os\21\21 otaa st\23\23 mf\35\71 pl\n\a"=~/#{s}/)/5

g=(0..4).map{'-'*17}
(n<4? n+5 : 6).times{|i|x=$'[i/3].ord/5**(i%3)%5;g[x][i*2+1]='^<>VA'[x]}
puts g

```
> 3 votes

# Answer
# Python 2, 141.5 Bytes -50% (283 Bytes)

```
s='D  2)AE0*  A2)D  AD )2 A  )D2A 0,"!A D2) A  (2EA"4H !A )2D A 1F`(A)2D  A  p\xc5*'.split("A")['sst pol zel sos sot sow sas ros mof scs nos eps bof'.split().index(raw_input())]
for c,n in zip(s,"^<>VA"):print"-".join([("-"+n)[i>"0"]for i in bin((ord(c)-32)%255)[2:].zfill(8)][::-1])

```

Stores each note as a byte as each line is 8 notes long. Recalls the binary representation and then replaces with the right characters.
> 2 votes

# Answer
# Lua, 249 bytes - 50% = 124.5

```
w=io.write for j=1,5 do n={sst=41881,pol=44915,zel=30814,sos=42315,sot=17577,sow=5953,sas=35588,ros=11065,mof=29335,nos=122170,eps=29729,bof=719576,scs=999999}[...]for i=1,8 do d=n%6 n=(n-d)/6 c=d==6-j and'AV><^':sub(d,d)or'-'w('-',c)end w('-\n')end

```

Pretty simple, just reads back songs encoded as base-6 numbers.
> 1 votes

---
Tags: code-golf, ascii-art, music
---


title: Hidden Power Calculator

text:
# Question
Title: Hidden Power Calculator
One of the reasons I've always loved Pokemon is because for such a simple-seeming game, it has so many layers of complexity. Let's consider the move Hidden Power. In game, the type and power (at least before Generation VI) of Hidden Power is different for every Pokemon that uses it! That's pretty cool, right? Now, would you be surprised if I told you that the type and power of Hidden Power isn't generated randomly?

In all Pokemon games, all Pokemon (not just ones in your party, ALL POKEMON) have six internally-stored integers (one for the HP stat, one for the attack stat, one for the defense stat, one for the special attack stat, one for the special defense stat and one for the speed stat) called their ***individual values,*** or IVs. These values range between 0 and 31, and they essentially are one of a few factors that influence a Pokemon's overall stats. HOWEVER, they also determine the type and power of Hidden Power!

In Generation III to V (the generations whose algorithm we'll be implementing), the type of Hidden Power is determined by the following formula (note the floor brackets, that means you need to round down the result):

where a, b, c, d, e and f are the least significant bits of the HP, Attack, Defense, Speed, Sp. Attack, and Sp. Defense IVs respectively. (Least significant bit is IV mod 2.) The number produced here then can be converted to the actual type using this chart:

```
0 Fighting
1 Flying
2 Poison
3 Ground
4 Rock
5 Bug
6 Ghost
7 Steel
8 Fire
9 Water
10 Grass
11 Electric
12 Psychic
13 Ice
14 Dragon
15 Dark

```

For power, a similar formula is used:

Here, however, u, v, w, x, y and z represent the second least significant bit of the HP, Attack, Defense, Speed, Sp. Attack and Sp. Defense IVs (in that order again). (Second least significant bit is more complicated then least significant bit. If IV mod 4 is 2 or 3, then the bit is 1, otherwise it is 0. If your language has some sort of built-in or at least a more clever way to do this, you should probably use it.)

---

So, as you probably figured out already, the challenge here is to write a program that takes in six integers separated by spaces via STDIN that represent the HP, Attack, Defense, Speed, Sp. Attack and Sp. Defense IVs of a Pokemon (in that order) and output the type and power of that Pokemon's Hidden Power.

Sample input:

```
30 31 31 31 30 31

```

Sample output:

```
Grass 70

```

Sample input:

```
16 18 25 13 30 22

```

Sample output:

```
Poison 61

```

This is code-golf, so shortest code wins. Good luck!

(And before people ask, I used the Generation V algorithm here because Generation VI gets rid of the power randomization and makes it always 60. Not only do I think this is incredibly lame, I think it makes the challenge a LOT LESS INTERESTING. So for the purposes of the challenge, we're running a Gen V game.)

# Answer
> 3 votes
# Pyth, 110 bytes

```
J+dGA.b/*iN2CY63Cm_+0jd2_Q"("r@cs@LJjC"!�W��Zm�����A�zB0i��ȏ\"���?wC�ǀ�-#ך
?ЫܦO@�J/m���#"26)G3+30H

```

This contains unprintable chars. So here's a hexdump:

```
00000000: 4a 2b 64 47 41 2e 62 2f 2a 69 4e 32 43 59 36 33  J+dGA.b/*iN2CY63
00000010: 43 6d 5f 2b 30 6a 64 32 5f 51 22 0f 28 22 72 40  Cm_+0jd2_Q".("r@
00000020: 63 73 40 4c 4a 6a 43 22 10 21 de 57 ad c8 5a 1c  cs@LJjC".!.W..Z.
00000030: 10 6d e0 d6 12 f6 80 bc 41 85 7a 42 30 69 ae 80  .m......A.zB0i..
00000040: c8 8f 5c 22 a0 84 ab 3f 77 43 01 ca c7 80 d0 1d  ..\"...?wC......
00000050: 2d 23 d7 9a 0a 3f d0 ab dc a6 4f 40 b9 4a 2f 6d  -#...?....O@.J/m
00000060: d2 ca c6 23 22 32 36 29 47 33 2b 33 30 48        ...#"26)G3+30H

```

You can also download the file pokemon.pyth and run it with `python3 pyth.py pokemon.pyth`

The input `30, 31, 31, 31, 30, 31` prints

```
Grass
70

```

### Explanation:

```
J+dGA.b/*iN2CY63Cm_+0jd2_Q".("
J+dG                            store the string " abc...xyz" in J
                 m      _Q      map each number d in reverse(input list) to:
                     jd2          convert d to base 2
                   +0             add a zero (list must have >= 2 items)
                  _               reverse the list
                C               zip
                          ".("  string with the ascii values 15 and 40
     .b                         map each N of ^^ and Y of ^ to:
         iN2                       convert N from base 2 to base 10
        *   CY                     multiply with the ascii value of Y
       /      63                   and divide by 63
    A                           G, H = ^

r@cs@LJjC"longstring"26)G3+30H
        C"longstring"           interpret the string as bytes and convert
                                from base 256 to base 10
       j             26         convert to base 26
   s@LJ                         lookup their value in J and create a string
                                this gives "fighting flying ... dark"
  c                    )        split by spaces
 @                      G       take the Gth element
r                        3      make the first letter upper-case and print
                          +30H  print 30 + H

```

# Answer
> 5 votes
# Ruby, 210

```
a=$*.map.with_index{|a,i|[a.to_i%2<<i,a.to_i[1]<<i]}.transpose.map{|a|a.inject &:+}
$><<"#{%w(Fighting
Flying
Poison
Ground
Rock
Bug
Ghost
Steel
Fire
Water
Grass
Electric
Psychic
Ice
Dragon
Dark)[a[0]*15/63]} #{a[1]*40/63+30}"

```

First time golfing, so I guess this is pretty obvious solution.

# Answer
> 3 votes
# CJam, ~~140~~ 115 bytes

```
q~]W%_1f&2bF*63/"GMÿD>BÙl½}YÛöí6P¶;óKs¯¿/·dÇ¯ã®Å[YÑÌÞ%HJ9¹G4Àv"256b25b'af+'j/=(euooSo2f/1f&2b40*63/30+

```

Note that the code contains unprintable characters.

Try it online in the CJam interpreter: Chrome | Firefox

# Answer
> 2 votes
# Javascript (ES6), 251 bytes

Kinda long, at least for now. The list of types and the complex maths take up about the same amount of space. I'm looking for ways to shorten either/both of them.

```
x=>([a,b,c,d,e,f]=x.split` `,`Fighting
Flying
Poison
Ground
Rock
Bug
Ghost
Steel
Fire
Water
Grass
Electric
Psychic
Ice
Dragon
Dark`.split`
`[(a%2+b%2*2+c%2*4+d%2*8+e%2*16+f%2*32)*5/21|0]+' '+((a/2%2+(b&2)+(c&2)*2+(d&2)*4+(e&2)*8+(f&2)*16)*40/63+30|0))

```

As usual, suggestions welcome!

# Answer
> 1 votes
# Javascript (ES6), 203 bytes

```
f=(...l)=>(q=(b,m)=>~~(l.reduce((p,c,x)=>p+(!!(c&b)<<x),0)*m/63),'Fighting0Flying0Poison0Ground0Rock0Bug0Ghost0Steel0Fire0Water0Grass0Electric0Psychic0Ice0Dragon0Dark'.split(0)[q(1,15)]+' '+(q(2,40)+30))

```

Example runs:

```
f(30,31,31,31,30,31)
> "Grass 70"

f(16,18,25,13,30,22)
> "Poison 61"

```

---
Tags: code-golf, number, game
---