title: Fixing a Froot Loop Necklace

text:
# Question
Title: Fixing a Froot Loop Necklace
Suppose you are stringing a strand of Froot Loops for a necklace, bracelet, shoelace, or whatever. There are 6 loop colors: **r**ed, **o**range, **y**ellow, **g**reen, **b**lue, and **p**urple. You want your strand to start with red at the very left and cycle in rainbow order going right, ending with purple. That is, you want to make it so your strand could be represented by the string `roygbp` repeated some number of times (possibly 0).

The problem is, you've already strung your loops, and not in any particular order. Which loops should you eat and not eat so that you can maximize the number of correct rainbow cycles going from left to right, with the very first loop red and the very last loop purple?

Write a program or function that takes in an arbitrary string of the characters `roygbp` and prints or returns a string of the same length with `e` in the place of loops to eat and `n` in the place of loops to not eat.

For example, if your Froot Loop strand looked like

the input would be

```
gorboypbgbopyroybbbogppbporyoygbpr

```

and going from left to right we can find 3 complete `roygbp` rainbow sequences, but some of the loops need to be eaten away. Thus the output would be

```
eenenneennenennneeeeneennenennnnne

```

resulting in a perfect 3 cycle strand:

If there are no complete rainbow cycles in the input then the output would be all `e`'s and the strand ends up loopless. e.g. the input `proygb` has output `eeeeee`. Conversely, `proygbp` has output `ennnnnn`.

You can assume all input strands have at least one loop.

**The shortest code in bytes wins.**

# Answer
# Pyth, 31 bytes

```
:*lz\nhf!:jk.DzT"roygbp"kyUlz\e

```

Incredibly inefficient, explanation coming soon.

`yUlz` generates all possible subsets of all possible indices of `z` (the input) in order. E.g. if the input is `abc`:

```
[[], [0], [1], [2], [0, 1], [0, 2], [1, 2], [0, 1, 2]]

```

Then `hf!` finds the first `T` in the above list such that `:jk.DzT"roygbp"k` is false. `.D` takes a string and list of indices, and deletes the elements at those indices. So `.D"abcd",1 3` is `"ac"`. Since `.D` returns a list (which should not be the case, will fix in future versions of Pyth), I use `jk` (`k` is `""`) to join it together back into a string. The `:_"roygbp"k` part replaces every instance of a cycle with the empty string.

Since the empty string is false, the above paragraphs explain how I find the smallest set of indices needed to eat to get a string consisting only of cycles.

`:*lz\n_\e` then turns that list of indices into an `nnnneeennene` string.
> 11 votes

# Answer
# Hexagony, ~~920~~ ~~722~~ 271 bytes

***Six*** different types of fruit loops, you say? That is what Hexagony was *made* for.

```
){r''o{{y\p''b{{g''<.{</"&~"&~"&<_.>/{.\.....~..&.>}<.._...=.>\<=..}.|>'%<}|\.._\..>....\.}.><.|\{{*<.>,<.>/.\}/.>...\'/../==.|....|./".<_>){{<\....._>\'=.|.....>{>)<._\....<..\..=.._/}\~><.|.....>e''\.<.}\{{\|./<../e;*\.@=_.~><.>{}<><;.(~.__..>\._..>'"n{{<>{<...="<.>../

```

Okay, it wasn't. Oh god, what did I do to myself...

This code is now a hexagon of side length 10 (it started out at 19). It could probably be golfed some more, maybe even to size 9, but I think my job is done here... For reference, there are 175 actual commands in the source, many of which are potentially unnecessary mirrors (or were added to cancel out a command from a crossing path).

Despite the apparent linearity, the code is actually two-dimensional: Hexagony will rearrange it into a regular hexagon (which is also valid code, but all whitespace is optional in Hexagony). Here is the unfolded code in all its... well I don't want to say "beauty":

```
          ) { r ' ' o { { y \
         p ' ' b { { g ' ' < .
        { < / " & ~ " & ~ " & <
       _ . > / { . \ . . . . . ~
      . . & . > } < . . _ . . . =
     . > \ < = . . } . | > ' % < }
    | \ . . _ \ . . > . . . . \ . }
   . > < . | \ { { * < . > , < . > /
  . \ } / . > . . . \ ' / . . / = = .
 | . . . . | . / " . < _ > ) { { < \ .
  . . . . _ > \ ' = . | . . . . . > {
   > ) < . _ \ . . . . < . . \ . . =
    . . _ / } \ ~ > < . | . . . . .
     > e ' ' \ . < . } \ { { \ | .
      / < . . / e ; * \ . @ = _ .
       ~ > < . > { } < > < ; . (
        ~ . _ _ . . > \ . _ . .
         > ' " n { { < > { < .
          . . = " < . > . . /

```

## Explanation

I won't even try and begin explaining all the convoluted execution paths in this golfed version, but the algorithm and overall control flow are identical to this ungolfed version which might be easier to study for the really curious after I've explained the algorithm:

```
                 ) { r ' ' o { { \ / ' ' p { . . .
                . . . . . . . . y . b . . . . . . .
               . . . . . . . . ' . . { . . . . . . .
              . . . . . . . . \ ' g { / . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
            . . . . . . . . . . . . . . . . . . . . . .
           . . . . . . . . > . . . . < . . . . . . . . .
          . . . . . . . . . . . . . . > . . ) < . . . . .
         . . . . . . . . . . / = { { < . . . . ( . . . . .
        . . . . . . . . . . . ; . . . > . . . . . . . . . <
       . . . . . . . . . . . . > < . / e ; * \ . . . . . . .
      . . . . . . . . . . . . @ . } . > { } < . . | . . . . .
     . . . . . / } \ . . . . . . . > < . . . > { < . . . . . .
    . . . . . . > < . . . . . . . . . . . . . . . | . . . . . .
   . . . . . . . . _ . . > . . \ \ " ' / . . . . . . . . . . . .
  . . . . . . \ { { \ . . . > < . . > . . . . \ . . . . . . . . .
 . < . . . . . . . * . . . { . > { } n = { { < . . . / { . \ . . |
  . > { { ) < . . ' . . . { . \ ' < . . . . . _ . . . > } < . . .
   | . . . . > , < . . . e . . . . . . . . . . . . . = . . } . .
    . . . . . . . > ' % < . . . . . . . . . . . . . & . . . | .
     . . . . _ . . } . . > } } = ~ & " ~ & " ~ & " < . . . . .
      . . . \ . . < . . . . . . . . . . . . . . . . } . . . .
       . \ . . . . . . . . . . . . . . . . . . . . . . . < .
        . . . . | . . . . . . . . . . . . . . . . . . = . .
         . . . . . . \ . . . . . . . . . . . . . . . . / .
          . . . . . . > . . . . . . . . . . . . . . . . <
           . . . . . . . . . . . . . . . . . . . . . . .
            _ . . . . . . . . . . . . . . . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
              . . . . . . . . . . . . . . . . . . . .
               . . . . . . . . . . . . . . . . . . .
                . . . . . . . . . . . . . . . . . .
                 . . . . . . . . . . . . . . . . .

```

Honestly, in the first paragraph I was only half joking. The fact that we're dealing with a cycle of six elements was actually a great help. The memory model of Hexagony is an infinite hexagonal grid where each edge of the grid contains a signed arbitrary-precision integer, initialised to zero.

Here is a diagram of the layout of the memory I've used in this program:

The long straight bit on the left is used as a 0-terminated string `a` of arbitrary size which is associated with the letter **r**. The dashed lines on the other letters represent the same kind of structure, each one rotated by 60 degrees. Initially, the memory pointer points at the edge labelled **1**, facing north.

The first, linear bit of the code sets the inner "star" of edges to the letters `roygbp` as well as setting the initial edge to `1`, such that we know where the cycle ends/begins (between `p` and `r`):

```
){r''o{{y''g{{b''p{

```

After this, we're back on the edge labelled **1**.

Now the general idea of the algorithm is this:

1. For each letter in the cycle, keep reading letters from STDIN and, if they are different from the current letter, append them to the string associated with that letter.
2. When we read the letter we're currently looking for, we store an `e` in the edge labelled **?**, because as long as the cycle is not complete, we have to assume that we'll have to eat this character as well. Afterwards, we'll move around the ring to the next character in the cycle.
3. There are two ways this process can be interrupted:
    * *Either* we've completed cycle. In this case, we make another quick round through the cycle, replacing all those `e`s in the **?** edges with `n`s, because now we want that cycle to remain on the necklace. Then we move on to printing code.
    * *Or* we hit EOF (which we recognise as a negative character code). In this case, we write a negative value into the **?** edge of the current character (so that we can easily distinguish it from both `e` and `n`). Then we search for the **1** edge (to skip the remainder of a potentially incomplete cycle) before moving to printing code as well.
4. The printing code goes through the cycle again: for each character in the cycle it clears the stored string while printing an `e` for each character. Then it moves to the **?** edge associated with the character. If it's negative, we simply terminate the program. If it's positive, we simply print it and move on to the next character. Once we complete the cycle we go back to step 2.

Another thing that might be interesting is how I've implemented the arbitrary-size strings (because it's the first time I've used unbounded memory in Hexagony).

Imagine we're at some point where we're still reading characters for **r** (so we can use the diagram as is) and **a\[0\]** and **a** have already been filled with characters (everything north-west of them is still zero). E.g. maybe we've just read the first two characters `og` of the input into those edges and are now reading a `y`.

The new character is read into the **in** edge. We use the **?** edge to check whether this character is equal to `r`. (There's a nifty trick here: Hexagony can only distinguish between positive and non-positive easily, so checking for equality via subtraction is annoying and requires at least two branches. But all the letters are less than a factor of 2 from each other, so we can compare the values by taking the modulo, which will only give zero if they are equal.)

Because `y` is different from `r`, we move the (unlabelled) edge left of **in** and copy the `y` there. We now move further around the hexagon, copying the character one edge further each time, until we have the `y` on the edge opposite of **in**. But now there is already a character in **a\[0\]** which we don't want to overwrite. Instead, we "drag" the `y` around the next hexagon and check **a**. But there's a character there as well, so we go another hexagon further out. Now **a\[2\]** is still zero, so we copy the `y` into it. The memory pointer now moves back along the string towards the inner ring. We know when we've reached the beginning of the string, because the (unlabelled) edges between the **a\[i\]** are all zero whereas **?** is positive.

This will probably be a useful technique for writing non-trivial code in Hexagony in general.
> 57 votes

# Answer
# Hexagony, 169 bytes

I was inspired by Martin Büttner’s answer (it’s his esolang, too) and decided I can do it in size 8. (I’m convinced it’s possible in size 7, too, but it’s very difficult. I’ve already spent four days non-stop on this.)

```
r'.'o\|{##|_#{#>\_{b{"]_\..<>"<>\/><#y/''"_<.}]''/'\>)}}.\}}'{<"\\#_#/<|##|#@#"p><n'>"{,<##g#_/#'.\<\##'#{(.<#e;#"\##%\\(};/*#>.)\>##_/"{__\}#>}=\#>=<|>##)|###_'#\"{__\\

```

Laid out hexagonally:

```
       r ' . ' o \ | {
      # # | _ # { # > \
     _ { b { " ] _ \ . .
    < > " < > \ / > < # y
   / ' ' " _ < . } ] ' ' /
  ' \ > ) } } . \ } } ' { <
 " \ \ # _ # / < | # # | # @
# " p > < n ' > " { , < # # g
 # _ / # ' . \ < \ # # ' # {
  ( . < # e ; # " \ # # % \
   \ ( } ; / * # > . ) \ >
    # # _ / " { _ _ \ } #
     > } = \ # > = < | >
      # # ) | # # # _ '
       # \ " { _ _ \ \

```

The program does not actually use the `#` instruction, so I’ve used that character to show which cells are actually unused. Furthermore, every no-op cell that is traversed in only one direction is a mirror (e.g. `_` if traversed horizontally), so you know all the `.` characters are traversed in more than one direction.

# Explanation

At the start, we execute the sequence of instructions `r''o{{y''g{{b''p"")"`. These are strewn a bit haphazardly across the code because I squeezed them in after I wrote everything else. I use `]` to switch to the next instruction pointer a few times; this way I can essentially teleport to another corner of the hexagon. The entire rest of the program is executed by instruction pointer #3.

The memory now looks as follows, with the important edges labeled with names I will use in this explanation:

The labeled edges mean the following:

* `in`: We use this edge to store a character we read from STDIN.
* `%`: We use this edge to perform a modulo operation on the character read from STDIN (`in`) and the current “valid” character (`r`, `o`, etc.), which will be `0` if they are equal. I stole this trick from Martin Büttner’s answer, but the rest of the program is different.
* `#`: For as long as we read “invalid” characters (i.e. colors we need to eat), we increment this edge. Thus, this edge remembers how many `e`s we need to output later.
* `r?`: Always `0` except where the `r` (red) part is. This tells us when we’ve completed a cycle.

The program proceeds thusly:

* Keep reading characters. If it’s not the character we’re currently looking for, increment `#`. Otherwise move to the next segment of the memory in clockwise order.
* When moving to the next segment, if `r?` is positive, we’ve made a whole revolution. Make a complete round and output `#` `e`s and 1 `n` per segment. This sets each `#` back to `0`. (The `e` is placed on an unlabeled edge, but for the `n` we misappropriate the `#` edge, which we set to `0` using a `*` (multiplication) afterwards, which works because we know that all the `%` edges are zero at this time.)
* When reading a character, if it is not positive (i.e., EOF), go backwards through the circle and output `#`+1 `e`s until you get back to where `r?` is positive, then exit.

After a complete run, the memory looks approximately as follows at the end. You will notice the edges containing `101` (the ASCII code of `e`); one of the `in` edges is `-1` (EOF); all the `#` edges are at 0; and the memory pointer ends at the positive `r?` edge.
> 31 votes

# Answer
# Retina, ~~148~~ ~~85~~ 79 bytes

```
$
#roygbp
.(?<=(?=((?=.*#(\2?(.))).*?\3(?<=^\5())?)+.*\3$)(.*))\4
n
#.*

[^n]
e

```

You can run this from a single source file with the `-s` interpreter flag.

## Explanation

Let's get the simple stuff out of the way first:

```
$
#roygbp

```

Appends `#roygbp` to the end of the string, which we'll use to compute the cycle of letters dynamically.

The next (long) step figures out which loops to keep and replaces them with `n`. We'll look into how this works in a bit.

```
#.*
<empty>

```

This gets rid of our lookup helper at the end of the string.

```
[^n]
e

```

This replaces all characters that weren't replaced in the second step with `e`, completing the transformation.

Now let's go back to the second step.

The basic structure uses a trick, which I discovered a few months ago to replace selected characters in a global match:

```
.(?<=(?=...(?<=^\k<prefix>(?<flag>))?...)^(?<prefix>.*))\k<flag>

```

where `...` corresponds to an arbitrarily complex pattern. This matches the character to be replaced with `.` and then starts a lookbehind (which you should read from right to left). The lookbehind captures everything up to the matched character into a group `prefix`. Then it switches to a look*ahead*, which now starts from the beginning of the string and can contain a complex pattern. *After* the character which we want to replace in that pattern, we put an optional look*behind*, which checks if the `prefix` group matches here. If it does, it captures an empty string into the `flag` group. If it doesn't, because it's optional, it doesn't affect the state of the regex engine at all and is ignored. Finally, once the lookahead is matched successfully, only the `\k<flag>` at the end is left which only matches if the flag was set at some point during the computation.

Now let's ungolf the long regex a bit by using named groups and freespacing mode:

```
.
(?<=
  (?=
    (?:
      (?=
        .*#
        (?<cycle>
          \k<cycle>?
          (?<char>)
        )
      )
      .*?
      \k<char>
      (?<=^\k<prefix>(?<flag>))?
    )+
    .*
    \k<char>$
  )
  (?<prefix>.*)
)
\k<flag>

```

I hope you recognise the general outline from above, so we only need to look at what I filled in for `...`.

We want to capture the next character in the cycle into the group `char`. We do this by also remembering the string from `#` to the current character in `cycle`. To get the next character, we use a lookahead to search for the `#`. Now we try to match `cycle` and then match the next character in `char`. This will usually be possible, unless `char` is the last character `p`. In this case, `\k<cycle>` will match the entire remainder of the string and there won't be a character left to capture into `char`. So the engine backtracks, omits the backreference to `cycle` and just matches the first character `r` instead.

Now we've got the next character in the cycle in `char`, we search for next possible occurrence of that character with `.*?\k<char>`. These are the characters we want to replace, so we put the `prefix` check after it. These steps (find the next `char` in the cycle, search for the next occurrence of it, set flag if appropriate) are now simply repeated with a `+`.

That's actually all there is to finding the cyclic subsequence, but we also need to make sure that we end on a `p`. This is fairly easy: just check that the value currently stored in `char` matches the `p` at the end of the string with `.*\k<char>$`. This also ensures that our lookup string isn't used to finish an incomplete cycle, because we need the trailing `p` for this check.
> 15 votes

# Answer
## Python 2, ~~133 130 126~~ 121 bytes

```
r=n=''
for c in input():r+='en'[c=='roygbp'[r.count('n')%6]]
for c in r:n+=['e',c][n.count('n')<r.count('n')/6*6]
print n

```

The first loop gets cycles, and the second removes an incomplete cycle

Saved 3 bytes thanks to J F and 5 from DLosc
> 7 votes

# Answer
# Perl 5, ~~76~~ 65 bytes

A pinch of pure undiluted regular expressions.
First finds what shouldn't be eaten. What remains is eatable.

```
s/r(.*?)o(.*?)y(.*?)g(.*?)b(.*?)p/n$1n$2n$3n$4n$5n/g;s/[^n\s]/e/g

```

### Test

```
$ perl -p fruitloops.pl <<<gorboypbgbopyroybbbogppbporyoygbpr
eenenneennenennneeeeneennenennnnne

```
> 3 votes

# Answer
# Lua, 101 bytes

```
s=arg[1]:gsub("r(.-)o(.-)y(.-)g(.-)b(.-)p.-","*%1*%2*%3*%4*%5*"):gsub("%w","e"):gsub("*","n")print(s)

```

Uses Lua patterns creatively; I think it's an interesting approach.

It replaces all non-eaten characters with "\*"s, replaces all alphanumeric characters with "e"s, then replaces all "\*"s with "n"s.
> 3 votes

# Answer
# Javascript (ES6), 118

```
a=>eval("b=[...a],d=0,e=b.map(f=>f=='roygbp'[d%6]?'n'[++d&0]:'e');for(i=e.length-1;i&&b[i]!='p';e[i--]='e');e.join``")

```

Fiddle tested in Firefox. I hear Chrome supports arrow functions now but I haven't tested this in Chrome yet.

Ungolfed:

```
input=>eval("
    array = [...input],
    rainbow_index = 0,
    mapped = array.map( item=>
        item == 'roygbp'[rainbow_index%6] ? 'n'[++rainbow_index&0] : 'e'
        // when we encounter an item of the rainbow, do not eat and start using
        // the next rainbow item, otherwise eat
    );
    // go through backwards and eat until we find a 'p' indicating the last
    // complete loop
    for(i = mapped.length - 1; i && array[i]!='p'; mapped[i--] = 'e');

    mapped.join``
")

```
> 2 votes

# Answer
# gawk, 96

```
{for(;c=substr("roygbp",++i,1);r=r"\\"i"n")p=p"([^"c"]*)"c;$0=gensub(p,r,"g");gsub(/[^n]/,"e")}1

```

Constructs the search pattern `"([^r]*)r([^o]*)o([^y]*)y([^g]*)g([^b]*)b([^p]*)p"` and the replacement `"\\1n\\2n\\3n\\4n\\5n\\6n"`. After that replacement it declares everything food ("e"), that's not part of a complete rainbow.

This combination automatically ensures, that no rainbows will be harmed during this operation, and no severed rainbows show up at the end.
> 2 votes

# Answer
# Pyth, 42 bytes

```
Jf-Z=+Zq@zT@"roygbp"ZUzs.e@"en"}k<J*6/lJ6z

```

Try it online: Demonstration
> 1 votes

# Answer
# CJam, 41 bytes

```
2r:R,m*{R.*s__,6/"roygbp"*=\,~*}$0="en"f=

```

Brute-force approach that tries all eat/not-eat variations and selects the one that results in the longest, valid necklace.

Try it online in the CJam interpreter.
> 1 votes

# Answer
# CJam, 50 bytes

```
l{"roygbp"T=={'nT):T;}{'e}?}%W%_'ne=6%{_'n#'et}*W%

```

Try it online

This is a little longer than some of the other submissions, but it is very efficient with linear complexity. It scans through the input string, and matches characters one by one.

The core part of the algorithm is actually fairly compact. About half of the code is for removing the incomplete cycle at the end.
> 1 votes

# Answer
# Javascript (ES6), ~~85~~ 82 bytes

The "necklace must end in a purple" rule was originally a great hurdle, increasing my score from 66 to 125, but I found a shorter way over it (thankfully!).

```
s=>(i=j=0,s.replace(/./g,x=>s.lastIndexOf`p`>=j++&x=='roygbp'[i%6]?(i++,'n'):'e'))

```

### Explanation:

This code loops through each character in the input and replaces each with `r` or `e` with this logic:

* If the character's position is \<= the last position of `p`, AND the character is the next one in the rainbow, keep it (replace it with `n`).
* Otherwise, eat it (replace it with `e`).

### Ungolfed:

```
function a(s) {
  var i=0, j=0, r='';
  t = t.replace(/./g, function (x) {
    if (s.lastIndexOf('p') >= j++ && x == 'roygbp'.charAt(i)) {
      i++;
      i %= 6;
      return 'n';
    } else {
      return 'e';
    }
  });
  return r;
}

```

Suggestions welcome!
> 1 votes

# Answer
# C90, 142-146 bytes (down to 119, depending)

Operates in linear time to efficiently eat those fruit loops that can't be part of a pretty rainbow. Then, a postprocess kills any partial loop at the end.

Here are four versions:

* Version 1 (146 bytes), call with `[name] [string]`:
`main(int a,char**b){char*v=b[1],*s="roygbp",i=0,k=0;for(;v[i];++i)if(s[k]==v[i]){++k;k%=6;v[i]='n';}else v[i]='e';while(k-->0)v[--i]='e';puts(v);}`
* Version 2 (142 bytes), call with `[name] [string] [rainbow order]`:
`main(int a,char**b){char*v=b[1],*s=b[2],i=0,k=0;for(;v[i];++i)if(s[k]==v[i]){++k;k%=6;v[i]='n';}else v[i]='e';while(k-->0)v[--i]='e';puts(v);}`
This allows you to define your own rainbow ordering with any colors you want so long as they aren't `n` or `e`. This actually makes the code shorter!
* Version 3 (123 bytes), call like version 1:
`main(int a,char**b){char*v=b[1],*s="roygbp",i=0,k=0;for(;v[i];++i)if(s[k]==v[i]){++k;k%=6;v[i]='n';}else v[i]='e';puts(v);}`
This one gives you as much of your rainbow as possible! The incomplete trailing rainbows show promise! We shouldn't eat them!
* Version 4 (119 bytes), call like version 2:
`main(int a,char**b){char*v=b[1],*s=b[2],i=0,k=0;for(;v[i];++i)if(s[k]==v[i]){++k;k%=6;v[i]='n';}else v[i]='e';puts(v);}`
Same as version 3, but MOAR RAINBOW TYPES!

Minor limitation: machine must have signed chars (the general case), and string must be fairly short. Outputs a trailing `\n` for clarity.

Version 1 is the only one that clearly passes the requirements, although version 2 is arguable. Versions 3 and 4 are less-correct (but still fun) interpretation of the question.
> 1 votes

# Answer
## Pyth, 38 bytes

I know this is significantly longer than orlp's answer, but this one runs in linear time :o)

```
u+G?qH@"roygbp"/G\n\n\e+_>_zJx_z\p*Jdk

```

Try it out here.

In brief, this program replaces all characters after the final 'p' with spaces, then iterates over each character in the resulting string. If the character is the next in the 'roygbp' sequence, print 'n', otherwise print 'e'.

```
                                          Implicit: z=input(), d=' ', k=''
                            Jx_z\p        Find number of chars after last p, store in J
                        _>_zJ             Take all but J chars of the input
                       +          *Jd     Append J spaces
u                                    k    Reduce on the above, starting with ''
               /G\n                       Count 'n' in output so far
      @"roygbp"                           Take relevant char from sequence string (modulus indexing)
   ?qH                                    Does the current char equal the above?
 +G                \n\e                   Select 'n' or 'e' as appropriate and append

```

I've struggled to find a shorter way to process the input string. `_>_zJ` in particular feels awkward, but `<Jz` doesn't give the required string when `J == 0`, i.e. when the input ends with a 'p'.
> 1 votes

# Answer
# Haskell, 138 bytes

`g` does it.

```
f(c:r)(h:t)|c==h='n':(f(r++[c])t)|0<1='e':(f(c:r)t)
f _""=""
z 'n' 'n'='n'
z a b='e'
r=reverse
g s=zipWith z(f"roygbp"s)(r$f"pbgyor"(r s))

```
> 1 votes

# Answer
# Python 2, 254 bytes

Loops!

```
i=raw_input();r='roygbp';l='r';d=''
for n in i:
 if n==l:d+='n';l=r[(r.index(l)+1)%6]
 else:d+='e'
d=list(d)[::-1];p=(r.index(l)+1)%6;
for s in range(len(d)):
 if d[s]=='n'and p-1:d[s]='e';p-=1
if d.count('n')<6:print'e'*len(d)
else:print''.join(d[::-1])

```

Excuse the pun. :P
> 0 votes

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


title: Rugby scores code golf

text:
# Question
Title: Rugby scores code golf
The Rugby World Cup starts in a few hours!

Write a program or function which, given a rugby team score as input, outputs all possible ways the score could have been attained in a Rugby game.

### Ways to score in Rugby

* **Penalty kick/Drop kick:** Both penalty kicks and a drop kicks are worth **3** points (We regroup them in this challenge to reduce the number of possibilities).
* **Try:** A try is worth **5** points.
* **Conversion:** A conversion is worth **2** points. **It can only occur if a try occurs too** (i.e. there can never be more conversions than trys in a game).

### Input

Input is a positive integer, which corresponds to the total score of one team at the end of the game. You may assume that the score is valid, i.e. it can be attained using at least one combination of ways to score described above.

### Ouput

The output for one possible way of attaining the score must look like this:

```
2K,1T,1C

```

(*the numbers can obviously change*). the number before `K` is the number of penalty kicks and/or drop kicks, the number before `T` is the number of Trys, and the number before `C` is the number of conversions.

Since you have to output all possible ways the score could have been attained, you may output them either inside a list, or separate them with line breaks (which is what I'll use in the examples below).

### Test cases

* Input: `9`

Output:

```
3K,0T,0C

```

There are no other possibilites (For example, `0K,1T,2C` would give 9 points but a conversion cannot happen without a corresponding try).

* Input: `12`

Output:

```
4K,0T,0C
0K,2T,1C

```
* Input: `19`

Output:

```
0K,3T,2C
4K,1T,1C
3K,2T,0C

```
* Input: `42`

Output:

```
14K,0T,0C
10K,2T,1C
9K,3T,0C
7K,3T,3C
6K,4T,2C
5K,5T,1C
4K,6T,0C
3K,5T,4C
2K,6T,3C
1K,7T,2C
0K,8T,1C
0K,6T,6C

```

### Scoring

This is , so the shortest code in bytes wins.

# Answer
> 4 votes
# Pyth, 42 bytes

```
V^Q3I&g@K.[Z3jNQ1eKqQs*VKj352Ts.iKc2"K,T,C

```

Try it out here.

This uses the same heuristic as Andrea Biondo's answer, in that it generates every possible combination of kicks, tries and conversions from 0 to `(n-1)`. It prints the formatted output only if `(number of tries) >= (number of conversions)` and the total score is correct.

```
                                              Implicit: Q=eval(input()), T=10, Z=0
V^Q3                                          For N in [0 - ((Q^3)-1)]:
             jNQ                                Convert N to base Q to get 3-tuple
         .[Z3                                   Left-pad the above with 0 to length 3
        K                                       Store in K
       @K       1                               K[1]
                 eK                             Last element of K (i.e. K[2])
      g                                         Rule 1: is K[1] >= K[2]?
                         j352T                  [3,5,2]
                      *VK                       By-element multiplication of K with the above
                     s                          Take the sum
                   qQ                           Rule 2: is that sum equal to the input?
    I&                                          If rules 1 & 2 are true:
                                  c2"K,T,C        ['K,', 'T,' 'C']
                               .iK                Interleave K with the above
                              s                   Concatenate into string and output

```

# Answer
> 5 votes
## Python 3, 113 104 bytes

```
a=int(input());print(['%sK,%sT,%sC'%(i%a,i/a%a+i%a,i%a)for i in range(a**3)if i%a*3+i/a%a*5+i/a/a*7==a])

```

First attempt at code golf. Brute force list comprehension. I'm assuming the list output is acceptable?

Counting tries + conversion as 7 points removes the if statement. Inspired by xor's python 2 answer.

Try it here

# Answer
> 4 votes
# R, ~~135~~ ~~126~~ 124 bytes

```
n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n"))

```

Quick explanation:

```
n=scan()                            # Takes input from stdin
a=expand.grid(k=0:n,t=0:n,c=0:n)    # Creates matrix of all possible combinations of 3 integers from 0 to n
with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,], # Only keeps the one that produced a correct score
     cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n")) # Prints

```

Usage:

```
> n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n"))
1: 9
2:
Read 1 item
3K,0T,0C
> n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n"))
1: 42
2:
Read 1 item
14K,0T,0C
9K,3T,0C
4K,6T,0C
10K,2T,1C
5K,5T,1C
0K,8T,1C
6K,4T,2C
1K,7T,2C
7K,3T,3C
2K,6T,3C
3K,5T,4C
0K,6T,6C

```

# Answer
> 3 votes
# CJam, 48 bytes

Quite slow, just generates all possible combination of values from `0` to `score - 1` for K, T and C. Then filters out the ones where the sum isn't right or `C > T`.

```
qi:X,3m*{_)\1=)<\[Z5Y].*:+X=&},::s"KTC"f.+',f*N*

```

Try it online.

# Explanation

```
qi:X                                             e# Take input as integer, assign to X
    ,3m*                                         e# Cartesian power [0 ... input-1]^3
        {                    },                  e# Keep values if:
         _)\1=)<                                 e#    Conversions <= Tries
                            &                    e#    AND
                \[Z5Y].*:+X=                     e#    Sum([k t c]*[3 5 2]) == X
                               ::s               e# [k t c] -> ["k" "t" "c"]
                                  "KTC"f.+       e# Vector append -> ["kK" "tT" "cC"]
                                          ',f*   e# Join with comma
                                              N* e# Join outer list with newline

```

# Answer
> 3 votes
# R, ~~113~~ 101 bytes

Not quite as elegant as @plannapus's answer. Go the All Blacks :)

```
n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='')

```

Test run

```
> n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='')
1: 9
2:
Read 1 item
3K,0T,0C
> n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='')
1: 12
2:
Read 1 item
4K,0T,0C
0K,2T,1C
> n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='')
1: 42
2:
Read 1 item
14K,0T,0C
9K,3T,0C
4K,6T,0C
10K,2T,1C
5K,5T,1C
0K,8T,1C
6K,4T,2C
1K,7T,2C
7K,3T,3C
2K,6T,3C
3K,5T,4C
0K,6T,6C

```

# Answer
> 3 votes
## Python 2, 93

```
lambda n:["%dK,%dT,%dC"%(k/n/n,k%n+k/n%n,k%n)for k in range(n**3)if k%n*7+k/n%n*5+k/n/n*3==n]

```

An anonymous function. Generates all possible triples of values by converting a value `k` from `0` to `n^3-1` to base `n`. Filters for those with the right sum. Try+conversion is considered a separate 7-point play, and the number of tries includes those too.

# Answer
> 2 votes
# Haskell, ~~102~~ 88 bytes

```
a#b=show a++b
f n=[k#"K,"++t#"T,"++c#"C"|q<-[[0..n]],k<-q,t<-q,c<-q,3*k+5*t+2*c==n,t>=c]

```

Usage example: `f 19` -\> `["0K,3T,2C","3K,2T,0C","4K,1T,1C"]`.

Edit: output in list format seems to be ok ...

# Answer
> 2 votes
# Ruby, 89

```
->s{(s*s).times{|i|c=s-3*(k=i%s)-5*t=i/s
c%2>0||c<0||c/2>t||puts("#{k}K,#{t}T,#{c/2}C")}}

```

call like this:

```
g=->s{(s*s).times{|i|c=s-3*(k=i%s)-5*t=i/s
c%2>0||c<0||c/2>t||puts("#{k}K,#{t}T,#{c/2}C")}}

g.call(gets.to_i)

```

Loops through all possible K and T and calculates the score from conversions that is required.

If the score for conversions is not invalid, print the K,T,C combination that has been found.

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


title: Counting the Endpoints of an ASCII Art

text:
# Question
Title: Counting the Endpoints of an ASCII Art
You should write a program or function which receives a string representing an ASCII art as input and outputs or returns the number of endpoints in the input.

The input will consist of the characters `space - | +` (with 0, 2, 2 and 4 endpoints respectively) and linebreaks. E.g.:

```
-|++-
  +

```

Two adjacent characters are connected and hence lose 1 endpoint each in the following cases:

```
--  -+  +- |  |  +  +  ++
           |  +  |  +

```

The first example has

```
2+2+2+2+1+
    3        = 12

```

endpoints.

## Input

* Input will be a string consisting of the characters space, `-`, `|`, `+` and newline.
* Input length can be 0 length and any input matching the above description is valid (in regex input is `[ -+|\n]*`).
* Trailing newline is optional.

## Output

* A single non-negative integer, the number of endpoints.

## Examples

Outputs are after the last row of their inputs.

```
+
4

-|++-
  +
12

+--+
|  |
+--+
8

  |  |
  +--+-- |||
12

--++
 |||--
10

<empty input>
0

|
|
2

--
++--
 ++
   --+
  +++ ||

 ----
30

```

This is code golf so the shortest entry wins.

# Answer
# Snails, 29

```
A
\+|\-)lr!\-|(\+|\|)n!\|}!\+

```

I added line comments with `,,`, in order to make a commented version.

```
A                    ,, Count all accepting paths
        \+ | \- )    ,, Literal '+' or '-'
        lr           ,, Set direction to left or right
        !\-          ,, Assert next char is not '-'
    |                ,, Or...
        ( \+ | \| )  ,, Literal '+' or '|'
        n            ,, Turn 90 degrees right or left (from initial direction right)
        !\|          ,, Assert next char is not '|'
}                    ,, Group everything previous
!\+                  ,, Assert next char is not '+'

```
> 11 votes

# Answer
# JavaScript (ES6), 168

Using template strings, all newlines are significant and counted.

Test running the snippet below in Firefox. (Chrome still does not support `...`)

```
f=s=>`
${s}
`.split`
`.map((r,y,s,v=c=>c>' '&c!='-',h=c=>c>' '&c<'|')=>[...r].map((c,x)=>t+=(v(c)?2-v(s[y-1][x])-v(s[y+1][x]):0)+(h(c)?2-h(r[x-1])-h(r[x+1]):0)),t=0)&&t

// Less golfed
u=s=>{
  s = ('\n' + s + '\n').split('\n'); // split in rows, adding a blank line at top and one at bottom
  t = 0; // init counter
  v = c => c>' ' & c!='-'; // function to check if a character has vertical end points
  h = c => c>' ' & c<'|'; // function to check if a character has horizontal end points
  s.forEach( (r,y) =>
    [...r].forEach( (c,x) => {
     if (v(c)) // if current character has vertical endpoints, check chars in previous and following row
        t += 2 - v(s[y-1][x]) - v(s[y+1][x]);
     if (h(c))  // if current character has horizontal endpoints, check previous and following chars in row
        t += 2 - h(r[x-1]) - h(r[x+1]);
    })
  )
  return t
}

//TEST
out=x=>O.innerHTML+=x+'\n'

;[
 [`+`,4]
,[`-|++-
  +`,12]
,[`+--+
|  |
+--+`,8]
,[`  |  |
  +--+-- |||`,12]
,[`--++
 |||--`,10]
,[``,0]
,[`
|
|`,2]
,[`
--
++--
 ++
   --+
  +++ ||

 ----`,30]
].forEach(t=>{ r=f(t[0]),k=t[1],out('Test '+(r==k?'OK':'Fail')+'\n'+t[0]+'\nResult:'+r+'\nCheck:'+k+'\n') })
```

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

# Answer
# Python 2, 123

```
l=[]
i=p=t=0
for c in input():
 l+=0,;h=c in'-+';t+=h>p;p=h;v=c in'|+';t+=v>l[i];l[i]=v;i+=1
 if' '>c:l=l[:i];i=0
print t*2

```

A one-pass method. Takes as input a string with linebreaks.

For the horizontals, the idea is to count the number of horizontal segments, each of which has two endpoints. A segment starts whenever a character is one of `+-` (boolean `h`) but the previous one isn't (boolean `p`).

For the verticals, we'd like to do the same thing on the transposed input, looking at runs of `+|`. Unfortunately, Python's transposing is really clunky. It requires something like `map(None,*s.split('\n'))` to fill in the blanks with `None`, which are also themselves to deal with.

Instead, we do the vertical count while iterating horizontally. We keep a list `l` of which columns indices are still "running", i.e. where that the previous character in that column connects down. Then, we do the same thing as with the horizontal, counting newly starting vertical segments. When we hit a newline, we cut off the list right of where we are, since all segments to the right were broken, and reset the current index to `0`.
> 3 votes

# Answer
# CJam, ~~66~~ ~~62~~ 61 bytes

```
q_N/_z,S*f.e|zN*"-|++"2$fe=1b"|-"{'++:R:a@+2ew{aR2m*&},,-}/2*

```

Try it online in the CJam interpreter.

### Idea

We can compute the endpoints as follows:

1. Count the number of `-`s, `|`s and `+`s in the input.
2. Multiply the last one by 2 and add the results.
3. Count the number of `--`s, `-+`s, `+-`s and `++`s in the rows.
4. Count the number of `||`s. `|+`s, `+|`s and `++`s in the columns.
5. Subtract the results from 3 and 4 from the result from 2.
6. Multiply the result from 5 by 2.

### Code

```
q        e# Read all input from STDIN.
_N/      e# Push a copy and split it at linefeeds.
_z,      e# Count the number of rows of the transposed array.
         e# This pushes the length of the longest row.
S*       e# Push a string of that many spaces.
f.e|     e# Perform vectorized logical OR with the rows.
         e# This pads all rows to the same length.
zN*      e# Transpose and join, separating by linefeeds.
"-|++"   e# Push that string.
2$       e# Copy the original input.
fe=      e# Count the occurrences of '-', '|', '+' and '+' in the input.
1b       e# Add the results.
"|-"{    e# For '|' and '-':
  '++    e#   Concatenate the char with '+'.
  :R     e#   Save the resulting string in R.
  :a     e#   Convert it into an array of singleton strings.
  @      e#   Rotate one of the two bottom-most strings on top of the stack.
         e#   This gets the transposed input for '|' and the original input for '-'.
  +      e#   Concatenate both arrays.
         e#   This pads the input with nonsense to a length of at least 2.
  2ew    e#   Push a overlapping slices of length 2.
  {      e#   Filter the slices; for each:
    a    e#     Wrap it in an array.
    R2m* e#     Push the second Cartesian power of R.
         e#     For '|', this pushes ["||" "|+" "+|" "++"].
    &    e#     Intersect.
  },     e#   If the intersection was non-empty, keep the slice.
  ,      e#   Count the kept slices.
  -      e#   Subtract the amount from the integer on the stack.
}/       e#
2*       e# Multiply the result by 2.

```
> 3 votes

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


title: Shuffling evenly

text:
# Question
Title: Shuffling evenly
Some trading cards have real value and can be sold for money. Bending the cards is frowned upon because it takes away their value and makes them look less new. Say you have a deck of trading cards (Pokemon, Magic, etc.) and you want to shuffle them. Instead of doing the bridge that bends all of the cards, another simple way to shuffle cards is to put them into piles. Here's what I mean.

# Background

With a 60 card deck in need of shuffling, you could separate the 60 cards into three piles of 20 cards. There are multiple ways to do this, the most plain being to put a card into pile A, then one into pile B, then one into pile C. Another way is to put a card into pile C, then B, then A. There are also ways to spread the cards across the piles unevenly. Here's one: put a card in pile A, put another card in A, then put a card in pile B, then put a card in pile C.

# Challenge

Create a full program that will output `even` if a certain way to shuffle into piles spreads the cards in the piles evenly, and outputs `uneven` and the number of cards in each pile otherwise.

# Input

Input will be taken through STDIN or the closest alternative (no functions).

```
[sequence] [deck size]

```
* `sequence` is a string of characters. It tells the pattern the cards are laid down into the piles. Each different character corresponds to a single pile. This string will always be under the deck size and will contain only capital letters A-Z.
* `deck size` is an integer that specifies how many cards are in the deck. If deck size is 60, the number of cards in the deck is 60.

# Output

```
even

```

If the number of cards in each pile at the end of the shuffle are the same, your program should output this.

```
uneven [pile1] [pile2] [...]

```

If the number cards in each pile at the end of the shuffles are the not the same, your program should output `uneven` and the number of cards in each pile like this: `uneven 20 30` if pile A contains 20 canrds and pile B contains 30. The order of the pile numbers does not matter.

# Other information

* This is a code golf challenge, so the shortest code in bytes on September 25 wins. If there is a tie in byte counts, the code that was submitted first wins.
* Your program must be a program, not a function.
* If possible, please include a link to an online interpreter or a link to a place where I can download an interpreter for your language in your answer.
* Anything I do not specify within this challenge is fair game, meaning if I don't say it, it's up to you. If anything is vague, tell me and I will edit the answer accordingly. (Hopefully this goes more smoothly than my last challenge.)

# Examples

```
     Input | Output | Alternate outputs (if uneven)
           |
    ABC 30 | even
    ABC 31 | uneven 11 10 10 | uneven 10 11 10 | uneven 10 10 11
    BCA 60 | even
    BBA 24 | uneven 8 16 | uneven 16 8
ABACBC 120 | even
  BBABA 50 | uneven 20 30 | uneven 30 20
  AABBB 12 | even

```

# Answer
> 5 votes
# Pyth, 33 31 bytes

```
jd+>"uneven"yK!tl{J/L@LzQ{z*J!K

```

Example input:

```
ABACBC
120

```

# Answer
> 4 votes
# Python 3.x, 106 ~~128~~ ~~138~~ bytes

```
s,n=input().split()
n=int(n)
t=(s*n)[:n]
*z,=map(t.count,set(t))
b=z[:-1]!=z[1:];print("un"*b+"even",*z*b)

```

This duplicates the input sequence (more times than needed, which is good enough) and then takes only the first `n` characters. These are counted and either `uneven` or `even` is chosen, and if the former, the counts also are printed with `print(*z)`, which automatically unpacks `z` for me.

Saved 32 bytes thanks to xnor and Sp3000!

Also, **Python 3.5** has a new feature that allows this 102 byte solution:

```
s,n=input().split()
n=int(n)
t=(s*n)[:n]
*z,=map(t.count,{*t})
b=len({*z})>1;print("un"*b+"even",*z*b)

```

`len({*z})>1` unpacks the list `z`, makes a set from it, then checks to see if it has more than one element. It is `{*z}` specifically that's new.

# Answer
> 2 votes
# CJam, 35 bytes

```
rri_@*<$e`0f=_)-"uneven":Ua@+S*U2>?

```

Try it online in the CJam interpreter.

### How it works

```
rri      e# Read a string (s) and an integer (n) from STDIN.
_@       e# Push a copy of n and rotate s on top of it.
*        e# Repeat s n times.
<        e# Keep only the first n characters.
$e`      e# Sort and perform run-length encoding.
0f=      e# Keep only the multiplicities.
_)-      e# Push a copy, pop the last element and remove its remaining occurrences.
         e# The result with be an empty array (falsy) iff all elements are equal.
"uneven" e# Push that string.
:Ua      e# Save it in U and wrap it in an array.
@+       e# Concatenate ["uneven"] with the array of multiplicities.
S*       e# Join, separating by spaces.
U2>      e# Push "even".
?        e# Select the result depending on whether _)- pushed an empty array.

```

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


title: Tips for golfing ASCII art

text:
# Question
Title: Tips for golfing ASCII art
I think the ASCII art questions on PPCG are fun to do, but personally I think it can be pretty hard, especially when the question is tagged as .

I wonder if anyone here might have some tips that will be useful for producing ASCII art.

Simply arranging characters is easy, but with (short) algorithms, things will become more complicated.

I'm talking about ASCII art like:

* Text to ASCII art (characters)
* Images (logos or icons)

I'm just looking for general tips, but language-specific is allowed since most of them can be translated anyhow.

# Answer
> 8 votes
## Compression algorithms

You can apply LZMA compression to the string.
Many languages support it.

## Run-length encoding

You can use processing instructions such as `[char][number]` (e.g. `b12`).
This compression algorithm is used here: https://codegolf.stackexchange.com/a/20589/10920

Further reading: http://en.wikipedia.org/wiki/Run-length\_encoding

## Integer packing

You can use arrays of integers to store small shapes such as:

```
// This is an invader!
// (SE line height makes it looks awful)
// ~158 characters

    ##          ##
      ##      ##
    ##############
  ####  ######  ####
######################
##  ##############  ##
##  ##          ##  ##
      ####  ####

```

Each space will be translated into a `0`.
Each sharp will be translated into a `1`.

```
// ~58 characters
// Saved ~100 bytes!
[
  196656,  49344,   262128,  999228,
  4194303, 3407859, 3342387, 62400
]

```

Each bit is then read using bitwise operator `&`.

The above algorithm could be improved by using a bigger integer base:

```
// ~44 characters
// Integers are in base 36.
// Use `_` as a separator (or a line break).
"47qo_122o_5m9c_lf0c_2hwcf_211ir_1zn03_1c5c"

```

# Answer
> 5 votes
## Look for symmetry

Sometimes the required ASCII art is symmetric at some point. For example, Argyle ASCII Art requires an output similar to this:

```
    /\        /\
   /  \  /\  /  \
/\/    \/  \/    \/\
\/\    /\  /\    /\/
   \  /  \/  \  /
    \/        \/

```

One could just print this normally, but depending on the language, the code required can be shortened by only generating the top half of the result, reversing it and swapping `/` and `\`.

## Try transposing

In ASCII Art Archery Arrows the result to print is this, scaled to a given `n`:

```
     /\
    /  \
   /    \
  /      \
  \      /
   \____/
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
   /|  |\
  / |  | \
 /  |  |  \
/   |  |   \
/   |  |   \
/   |__|   \
/  /    \  \
/ /      \ \
//        \\
/          \

```

If we take a look at the arrow, we can see there's 8 kinds of lines:

```
/ \
\ /
\_/
| |
/ | | \
/ |_| \
/ / \ \
/ \

```

Let's try the same for its transpose.

```
                         ///////
                        /     /
   /\                  /     /
  /  \                /     /
 /   _||||||||||||||||||||||
/    _                     _
\    _                     _
 \   _||||||||||||||||||||||
  \  /                \     \
   \/                  \     \
                        \     \
                         \\\\\\\

```

Here, there are 10 kinds of lines.

```
/
/ /
/ \ / /
/ _|
/ _ _
\ _ _
\ _|
\ / \ \
\ \
\

```

But here's the catch: the bottom 5 are identical to the top 5, except for swapping `/` and `\`. As per the previous rule, you can first generate the first 5, copy, do the swap, and finally transpose to get the arrow. This can save a lot of code.

# Answer
> 5 votes
# Control characters, escape sequences and console codes

Unless the question forbids them, the current consensus on Meta is that ASCII art challenges do not require a specific byte stream, but output that looks correct.

This means that we can use ASCII control characters, ANSI escape sequences and Linux console codes in our answers, assuming a supporting terminal.

Unless specified otherwise, the rest of this answer will explain the behavior of Linux terminals, which is what I have available for testing right now.

### ASCII control characters

Support/interpretation varies from terminal to terminal and character to character. The most portable one ought to be the linefeed (`\n`, `\x0a`), which moves the character to the beginning of the next line.

Other useful characters include:

* The vertical tab (`\v`, `\x0b`) moves the cursor one position to the right, then one position down.

```
$ echo -e 'a\vb'
a
 b

```
* The carriage return (`\r`, `\x0d`) moves the cursor to the beginning of the *current* line. Any subsequent printable character will overwrite the first character of the current line.

```
$ echo -e 'ab\rc'
cb

```
* The backspace (`\b`, `\x08`) moves the cursor one position to the left. Any subsequent printable character will overwrite the character before the backspace.

```
$ echo -e 'ab\bc'
ac

```
* The escape (`\e`, `\x1b`) does nothing on its own, but forms part of ANSI escape sequences (optionally) and Linux console codes.

Many languages permit actual control characters in the source code.

### ANSI escape sequences

(yet to come)

### Linux console codes

While there are many more, the most useful console codes for ASCII art are probably these:

* The sequence `\ec` will *reset* the terminal. This clears the screen, moes the cursor the upper left corner and sets fore- and background color, cursor blinking rate, etc. to their default values.
* The sequence `\eM` causes a *reverse linefeed*, i.e., the cursor will move one position up.

```
$ echo -e '\na\eMb\n'
 b
a

```
* The sequence `\eH` sets the *tab stop* at the current column.

```
$ echo -e '   \eHa\n\tb'
   a
   b

```

# Answer
> 2 votes
## Look for patterns

This one might be a bit obvious, but... look for patterns, similarities and repetitions in the output. For instance, when I saw the Transform number into 7-segment display pattern task I started thinking about how one could golf it, and started looking for similarities. Due to the way the horizontal segments go between the vertical ones in the character matrix it'd probably be easiest to deal with three segments at a time, grouped together as such (adding two "always empty" segments for the first, topmost one):

Thus, you could do something like `lc + " "*N + rc + "\n"` N-1 times and then `lc + bc*N + rc` once, for every three segments (`lc`, `bc`, `rc` being the left-, bottom-, and right-segment characters, i.e. one of `|`, `_` or ).

# Answer
> 2 votes
# Use base conversion

This answer was to a question which wanted ASCII art which consisted of the characters `+ |-` and newlines. Since there are only 5 possible characters, these can be treated as a base 5 number and converted to bytes, packing 3.45 characters per byte.

# Exploit regularities

Often, the data will have some regularities, even if those regularities aren't strong enough to employ specific tools such as mirroring. For instance, in the above question, the desired output had newlines roughly evenly spaced throughout the test, since the text was roughly rectangular. I exploited this to shorten my code, by using Pyth's split into n pieces function, then joining on newlines.

# Know your tools, and choose the right one for the job.

The most powerful and efficient text processing tools I know are:

Regex engines: `///`, Retina, Perl, in order of power/conciseness tradeoff.

Use if the thing you want to do can be conscisely described in regex substitutions, such as this answer

Obscure text-processing tools: gema, etc. (I'm sure there are others, but they're too obscure)

Use if they have a feature that is exactly what you need, that nothing else has. Such as in this question, with gema's recursive matching.

General code golfing languages: CJam, Pyth, etc.

Use if you're exploiting some subtlety complex enough that no other tool will do the job or it just does the job shorter.

# Try many approaches

This applies in every code-golf question, but especially here. You're not going to know whether a regularity is exploitable until you try it out. Possibly in multiple languages.

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


title: The Truck Problem

text:
# Question
Title: The Truck Problem
I am a teacher who was given a problem a few years ago. Every year since I have given it to my advanced students as a bonus assignment, but in ~10 years only 8 solved it, each with a slightly different approach. The problem is as follows:

You have some input **(from stdin)**, in the following format (the `//comments` are not included in the input):

```
6      //Route Begin
1 2    //Route data...
1 3
3 4
3 5
4 6
5 6
2 3
2 4
0 0    //Route end
4      //Route Begin
2 3    //Route Data...
3 4
5 1
1 6
7 8
8 9
2 5
5 7
3 1
1 8
4 6
6 9
0 0    //Route end
// continued...

```

The input begins with the destination, an integer. It is followed by a 'map' of all streets in the city. Each line represents a connection, so you can get from street 1 to street 2, and vice-versa. On every rout you start at street 1, then work your way to your destination.

**The objective:** List all possible routes, and tell the user the shortest one (least amount of street changes). Also, the code beads to be human readable. So you would wont to output something like:

```
Destination 1 (6):
1 2 3 4 6
1 2 3 5 6
1 2 4 3 5 6
1 2 4 6
1 3 2 4 6
1 3 4 6
1 3 5 6
There are 7 routes from the truck station to street 6.
The shortest of these is the route "1 2 4 6", with 4 streets.

Destination 2 (4):
1 3 2 5 7 8 9 6 4
1 3 4
1 5 2 3 4
1 5 7 8 9 6 4
1 6 4
1 6 9 8 7 5 2 3 4
1 8 7 5 2 3 4
1 8 9 6 4
There are 8 routes from the truck station to street 4.
The shortest of these is the route "1 3 4", with 3 streets.

```

Now personally, I rather java or python (and java is preferred more), but I leave this open ended to my students, so they can choose any language they like.

The original document is here

**HOW TO WIN:** Create the described program in a readable programming language, with the following criteria: \- Readable \- takes the input from the user(stdin/file) \- Is mildly easy to understand.

# Answer
**Javascript (1159)**

```
function h(g,e){var b=[],d=0,c=null,f=0;g.split("\n").forEach(function(a){a=a.replace(/\s*\/\/.*?$/,"");switch(d){case 0:c={};f=a;d++;break;case 1:a=a.split(" "),"0"===a[0]&&"0"===a[1]?(b.push(c),a=[],k(f,c,null,null,a),e.push([f,a]),d=0):(c[a[0]]||(c[a[0]]=[]),c[a[1]]||(c[a[1]]=[]),c[a[0]].push(a[1]),c[a[1]].push(a[0]))}})}
function k(g,e,b,d,c){b||(b="1",d=[]);d.push(b);var f=[];if(g!=b){if(e[b].forEach(function(a){-1==d.indexOf(a)&&(a=k(g,e,a,d.slice(),c))&&f.push(a)}),f.length)return f}else return c.push(d),d}
(function(g,z){var e=[];h(g,e);e.forEach(function(b){document.write("Destination "+b[0]+z);var d=99,c=-1;b[1].forEach(function(b,a){document.write(b.join(", ")+z);b.length<d&&(d=b.length,c=a)});document.write("There are "+b[1].length+" routes from the fire station to street "+b[0]+z);document.write('The shortest of these is the route "'+b[1][c].join(" ")+'", with '+d+" streets"+z)})})("6      //Route Begin\n1 2    //Route data...\n1 3\n3 4\n3 5\n4 6\n5 6\n2 3\n2 4\n0 0    //Route end\n4      //Route Begin\n2 3    //Route Data...\n3 4\n5 1\n1 6\n7 8\n8 9\n2 5\n5 7\n3 1\n1 8\n4 6\n6 9\n0 0    //Route end\n// continued...\n","<br>");
```

notes:

* Just used "regular" javascript code, then minified it using Closure Compiler
* Route data embedded, could have been alot shorter without a "parser". That would mean the data should be JSON encoded ..

Unminified version (added per request):

```
function parseInput(input, data)
{
    var output = [];
    var lines = input.split("\n");
    var state = 0;
    var route = null;
    var routeDest = 0;
    lines.forEach(function(val){
        val = val.replace(/\s*\/\/.*?$/, "");

        switch(state)
        {
            case 0:
                route = {};
                routeDest = val;
                state++
            break;
            case 1:
                var conn = val.split(" ");
                if (conn[0] === "0" && conn[1] === "0")
                {
                    output.push(route);
                    var innerData = [];
                    calculateRoutes(routeDest, route, null, null, innerData);
                    data.push([routeDest, innerData]);
                    state = 0;
                }
                else
                {
                    if (!route[conn[0]])
                    {
                        route[conn[0]]=[]
                    }
                    if (!route[conn[1]])
                    {
                        route[conn[1]]=[]
                    }

                    route[conn[0]].push(conn[1]);
                    route[conn[1]].push(conn[0]);
                }
            break;
        }
    });

    return output;
}

function calculateRoutes(dest, data, curr, from, returnData)
{
    if (!curr)
    {
        curr = "1";
        from = [];
    }

    from.push(curr);

    var routes = [];

    if (dest != curr)
    {
        data[curr].forEach(function(val){
            if (from.indexOf(val) == -1)
            {
                var route = calculateRoutes(dest, data, val, from.slice(), returnData);
                if (route)
                {
                    routes.push(route);
                }
            }
        });

        if (routes.length)
        {
            return routes;
        }
    }
    else
    {
        returnData.push(from);
        return from;
    }
}

function printRoutes(routeInfo)
{
    var data = [];
    parseInput(routeInfo, data);

    data.forEach(function(val){
        console.log("Destination " + val[0]);
        var shortLen = 99;
        var shortId = -1;
        val[1].forEach(function(ele, id){
            console.log(ele.join(", "));
            if (ele.length < shortLen)
            {
                shortLen = ele.length;
                shortId = id;
            }
        });
        console.log("There are " + val[1].length + " routes from the fire station to street " + val[0]);
        console.log("The shortest of these is the route \"" + val[1][shortId].join(" ") + "\", with " + shortLen + " streets");
    });
}

var nl = "\n"

printRoutes("6      //Route Begin" + nl +
    "1 2    //Route data..." + nl +
    "1 3" + nl +
    "3 4" + nl +
    "3 5" + nl +
    "4 6" + nl +
    "5 6" + nl +
    "2 3" + nl +
    "2 4" + nl +
    "0 0    //Route end" + nl +
    "4      //Route Begin" + nl +
    "2 3    //Route Data..." + nl +
    "3 4" + nl +
    "5 1" + nl +
    "1 6" + nl +
    "7 8" + nl +
    "8 9" + nl +
    "2 5" + nl +
    "5 7" + nl +
    "3 1" + nl +
    "1 8" + nl +
    "4 6" + nl +
    "6 9" + nl +
    "0 0    //Route end" + nl +
    "// continued..." + nl);

```

The unminified version uses `console.log` for output instead of `document.write`. Because `document.write` gives a better experience as a code snippet than `console.log`.
> 2 votes

---
Tags: popularity-contest, sorting, puzzle-solver, path-finding
---


title: Bounce Dynamics

text:
# Question
Title: Bounce Dynamics
# The Challenge

Write a program that can calculate how many times and how long a ball will bounce based on a few input variables.

---

# Input

There are three variables that will be passed. You can accept these however you like (user input, function call, etc). The variables are as follows:

1. height
2. velocity
3. "bounciness"

They must be passed in this order.

---

### Height

Height will be expressed as an integer, `H`, where `10^6 ≥ H ≥ 10`. The height is measured in arbitrary units, `u`, which have no effect on your program's output.

---

### Velocity

The velocity of the ball will be represented by an integer, `V`, where `10^6 ≥ V ≥ 1`. It is expressed as `Vu/s` (`V` units per second).

---

### Bounciness

The "bounciness" will be expressed as a decimal, `B`, where `0.00 ≤ B < 1.00`. The maximum precision of `B` will be the hundredths place (two digits after the decimal point).

---

# Output

You output will be two integers representing:

* number of times the ball will bounce before coming to rest, `N`
* how long it takes the ball to complete all of these bounces, `T`

---

# Calculation

To calculate the number of times the ball will bounce, you would continuously multiply the current height by the "bounciness" until it dipped below `1`. Once the result gets below `1`, you should round the height down to `0`, and stop calculating.

Each time these two are multiplied, the time is incremented by the quotient of the current height and velocity.

Intermediary calculations should have a minimum precision to the ten-thousandths (four digits after the decimal).

---

# Example 1

If the input is:

```
10 10 0.5

```

The following table shows the necessary calculations for each bounce:

```
Height          Next       Height             Bounces
------        -------      ------             -------
10.0000       10.0000    *   0.5    = 5.0000        1
 5.0000        5.0000    *   0.5    = 2.5000        1
 2.5000        2.5000    *   0.5    = 1.2500        1
 1.2500        1.2500    *   0.5    = 0.6250        1

                                              -------
                                Total Bounces:      4

   Time added
----------------
10.0000    /  10   =   1.0000
 5.0000    /  10   =   0.5000
 2.5000    /  10   =   0.2500
 1.2500    /  10   =   0.1250

                       ------
           Total Time: 1.8750

```

At this point, the computation terminates because the height is less than `1`. The time is rounded up to yield `2`. These two integers should then either be returned or output as a string in this form:

```
4 2

```

---

# Example 2

If the input is:

```
50 15 0.7

```

The following table shows the necessary calculations for each bounce:

```
Height      Next                  Height     Bounces
------     -------                -------    -------
50.0000    50.0000  *   0.7    =  35.0000          1
35.0000    35.0000  *   0.7    =  24.5000          1
24.5000    24.5000  *   0.7    =  17.1500          1
17.1500    17.2500  *   0.7    =  12.0050          1
12.0050    12.0050  *   0.7    =   8.4035          1
 8.4035     8.4035  *   0.7    =   5.8825          1
 5.8825     5.8825  *   0.7    =   4.1177          1
 4.1177     4.1177  *   0.7    =   2.8824          1
 2.8824     2.8824  *   0.7    =   2.0177          1
 2.0177     2.0177  *   0.7    =   1.4124          1
 1.4124     1.4124  *   0.7    =   0.9887          1

                                            --------
                              Total Bounces:      11

Time added
-----------
50.0000    /  15   =     3.3333
35.0000    /  15   =     2.3333
24.5000    /  15   =     1.6333
17.1500    /  15   =     1.1433
12.0050    /  15   =     0.8003
 8.4035    /  15   =     0.5602
 5.8825    /  15   =     0.3922
 4.1177    /  15   =     0.2745
 2.8824    /  15   =     0.1922
 2.0177    /  15   =     0.1345
 1.4124    /  15   =     0.0942

                     ----------
          Total Time:   10.8913

```

At this point, the computation terminates because the height is less than `1`. The time is rounded up to give `11`. These two integers should then either be returned or output as a string in this form:

```
11 11

```

# Scoreboard

For your score to appear on the board, it should be in this format:

```
# Language, Score

```

Or if you earned a bonus:

```
# Language, Score (Bytes - Bonus%)

```

```
function getURL(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(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58319,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# CJam, ~~31~~ ~~28~~ 29 bytes

Latest version rounds up time to next integer. I had missed that in the requirements. This adds 2 bytes, and saves 1 byte based on a suggestion by Dennis.

```
l~_3$W#2$mLm]@1$#(@(/@/@*m]S\

```

Try it online

Thanks to @ThomasKwa for suggesting the use of `mL` instead of the quotient of two separate logarithms.

This uses basic log laws for calculating the number of bounces, and then the sum of a geometric series, which I had to look up on Wikipedia.

Explanation:

```
l~    Get and interpret input.
_     Copy B, will need this later.
3$    Get copy of H to top.
W#    Calculate H^-1 = 1/H as double.
2$    Get copy of B to top.
mL    Log with base.
m]    Ceiling. This is the number of bounces N.
@     Rotate one copy of B to top.
1$    Copy number of bounces to top.
#     Exponent B^N.
(     Subtract 1.
@     Get other copy of B to top.
(     Subtract 1.
/     Divide the two values.
@/    Rotate V to top and divide.
@*    Get H to top and multiply. This is T.
m]    Ceiling for time.
S\    Swap a space between the two resulting values.

```
> 2 votes

# Answer
# Python2, 84 82 bytes

```
from math import*
h,v,b=input()
n=ceil(-log(h,b))
print ceil(h*(b**n-1)/(b-1)/v),n

```

Closed forms, yay!
> 6 votes

# Answer
# TI-BASIC, 35

```
Prompt H,V,B
-int(logBASE(H,B
Disp -int(H/V(B^Ans-1)/(1-B
Ans

```

A port of orlp's Python answer.
> 4 votes

# Answer
## CoffeeScript, 62 bytes

```
f=(h,v,b,n=t=0)->(t+=h/v;h*=b;n++)while 1<=h;n+' '+Math.ceil t

```
> 3 votes

# Answer
# Pyth, 27 bytes

```
L_/b1y_c*Qt^KvwJy.lQK*vwtKJ

```

Direct port of my Python answer. Takes input in the following format:

```
h
b
v

```
> 2 votes

# Answer
## PHP, 87 bytes

Takes three command line arguments.

```
<?for($h=$argv[1],$n=$t=0;$h=>1;$n++){$t+=$h/$argv[2];$h*=$argv[3];}echo"$n ".ceil($t);

```
> 1 votes

---
Tags: code-golf, math, number
---


title: Avast, ye scallywags!

text:
# Question
Title: Avast, ye scallywags!
Blackbeard was an English pirate of the early 18th century. Although he was known for looting and taking ships, he commanded his vessels with the permission of their crews. There are no accounts of him ever harming or murdering his captives.

This challenge is in honor of the infamous Blackbeard and inspired by International Talk Like a Pirate Day (September 19). It is also the inverse of this challenge by Pyrrha.

---

# The Challenge

Create a program that takes a treasure map as an input (composed of the characters listed below), and outputs it's directions.

---

# Input

All inputs will consist of `v`, `>`, `<`, `^`, whitespace, and a single `X`.

You can assume the following:

* the map will never loop or cross itself
* the starting arrow will always be the bottommost character in the leftmost column
* there will always be a treasure (`X`)

A sample input is shown below.

```
  >>v   >>>>>>v
  ^ v   ^     v
  ^ v   ^   v<<
  ^ v   ^   v
  ^ >>>>^   >>X
  ^
>>^

```

---

# Output

The output should be a `", "`-delimited string of directions. Below is the correct output from the above map.

```
E2, N6, E2, S4, E4, N4, E6, S2, W2, S2, E2

```

A single trailing newline or space is permitted.

---

# Examples

```
In:
>>>>>>>>>>>>>>>v
               v
               v
               >>>>X

Out:
E15, S3, E4

In:
>>>>>>v
^     v
^     >>>>X

Out:
N2, E6, S2, E4

In:
X
^
^
^

Out:
N3

In:
>>>>>>v
^     v
^     v
      v
      >>>>>>X

Out:
N2, E6, S4, E6

In:
 X
 ^
 ^
>^

Out:
E1, N3

In:
>X

Out:
E1

In:
v<<<<<
vX<<<^
>>>>^^
>>>>>^

Out:
E5, N3, W5, S2, E4, N1, W3

```

---

**Happy International Talk Like a Pirate Day!**

# Answer
> 3 votes
# CJam, 78 bytes

```
qN/_:,$W=:Tf{Se]}s:U,T-{_U="><^vX"#"1+'E1-'WT-'NT+'S0"4/=~_@\}g;;]e`{(+}%", "*

```

Try it online.

# Explanation

The main idea here is to find the longest line (we'll call this length `T`), then pad all lines to the same length and concatenate them (this new string is `U`). This way only a single counter is needed to move in the map. Adding/subtracting `1` means moving to the right/left in the same line, adding/subtracting `T` means moving down/up one line.

```
qN/    e# Split the input on newlines
_:,    e# Push a list of the line lengths
$W=:T  e# Grab the maximum length and assign to T
f{Se]} e# Right-pad each line with spaces to length T
s:U    e# Concatenate lines and assign to U

```

Now it's time to set up the loop.

```
,T-    e# Push len(U) - T
       e# i.e. position of first char of the last line
{...}g e# Do-while loop
       e# Pops condition at the end of each iteration

```

The loop body uses a lookup table and eval to choose what to do. At the beginning of each iteration, the top stack element is the current position. Underneath it there are all the processed NSWE directions. At the end of the iteration, the new direction is placed underneath the position and a copy of it is used as the condition for the loop. Non-zero characters are truthy. When an X is encountered, 0 is pushed as the direction, terminating the loop.

```
_U=      e# Push the character in the current position
"><^vx"# e# Find the index in "><^Vx"
"..."4/  e# Push the string and split every 4 chars
         e# This pushes the following list:
         e# [0] (index '>'): "1+'E" pos + 1, push 'E'
         e# [1] (index '<'): "1-'W" pos - 1, push 'W'
         e# [2] (index '^'): "T-'N" pos - T, push 'N'
         e# [3] (index 'v'): "T+'S" pos + T, push 'S'
         e# [4] (index 'X'): "0"    push 0
=~       e# Get element at index and eval
_@\      e# From stack: [old_directions position new_direction]
         e# To stack: [old_directions new_direction position new_direction]
         e# (You could also use \1$)
         e# new_direction becomes the while condition and is popped off

```

Now the stack looks like this: `[directions 0 position]`. Let's generate the output.

```
;;    e# Pop position and 0 off the stack
]     e# Wrap directions in a list
e`    e# Run length encode directions
      e# Each element is [num_repetitions character]
{     e# For each element:
 (+   e#   Swap num_repetitions and character
}%    e# End of map (wraps in list)
", "* e# Join by comma and space

```

# Answer
> 3 votes
# CJam, 86 bytes

```
qN/_,{1$=cS-},W=0{_3$3$==_'X-}{"^v<>"#_"NSWE"=L\+:L;"\(\ \)\ ( )"S/=~}w];Le`{(+}%", "*

```

Try it online

Explanation:

```
qN/     Get input and split into rows.
_,      Calculate number of rows.
{       Loop over row indices.
  1$=     Get row at the index.
  c       Get first character.
  S-      Compare with space.
},      End of filter. The result is a list of row indices that do not start with space.
W=      Get last one. This is the row index of the start character.
0       Column number of start position. Ready to start tracing now.
{       Start of condition in main tracing loop.
  _3$3$   Copy map and current position.
  ==      Extract character at current position.
  _'X-    Check if it's the end character `X.
}       End of loop condition.
{       Start of loop body. Move to next character.
  "^v<>"  List of directions.
  #       Find character at current position in list of directions.
  _       Copy direction index.
  "NSWE"  Matching direction letters.
  =       Look up direction letter.
  L\+:L;  Append it to directions stored in variable L.
  "\(\ \)\ ( )"
          Space separated list of commands needed to move to next position for each of
          the 4 possible directions.
  S/      Split it at spaces.
  =       Extract the commands for the current direction.
  ~       Evaluate it.
}w      End of while loop for tracking.
];      Discard stack content. The path was stored in variable L.
Le`     Get list of directions in variable L, and RLE it.
{       Loop over the RLE entries.
  (+      Swap from [length character] to [character length].
}%      End of loop over RLE entries.
", "*   Join them with commas.

```

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

```
a=>(b=a.split`
`,b.reverse().some((c,d)=>c[0]!=' '&&((e=d)||1)),j=[],eval("for(g=b[e][f=0];b[e][f]!='X';g=b[e][f],j.push('NSEW'['^v><'.indexOf(i)]+h))for(h=0;g==b[e][f];e+=((i=b[e][f])=='^')-(i=='v'),f+=(i=='>')-(i=='<'),h++);j.join`, `"))

```

Explanation:

```
a=>(
    b = a.split('\n'),
    // loops through list from bottom to find arrow
    b.reverse().some(
        (c, d)=>
            // if the leftmost character is not a space, saves the index and exit
            // the loop
            // in case d == 0, the ||1 makes sure the loop is exited
            c[0] != ' ' && ((e = d) || 1)
    ),
    j = [], // array that will hold the instructions
    eval("  // uses eval to allow a for loop in a lambda without 'return' and {}

        // loops through all sequences of the same character
        // e is the first coordinate of the current character being analyzed
        // f is the second coordinate
        // defines g as the character repeated in the sequence
        // operates on reversed b to avoid using a second reverse
        // flips ^ and v to compensate

        for(g = b[e][f = 0];
            b[e][f] != 'X'; // keep finding sequences until it finds the X
            g = b[e][f],    // update the sequence character when it hits the start of a
                            // new sequence
            j.push('NSEW'['^v><'.indexOf(i)] + h)) // find the direction the sequence is
                                                   // pointing to and add the
                                                   // instruction to j

            // loops through a single sequence until it hits the next one
            // counts the length in h
            for(h = 0;
                g == b[e][f]; // loops until there is a character that isn't part of
                              // the sequence
                // updates e and f based on which direction the sequence is pointing
                // sets them so that b[e][f] is now the character being pointed toward
                e += ((i = b[e][f]) == '^') - (i == 'v'),
                f += (i == '>') - (i == '<'),
                // increments the length counter h for each character of the sequence
                h++);

            // return a comma separated string of the instructions
            j.join`, `
    ")
)

```

# Answer
> 0 votes
# JavaScript(ES6), 189

Test running the snippet below in an EcmaScript 6 compliant browser.

```
f=m=>{(m=m.split`
`).map((r,i)=>r[0]>' '?y=i:0);for(x=o=l=k=p=0;p!='X';++l,y+=(k==1)-(k<1),x+=(k>2)-(k==2))c=m[y][x],c!=p?(o+=', '+'NSWE'[k]+l,l=0):0,k='^v<>'.search(p=c);alert(o.slice(7))}

// Testable version, no output but return (same size)
f=m=>{(m=m.split`
`).map((r,i)=>r[0]>' '?y=i:0);for(x=o=l=k=p=0;p!='X';++l,y+=(k==1)-(k<1),x+=(k>2)-(k==2))c=m[y][x],c!=p?(o+=', '+'NSWE'[k]+l,l=0):0,k='^v<>'.search(p=c);return o.slice(7)}

// TEST
out = x => O.innerHTML += x+'\n';

test =
[[`>>>>>>>>>>>>>>>v
               v
               v
               >>>>X`,'E15, S3, E4']
,[`>>>>>>v
^     v
^     >>>>X`,'N2, E6, S2, E4']
,[`X
^
^
^`,'N3']
,[`>>>>>>v
^     v
^     v
      v
      >>>>>>X`,'N2, E6, S4, E6']
,[` X
 ^
 ^
>^`,'E1, N3']
,[`>X`,'E1']
,[`v<<<<<
vX<<<^
>>>>^^
>>>>>^`,'E5, N3, W5, S2, E4, N1, W3']];

test.forEach(t=>{
  var k = t[1];
  var r = f(t[0]);
  out('Test ' + (k==r ? 'OK' : 'Fail')
      +'\n'+t[0]+'\nResult: '+r
      +'\nCheck:  '+k+'\n');
})
```

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

**Less golfed**

```
f=m=>{
  m=m.split('\n'); // split in rows

  x = 0; // Starting column is 0
  m.forEach( (r,i) => r[0]>' '? y=i : 0); // find starting row

  o = 0; // output string
  p = 0; // preceding character
  l = 0; //  sequence length (this starting value is useless as will be cutted at last step)
  k = 0; //  direction (this starting value is useless as will be cutted at last step)
  while(p != 'X') // loop until X found
  {
    c = m[y][x]; // current character in c
    if (c != p) // changing direction
    {
      o +=', '+'NSWE'[k]+l; // add current direction and length to output
      l = 0 // reset length
    );
    p = c;
    k = '^v<>'.search(c); // get new current direction
    // (the special character ^ is purposedly in first position)
    ++l; // increase sequence length
    y += (k==1)-(k<1); // change y depending on direction
    x += (k>2)-(k==2); // change x depending on direction
  }
  alert(o.slice(7)); // output o, cutting the useless first part
}

```

---
Tags: code-golf
---