title: Hate/love conundrum

text:
# Question
Title: Hate/love conundrum
# Challenge description

In this challenge, we only consider `love` and `hate` as feelings. If we want to utter a **feeling expression** of order `N`, we alternate between these two (starting with `hate`):

```
order | expression

1       I hate it.
2       I hate that I love it.
3       I hate that I love that I hate it.
4       I hate that I love that I hate that I love it.

```

The pattern follows for every positive integer `N`. Given `N`, output the correspoinding feeling expression of order `N`.

# Notes

* Full stop (`.`) at the end of the expression is mandatory,
* Trailing and leading whitespaces (including newlines) are permitted,
* Output for a non-positive or non-integer `N` is undefined,
* This is a challenge, so make your code as short as possible!

# Answer
# Python, 54 bytes

```
lambda n:("I hate that I love that "*n)[:12*n-5]+"it."

```
> 21 votes

# Answer
## CJam, 36 bytes

```
ri{"hatlov"3/='IS@"e that "}/2<"it."

```

Try it online!

### Explanation

```
ri            e# Read input and convert to integer N.
{             e# For each i from 0 to N-1...
  "hatlov"3/  e#   Push ["hat" "lov"].
  =           e#   Use i as a cyclic index into this array to alternate between
              e#   "hat" and "lov".
  'IS         e#   Push character 'I' and a space.
  @           e#   Pull "hat" or "lov" on top of it.
  "e that "   e#   Push "e that "
}/
2<            e#   Truncate the last "e that " to just "e ".
"it."         e#   Push "it."

```
> 15 votes

# Answer
# C, ~~83~~ ~~76~~ ~~75~~ 74 bytes

*Thanks to @Leaky Nun for saving 11 bytes and adding 4 bytes!*
*Thanks to @YSC for saving a byte!*

```
i;f(n){for(i=0;n--;)printf("I %se %s",i++%2?"lov":"hat",n?"that ":"it.");}

```

Try it on Ideone
> 7 votes

# Answer
## Javascript (ES6), ~~75~~ ~~73~~ 70 bytes

```
n=>[...Array(n)].map((_,i)=>i&1?'I love':'I hate').join` that `+' it.'

```

*Saved 2 bytes thanks to Neil*
*Saved 3 bytes thanks to Whothehellisthat*

### Test

```
let f =
n=>[...Array(n)].map((_,i)=>i&1?'I love':'I hate').join` that `+' it.'

console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
```
> 6 votes

# Answer
# Java 8, 91 bytes

```
i->{for(int j=0;j++<i;)System.out.printf("I %se %s",j%2>0?"hat":"lov",j<i?"that ":"it.");};

```

# Ungolfed Test Program

```
public static void main(String[] args) {
    Consumer<Integer> c = i -> {
        for (int j = 0; j++ < i;) {
            System.out.printf("I %se %s", j % 2 > 0 ? "hat" : "lov", j < i ? "that " : "it.");
        }
    };

    c.accept(1);
    c.accept(2);
    c.accept(3);
}

```
> 5 votes

# Answer
## Mathematica, 63 bytes

```
"I love"["I hate"][[#~Mod~2]]&~Array~#~Riffle~" that "<>" it."&

```
> 5 votes

# Answer
# Jelly, 25 bytes

```
“ṅɠT5“£ẏkg⁷»ṁj“¥ıQ»ṙ1“it.

```

Try it online!

## Explanation

```
                             Input: n, a number.
“ṅɠT5“£ẏkg⁷»                 Compressed string array [' I hate', ' I love']
            ṁ                Cycle for n repetitions.
             j“¥ıQ»          Join by compressed string ' that'.
                   ṙ1        Rotate left once: move the initial space to the end.
                     “it.    Implicitly print the result, then print 'it.'

```
> 5 votes

# Answer
# 05AB1E, ~~34~~ ~~32~~ 27 bytes

Saved 5 bytes thanks to Adnan.

```
“I«¢€Š I„Î€Š “×¹12*5-£…it.«

```

**Explanation**

```
“I«¢€Š I„Î€Š “               # "I hate that I love that "
              ×              # repeat input nr of times
               ¹12*5-£       # take the first input*12-5 chars of string above
                      …it.«  # append "it."
                             # implicitly display

```

Try it online!
> 4 votes

# Answer
# R, 79 bytes

```
n=scan();for(i in n:1)cat(if((i+n)%%2)"I love"else"I hate",if(i>1)"that "else"it.")

```

Luckily in R, the default separator for `cat` is a space.

(Edited from original 73 byte version which didn't quite solve the problem.)
> 4 votes

# Answer
# Retina, ~~42~~ 38 bytes

Thanks to Leaky Nun for helping me golf it!

```
11
1I love n
1
I hate n
n$
it.
n
that

```

Input is taken in unary.

Try it online!

**Explanation**

```
11
1I love n

```

Replace every pair of `1`s with `1I love n`.

```
1
I hate n

```

Replace the remaining `1`s with `I hate n`.

```
n$
it.
n
that

```

Replace the `n` at the end of the line with `it.` and every other n with `that`.
> 2 votes

# Answer
# Javascript (ES5), 99 94 bytes

```
function(c){for(d="",b=0;b<c;++b)d+=(b%2?"I love ":"I hate ")+(b==c-1?"it.":"that ");return d}

```

Saved 5 bytes thanks to Leaky Nun.

OLD 99 byte solution:

```
function(c){for(d="",b=0;b<c;++b)d+=(0==b%2?"I hate":"I love")+" "+(b==c-1?"it.":"that ");return d}

```

Another 98 byte solution:

```
function(d){for(c=[],b=0;b<d;++b)c.push(["love","hate"][b%2]);return"I "+c.join(" that I ")+" it"}

```

My code before minification:

```
function a(n){
  var hate="I hate",love="I love",it="it ",that="that ",out="";
  for(var i=0;i<n;++i){out+=(i%2==0?hate:love)+" "+(i==n-1?it+".":that)}return out;
}

```
> 1 votes

# Answer
# php, ~~64~~ 62 bytes

```
<?=str_pad("",$argv[1]*12-5,"I hate that I love that ")."it.";

```

Unfortunately I couldn't work out a way to avoid repeating the " that I ", or at least no way to do it in less than 7 bytes.

edit: saved 2 bytes thanks to @Jörg Hülsermann
> 1 votes

# Answer
# Haskell, 70 bytes

```
g 1="I hate";g n=g(n-1)++" that "++cycle["I love",g 1]!!n
(++" it.").g

```
> 1 votes

# Answer
## PowerShell v2+, 64 bytes

```
((1..$args[0]|%{('I love','I hate')[$_%2]})-join' that ')+' it.'

```

Rather straightforward. Loops from `1` up to the input `$args[0]`, each iteration placing either `'I love'` or `'I hate'` on the pipeline, based on a pseudo-ternary for modulo-2 (i.e., it alternates back and forth, starting with `'I hate'`). Those strings are encapsulated in parens and `-join`ed with `' that '` to smush them together, then string concatenation `' it.'` at the end.

### Test Cases

```
PS C:\Tools\Scripts\golfing> 1..5|%{.\hate-love-conundrum.ps1 $_}
I hate it.
I hate that I love it.
I hate that I love that I hate it.
I hate that I love that I hate that I love it.
I hate that I love that I hate that I love that I hate it.

```
> 1 votes

# Answer
## Perl, ~~62~~ ~~54~~ 50 bytes

```
$_="I xe tx "x$_;s/tx $/it./;s/x/++$.%4?hat:lov/ge

```

(credit to @Ton Hospel)

Demo: http://ideone.com/zrM27p

### Previous solutions:

```
$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./

```

(credit to @Dada)

Run with `perl -pE '$_="I xe that "x$_;s/x/$@++&1?lov:hat/ge;s/\w+.$/it./'`

### First solution (only this was mine)

```
for$x(1..<>){$_.=' I '.($x%2?hat:lov).'e that'}s/\w+$/it./;say

```

In parts:

```
for $x (1..<>) {
   $_ .= ' I '.($x % 2 ? hat : lov).'e that'
}
s/\w+$/it./;
say

```

Demo: http://ideone.com/mosnVz
> 1 votes

# Answer
# Bash + coreutils, 106 bytes:

```
for i in `seq $1`;{ printf "I %s %s " `((i%2>0))&&echo hate||echo love` `((i==$1))&&echo it.||echo that`;}

```

Simply creates a sequence starting at `1` up to and including the input integer using the `seq` built-in, and then iterates through it one by one, first outputting `hate` if the value of the iteration variable, `i`, is not divisible by `2` and `love` otherwise. In the same iteration, it then chooses to output `that` if `i` is not equal to the input value, and `it.` otherwise.

Try It Online! (Ideone)
> 1 votes

# Answer
# ///, ~~60~~ 57 bytes

```
/!/I hate //T/that //
/it.//00/!TI love T//Tit./it.//0/!/

```

*-3 bytes thanks to m-chrzan*

Input in unary with trailing new line.

Try it online!
> 1 votes

# Answer
## R, 92 90 bytes

An R adaptation of @Leaky Nun's python answer. Working with strings in R is tedious as always.

```
n=scan();cat(rep(strsplit("I hate that I love that ","")[[1]],n)[6:(n*12)-5],"it.",sep="")

```

This could probably be golfed further though.

Edit: saved 2 bytes by changing:

`[1:((n*12)-5)]`to `[6:(n*12)-5]`
> 0 votes

# Answer
## C, 96 Bytes

```
c;f(i){printf("I hate");for(;c<i+1/2-1;c++)printf(" that I %s",c&1?"hate":"love");puts(" it.");}

```

I didn't see the above solution from Releasing Helium Nuclei which is better.
> 0 votes

# Answer
# MATL, 37 bytes

```
:"2@o3]Qv'hate I that it. love'Ybw)Zc

```

Try it online!

### Explanation

The code is based on the following mapping from numbers to strings:

```
0: 'love'
1: 'hate'
2: 'I'
3: 'that'
4: 'it.'

```

The program pushes numbers to the string in groups of three: `2`, `0`, `3`; then `2`, `1`, `3`; then `2`, `0`, `3`; ... as many times as the input `n`. After that, the final `3` is transformed into a `4`, the mapping is applied to transform numbers to strings, and the strings are joined using space as separator.

```
:                         % Input n implicitly. Push range [1 2 ... n]
"                         % For each
  2                       %   Push 2
  @o                      %   Iteration index modulo 2: pushes 0 or 1
  3                       %   Push 3
]                         % End
Q                         % Add 1 to the last 3
v                         % Concatenate stack contents into a numeric column vector
'hate I that it. love'    % Push this string
Yb                        % Split at spaces. Gives a cell array of five strings
w                         % Swap to move numeric vector to top
)                         % Index cell array of strings with that vector. Indexing
                          % is 1-based and modular, so 0 refers to the last string.
                          % This gives a cell array of (repeated) strings
Zc                        % Join those strings by spaces. Display implicitly

```
> 0 votes

# Answer
# JavaScript (ES6), 68 bytes

```
f=(n,i)=>n?(i?' that I ':'I ')+(i&1?'love':'hate')+f(n-1,-~i):' it.'

document.write('<pre>'+[ 1, 2, 3, 4, 10, 100 ].map(c=>c+': '+f(c)).join`\n`);
```
> 0 votes

# Answer
# Lua , 75 Bytes

```
n=io.read();print(('I hate that I love that '):rep(n):sub(1,n*12-5)..'it.')

```
> 0 votes

# Answer
# C#, ~~85~~ 83 bytes

```
string f(int n,int m=2)=>"I "+(1>m%2?"hat":"lov")+(m>n?"e it.":"e that "+f(n,m+1));

```

Recursively constructs the string, using an optional parameter to keep track of which hate/love and how many to append.

*-2 bytes from this tip for checking the evenness/oddness of a number.*

### No optional parameter solution, ~~87~~ ~~86~~ 84 bytes

```
string h(int n)=>"I "+(0<n?"hat":"lov")+(2>n&-2<n?"e it.":"e that "+h(0<n?~n+2:~n));

```

This one does the same thing except determines which hate/love to append based on whether the parameter is positive or negative. Each iteration the parameter approaches zero, alternating sign.
> 0 votes

# Answer
# Thue, 100 bytes

```
@::=:::
>##::=>$.
$::=~I hate that I love
>.#::=>&#
&::=~that
>#<::=~I hate it.
>.<::=~it.
::=
>@<

```

Takes input as unary. (A string of n `#`s)
> 0 votes

# Answer
## Pyke, 36 bytes

```
2/"I hate ""I love "]*"that "J"it."+

```

Try it here!

```
2/                                   -    input/2
                     *               -   ^ * v
  "I hate ""I love "]                -    ["I hate ", "I love "]
                      "that "J       -  "that ".join(^)
                              "it."+ - ^+"it."

```

Also 36 bytes

```
12*5+.daෆ   ű   l5d+12"I ":Q*<"it."+

```

Try it here! (Link uses `X` instead of `I`, this should work for the same amount of bytes offline where you can literally use those bytes. Online `\r` gets automatically replaced with `\n`)
> 0 votes

# Answer
# \>\<\> (Fish), 82 Bytes

```
' I'oov.2coo<;oooo' it.'<
'ahv'v>'et'
oop26<^ooooo^o' that I '^!?:-1oo
'ol^'^>'ev'

```

Doubt it's very efficient, but it seems to more or less work. Input is via the starting stack, which makes the score 85 Bytes if you include the size of the `-v` argument required to do so.

Try it online!
> 0 votes

# Answer
# ///, 68 bytes

```
/@/1\/#love //%/hate//#/that I //%1i/% i//I %1/I % //1@#% //@/I %1it.

```

Input in unary - add more `1`s in the last section.

Try it online!
> 0 votes

# Answer
## dc, 75 bytes

```
?[1-lbP[I lov]P]sa[e that ]sb[[e it.]Pq]sc[1-[I hat]Pd2%1=ad1>clbPlxx]dsxx

```

We're really just printing one chunk of string at a time here, and not leaving any garbage on the stack. This is great, we don't need to waste any bytes dealing with a register for our counter.

```
?                              #Input, works as our decrement counter
[1-lbP[I lov]P]sa              #Macro 'a' decrements our counter, prints string 'b',
                               #then prints 'I lov'
[e that ]sb                    #String 'b'
[[e it.]Pq]sc                  #Macro 'c' prints the tail end of our message and quits
[1-                            #I'll unfold our main macro here; first step is to
                               #decrement our counter
   [I hat]P                    #We always start by hating 'it,' no conditional needed
           d2%1=a              #Check the oddness of our counter; execute 'a' if odd
                 d1>c          #Check our counter; If we're done, execute 'c'
                     lbPlxx]   #Otherwise, print 'b' again and start this macro ('x') over
dsxx                           #Stores the above macro as 'x' and runs it.

```
> 0 votes

# Answer
## Julia, 91 Bytes

Thought I add a julia solution:

```
f(N)=string("I hate ",join(["that I love that I hate " for _ in 1:N-1])[1:12*(N-1)],"it."))

```
> 0 votes

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


title: Alexa and the Tea Plantation

text:
# Question
Title: Alexa and the Tea Plantation
*Hey guys, first time poster here. I went on Coderoulette recently and some guy posted this question. I looked around online but it doesn't seem to be anywhere. I figured I would post it here for anyone who is a fan of these types of problems. Enjoy!*

---

Alexa is a druid who loves Mathematics! She lives in the land of Alfa, taking care of a tea plantation.
The plantation has N plants and the height of the ith plant is Hi.

Alexa has developed a recent interest in palindromes. She wants to crop the plants so the height of the plants forms a palindrome (without any reordering). She has 2 spells in her arsenal- the 'Growlith' spell will increase the height of a plant by 1 unit, the 'Shrinkooza' spell will decrease the height of a plant by 1 unit. The 'Growlith' and 'Shrinkooza' spells cost A and B units of magic respectively. Help Alexa find the minimum units of magic, that shall enable her to fulfill her objective.

### Input Format

First line contains an integer T. T testcases follow.
First line of each test case consists of 3 space-separated integers N, A and B.
Next line consists of N space-separated integers, the initial height of the plants.

### Output Format

Print the answer to each test case on a new line.

### Constraints

1 \<= T \<= 10
1 \<= N \<= 105
0 \<= A, B \<= 108
1 \<= Hi \<= 103

---

## Example

### Input

```
1
5 2 2
1 6 2 3 4

```

### Output

```
12

```

### Explanation

She can use the 'Growlith' spell on the first plant 3 times and the 'Shrinkooza' spell on the second plant 3 times to form 4 3 2 3 4.

### Challenge

Write code that will create a palindrome using the least units of magic possible for N plants.

### Scoring

This is code golf. The shortest code in bytes wins.

# Answer
# 05AB1E, 20 bytes

```
WU|vy#Â‚ø€¥˜Ä2ä`OX*,

```

**Explanation**

```
WU                    # store minimum cost in X
  |v                  # for each testcase
    y#                # convert to list split on spaces
      Â‚ø             # zip with its own reverse
         €¥           # deltas of each pair
           ˜Ä         # deep flatten and take absolute value
             2ä       # split into 2 pieces
               `      # flatten (leaves the smaller piece on top of the stack)
                O     # sum
                 X*   # multiply with minimum cost
                   ,  # print

```

Try it online!
> 2 votes

# Answer
## Julia, 88 Bytes

```
f(l,A,B)=reduce(+,map(abs,map(sum,[zip(-l,reverse(l))...][1:fld(end,2)])))*min([A,B]...)

```

**Explained:**

If I am not mistaken, all we have to do is either grow all necessary plants or shrink them (depending on which operations is less expensive)

1. zip input list with a reverse of itself (align corresponding heights)
2. only look at first half of the list (floor when length is odd)
3. sum the differences
4. multiply with minimum cost (A or B)

**Example**

```
f([1,6,2,3,4],1,2) -> 6   (grow plant 1 and 4, yields [4,6,2,6,4])
f([1,6,2,3,4],3,2) -> 12   (shrink plant 2 and 5, yields [1,3,2,3,1])

```

**Note:**

As there is still a discussion about the input format, I disregarded it for the moment.

**Update:**

Updated to output energy, as I think that outputing the actual palindrome is more challenging I attach my previous code here (76 Bytes):

```
f(l,A,B)=reduce(hcat,map(x->sort([x...]),[zip(l,reverse(l))...]))[A>B?1:2,:]

```
> 1 votes

# Answer
## JavaScript (ES6), 70 bytes

```
f=(a,g,s)=>a.reduce((t,h,i)=>t+Math.abs(a[a.length+~i]-h),0)*(g>s?s:g)/2

```

Double-counts the differences, but we only need to make half the changes, which is achieved by dividing by 2 at the end.
> 1 votes

---
Tags: code-golf, math, palindrome
---


# Question
Title: Make An ASCII Poker Chip Stack Arrangement
Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s).

---

**The Challenge**

We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, `n`.

**Input**
\- A positive integer, `n` (up to `2**32-1` should be handled)

**Output**
\- An ASCII representation of the stack arrangement as defined below.
This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line;
This may contain a single trailing new line; and
The characters representing chips may be in lowercase if you prefer.

The stack arrangement will:

* Contain the fewest chips possible, given the denominations (see below);
* Will have equal valued chips in "stacks" (columns);
* Be ordered such that the shorter stacks are to the right of taller stacks; and
* Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right)

The chips themselves are to be represented as individual characters identifying their colour:

```
    White : 1    = W
      Red : 5    = R
    Green : 25   = G
    Black : 100  = B
   Yellow : 500  = Y
     Pink : 1K   = P
   Orange : 5K   = O
     Cyan : 25K  = C
  Magenta : 100K = M
Aqua-blue : 500K = A
 Lavender : 1M   = L
   Indigo : 5M   = I
Turquoise : 25M  = T
   Violet : 100M = V
   Silver : 500M = S

```

---

**Example**

For `n = 276,352` the smallest number of chips would be:

```
2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1
    MM         CCC       P        BBB       GG       WW

```

The single `P` must go on the far right,
then the three stacks of size `2` must go next,
\- but the `MM` must go furthest to the right followed by the `GG` and then the `WW` since `100K > 25 > 1` then the two stacks of size `3` go on the left,
\- but the `CCC` must go to the right of the `BBB` since `25K > 100`

Now we must place these chips into actual stacks, to make our output:

```
BC
BCWGM
BCWGMP

```

---

**Test Cases**

```
Input:
1

Output:
W

Input:
9378278

Output:
L
LWGPCM
LWGPCMB
LWGPCMBI

Input:
22222222

Output:
ROI
ROI
ROIWBPML
ROIWBPML

Input:
1342185143

Output:
WRCIV
WRCIVOLS
WRCIVOLSGBMT

Input:
2147483647

Output:
RMIS
RMISPC
RMISPCWL
RMISPCWLGBYOTV

Input:
4294967295

Output:
S
S
S
S
SRML
SRMLGOIT
SRMLGOITBPCV
SRMLGOITBPCVA

```

---

This is , so shortest code in bytes wins. No loopholes, yada yada, you know the drill.

# Answer
# Pyth, ~~56~~ ~~55~~ 52 bytes

The code contains some unprintables, so here's a reversible `xxd` hexdump.

```
00000000: 3d48 516a 5f2e 745f 2023 6c44 2a56 2e22  =HQj_.t_ #lD*V."
00000010: 4159 261c 0c24 2087 0c86 1e22 6d68 412e  AY&..$ ...."mhA.
00000020: 4448 645f 2e75 2a4e 5950 2a33 6a37 3733  DHd_.u*NYP*3j773
00000030: 3620 362f                                6 6/

```

Try it online. Test suite.

Pro tip: to golf  `1` in the end of a program accepting a nonzero number in `Q`, just add `/`. `/QQ`, which in Python would be `Q // Q`, is 1 for nonzero `Q`.

Without compression and unprintables (55 bytes):

```
=HQj_.t_ #lD*V"SVTILAMCOPYBGRW"mhA.DHd_.u*NYP*3j7736 6/

```
> 5 votes

# Answer
# JavaScript (ES6), ~~185~~ ~~177~~ ... 171 bytes

```
f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

```

### Formatted and commented

```
(a, s = '') => (                           // a = bankroll OR array of chip stacks
  a = (                                    // s = string of chip initials for this iteration
    a[0] ?                                 // if 'a' already is an array:
      a                                    // use it as-is
    :                                      // else, 'a' is the bankroll:
      [...(m = '25455') + m + m]           // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3)
      .map((m, i) =>                       // v = current chip value = previous value / m
        (                                  // k = floor(a / v) = number of these chips
          a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v
          k * 16 + i                       // saved in array: chip index in bits 0-3
        ),                                 // and number of chips in bits 4+
        v = 1E9                            // initial chip value = 1 billion
      )                                    // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.)
      .sort((a, b) => b - a)               // sort the chip stacks
  )                                        //
  .map(n =>                                // for each chip stack:
    n > 15 &&                              // if there's at least one remaining chip of
    (                                      // this kind:
      s += 'SVTILAMCOPYBGRW'[n & 15],      // append its initial to the string
      n - 16                               // decrement the number of chips in this stack
    )                                      //
  ),                                       // process recursive call if there was at least
  s && f(a) + '\n' + s                     // one non-empty chip stack (the next lines are
)                                          // appended at the beginning of the final string)

```

### Demo

```
let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

function update() {
  document.getElementById('o').innerHTML = f(+document.getElementById('i').value);
}
update();
```

```
<input id="i" value="1342185143" oninput="update()"><pre id="o"></pre>
```
> 6 votes

# Answer
# Ruby, ~~181~~ 177 bytes

```
->n{*a=5*10**8
14.times{|i|a<<a[-1]/[5,4,5,5,2][i%5]}
a=a.zip("SVTILAMCOPYBGRW".chars).map{|v,c|[-(n/v),v,c,n%=v]}.sort
l=-a[0][0]
(1..l).map{|i|a.map{|d|l-i<-d[0]?d[2]:""}*""}}

```

Tests on Ideone.
> 5 votes

# Answer
## Python 2.7, ~~282~~ ~~248~~ 238 bytes

```
c=input();L=[]
for i in range(15):m=[5,1,25,5,1][i%5]*10**int("886665533322000"[i]);L+=[[c/m,i,"SVTILAMCOPYBGRW"[i]]];c%=m
L.sort();S=[]
while L[~1][0]:
 s=""
 for X in L[::-1]:
  if X[0]>0:X[0]-=1;s+=X[2]
 S+=[s]
for s in S[::-1]:print s

```

**Explanation:**
Fill list `L` with elements `[quanity, chip_order, chip_character]` indicating the quantity of each type of chip , where `chip_order` ensures chips of equal quantity get sorted in reverse order (higher value chips *first*). Take chips from `L` in reverse to build strings for each line. Print lines in reverse to get smallest lines on top.

*Thanks to Blue for some of the improvements.*
> 4 votes

# Answer
## Mathematica, 440 bytes

```
n=Input[]
c=Characters["SVTILAMCOPYBGRW"]
l=Reap[Do[n=n-#[[-i]]*Sow[Floor[n/#[[-i]]]]&@FoldList[Times,1,{5,5,4,5,2,5,5,4,5,2,5,5,4,5}],{i,1,15}]][[2,1]]
StringJoin@@((StringJoin[#,"\n"])&/@StringJoin/@Reverse/@((PadRight[#,Max[l],""]&/@Sort[Table[If[l[[n]]>0,Table[c[[n]],l[[n]]],Nothing],{n,1,15}],If[Length[#1]==Length[#2],Position[c,#1[[1]]][[1,1]]<Position[c,#2[[1]]][[1,1]],Length[#1]<Length[#2]]&])[[All,#]]&/@Range[Max[l]])//Reverse)

```

The ASCI-representation and right order swallows most of the code.

**\*Only works with Version11 *and higher* (use of Nothing)\***
> 3 votes

# Answer
# PHP, 274 Bytes

```
$t=$argv[1];$n=[500,100,25,5,1];$c=YBGRWAMCOPSVTIL;foreach($n as$k=>$v)for($i=0;$i<3;)$r[$v*10**($i*3)]=$c[$k+$i++*5];krsort($r);foreach($r as$v=>$k)$t-=($x[$v]=floor($t/$v))*$v;ksort($x);arsort($x);for($y=max($x);$y;$y--){foreach($x as$k=>$v)if($v>=$y)echo$r[$k];echo"\n";}

```
> 0 votes

---
Tags: code-golf, ascii-art, number, sorting, conversion
---


title: Animations with all colours

text:
# Question
Title: Animations with all colours
Last year, there was a very popular challenge to create an image containing every 24-bit RGB colour.

My challenge is to create a smooth animation (24 frames/s say), where the colour of every pixel of every frame is unique. I will also allow duplication of colours as long as *every colour appears the same number of times (greater than 0)*, since otherwise the animation will have to be short, or the frames small.

I have produced some examples here, based on the winning solution to the 2d version. Unfortunately, it seems you can't embed videos, so links will have to do.

# Answer
> 4 votes
# Mathematica

This is a straightforward implementation with each rgb colour occupying an intersection in a 256 by 256 by 256 unit grid.

The jerkiness seems to be an artefact of the video, not an error in the data, which should be exact.

red values increase downwards, green values increase rightwards, and blue values increase by frame.

Perhaps I'll jumble things up later.

```
f@b_ := Image@Table[{r, g, b}/255, {r, 0, 255}, {g, 0, 255}]
Export["c.mov", Table[f@b, {b, 0, 255}]]

```

QuickTime clip

# Answer
> 0 votes
# PHP (+ HTML) + JavaScript

**Part 1**
generate 256 images with distinct red values from 0 to 255;
green value=row index, blue value=column index

```
for($r=$h=256;$r--;){$i=imagecreatetruecolor($g=$h,$h);for(;$g--;)for($b=$h;$b--;)imagesetpixel($i,$g,$b,imagecolorallocate($i,$r,$g,$b));imagepng($i,"$r.png");imagedestroy($i);}

```

*Note*: Depending on Your PHP implementation, this may throw an internal server error.
If it does, take the lowest number of the images that already have been created, insert `<number>,` after `$r=` and run again.

**Part 2**
loop through these images from 0 to 255 and back (0 and 255 taking 2 frames each)

```
<img><script>r=d=0;setInterval(()=>{document.images[0].src=r+".png",(d?!r--:(++r)>=256)?r-=(d=!d)?1:-1:r},40);</script>

```

---
Tags: popularity-contest, graphical-output, animation
---


title: Is this string prime?

text:
# Question
Title: Is this string prime?
> A string is called a "prime string" if it can't be written as a concatenation of more than one of the same string.

Your task is to write a program that, given a sequence of letters of length *N* (5 \< *N* \< 100), determines if it is prime or not.

## Examples

Input: `AABBAA`
Output: `not prime`, `false`, `0`, etc.

Input: `FDFJKEHKLJHDSUS`
Output: `prime`, `true`, `1`, etc.

Uppercase and lowercase letters count as the same letter.

Remember, this is , so the code with the smallest number of bytes wins.

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=94238,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(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){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<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="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Ruby, 16 + 1 (`n` flag)\` = ~~36~~ 17 bytes

Basically the prime-checking regex for unary numbers. Probably shorter in Retina. If you want a newline after the output, add the newline for 1 bytes.

Edited to a shorter version only for the sake of posterity, since there's not much point in answers to dupe questions.

```
p ! ~/^(.+)\1+$/

```
> 1 votes

---
Tags: code-golf
---


# Question
Title: Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as `.` or `.`, ***or*** the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as `\` or `/\/` or `\/\/\/\/\/\/`.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the `.`, moving it one place to the right, then output the resulting string. For example:

`.``.`
`.``.`
`.``.`
`.``.`
`.``.`
`.``.`
`.``.`
`.``.`

In the wave case, append either `/` or `\` appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

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

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

**The shortest code in bytes wins.**

# Answer
# C, 69 bytes

```
p;f(char*s){p=s[strlen(s)-1]^46;p^=p?93:3022856;printf("%s%s",s,&p);}

```

This requires a little-endian machine, and output to a terminal that support ASCII escape codes.

`p=s[strlen(s)-1]^46` grabs the last ASCII code of the input string, and XORs it with the ASCII code of a dot.

`p^=p?93:3022856` will cause `p` to be `p^93` if the ASCII code is not a (back)slash, where `p^46^93 == p^115`, which will toggle between back and forward slash. If `p` is a dot, it will instead be `3022856`, which is little-endian for `"\b ."`.

`printf("%s%s",s,&p);` prints the input string followed by the integer `p`, interpreted as a little-endian byte string.
> 16 votes

# Answer
# Jelly, ~~17~~ 14 bytes

```
ṪO*2.ị“ .\/\”ṭ

```

Try it online! or verify all test cases.

### How it works

```
ṪO*2.ị“ .\/\”ṭ  Main link. Argument: s (string)

Ṫ               Tail; pop and yield the last character.
 O              Ordinal; map “./\” to [46, 47, 92].
  *2.           Elevate the code point to the power 2.5.
                This maps [46, 47, 92] to [14351.41, 15144.14, 81183.84].
     ị“ .\/\”   Index into that string.
                Jelly's indexing is modular, so this takes the indices modulo 5,
                which gives [1.41, 4.14, 3.84].
                Also, for a non-integer index, ị retrieves the elements at both
                adjacent integer indices (1-based). Here, these are [1, 2], [4, 5],
                and [3, 4], so we get " .", "/\", or "\/".
             ṭ  Tack; append the characters to the popped input string.

```
> 12 votes

# Answer
# CJam, 16 bytes

```
l)_'.={S\}"\/"?|

```

Try it online! or verify all test cases.

### How it works

```
l                 Read a line from STDIN.
 )_               Shift out the last character and copy it.
   '.=            Compare the copy with a dot.
              ?   If the last character is a dot:
      {S\}            Push " " and swap the dot on top.
          "\/"    Else, push "\/".
               |  Perform set union, ordering by first occurrence.
                    " " '.  | -> " ."
                    '/ "\/" | -> "/\"
                    '\ "\/" | -> "\/"

```
> 7 votes

# Answer
## Python, 41 bytes

```
lambda s:[s+'\/'[s[-1]>'/'],' '+s][s<'/']

```

Casework. Uses the sorted order `' ', '.', '/', '\'`. For spaces and period, prepends a space. Otherwise, appends a slash or blackslash opposite to the last character.
> 6 votes

# Answer
## Python,  ~~44~~  42 bytes

```
lambda s:s[:-1]+"\/ /\."[-ord(s[-1])&3::3]

```

Replaces the last character with the correspond set of two characters. ideone link

*(-2 bytes thanks to @xsot's shorter mapping function)*
> 5 votes

# Answer
# Game Maker Language, 107 bytes

```
s=argument0;if string_pos(" ",s)return " "+s;if string_pos(s,string_length(s))="/"s+="\"else s+="/"return s

```
> 5 votes

# Answer
# Vim, ~~27~~ 23 keystrokes

First vim answer ever, haven't used vim at all really even.

```
A/<esc>:s#//#/\\<cr>:s#\./# .<cr>

```

How it works: It appends a `/` at the end of line, subs `//` for `/\`, subs `./` for  `.`
> 5 votes

# Answer
# MATL, 19 bytes

```
t47<?0w}'\/'yO)o)]h

```

Try it online! Or verify all test cases.

### Explanation

```
t        % Input string implicitly. Duplicate
47<      % Are entries less than 47 (i.e dot or spaces)?
?        % If all are
  0      %   Push a 0. When converted to char it will be treated as a space
  w      %   Swap, so that when concatenated the space will be at the beginning
}        % Else
  '\/'   %   Push this string
  y      %   Duplicate the input string onto the top of the stack
  O)     %   Get its last element
  o      %   Convert to number
  )      %   Use as (modular) index to extract the appropripate entry from '\/'
]        % End
h        % Concatenate string with either leading 0 (converted to char) or
         % trailing '\'  or '/'. Implicitly display

```
> 4 votes

# Answer
# CJam, ~~35~~ ~~26~~ 25 bytes

Saved 9 bytes thanks to dennis

Saved 1 more byte, also thanks to dennis

```
q:I'.&SI+IW='/=I'\+I'/+??

```

Try it online!

Probably poorly golfed, but I'm not too familiar with CJam. There's probably a better way to check if an element is in an array, but I couldn't find any operators for that.

Explanation:

```
q:I e# take input
'.& e# push union of input and ".", effectively checking if input contains it
SI+ e# push string with space in beginning
IW='/= e# push 1 if the last chsaracter in the input is /
I'\+ e# push the input with a \ appended
I'/+ e# push the input with a / appended
? e# ternary if to select correct /
? e# ternary if to select final result

```
> 3 votes

# Answer
## 05AB1E, ~~17~~ 15 bytes

```
D'.åiðìë¤„\/s-J

```

**Explanation**

```
D'.åi              # if input contains dot
     ðì            # prepend a space
       ë           # else
        ¤„\/s-     # subtract last char of input from "\/"
              J    # join remainder to input
                   # implicitly print

```

Try it online
> 3 votes

# Answer
# C, 85 bytes

```
j;f(char*n){j=strlen(n)-1;printf("%s%s",n[j]<47?" ":n,n[j]==46?n:n[j]==47?"\\":"/");}

```

Ideone

I haven't slept for about 20 hours, my code probably can be golfed a lot.
> 2 votes

# Answer
# Brachylog, 35 bytes

```
t~m["\/.":X]t:"/\ "rm:?{.h" "|r.}c.

```

Test suite. (Slightly modified.)
> 2 votes

# Answer
# Retina, 19 bytes

```
\.
 .
/$
/\^H
\\$
\/

```

`^H` represents the BS byte. Try it online!
> 2 votes

# Answer
## Matlab, ~~74~~ ~~71~~ ~~62~~ 57 bytes

```
@(s)[s(1:end-1) ' .'+(s(1)>46)*'/.'+(s(end)>47)*[45 -45]]

```

It computes the last two characters based on the `s(1)` (first character) - to determine if we're dealing with the `\/` case, and the last character `s(end)` to make the correct tuple for the `\/` characters.
> 2 votes

# Answer
# JavaScript, ~~79~~ ~~70~~ ~~65~~ 58 bytes

```
(a,b="/\\/",i=b.indexOf(a[a.length-1]))=>i<0?" "+a:a+b[i+1]

```
> 2 votes

# Answer
# \>\<\>, 47 bytes

```
i:0(?\
*=?$r\~:1[:"./ \/"{=?@r=?$r~~]:48
l?!;o>

```

Try it online!

The first line is a standard \>\<\> input loop. The second line chooses the appropriate character from `/ \` to append to the string, based on the last input character. In addition, if the last input character was a `.`, the top two elements are switched. Finally, the stack contents are printed in reverse.
> 2 votes

# Answer
## C# - 46 bytes

`s=>s[0]<47?' '+s:s+(s.EndsWith("/")?'\\':'/')`

Try it here.
> 2 votes

# Answer
# Haskell, ~~46~~ ~~45~~ 44 bytes

```
f z@(x:_)|x<'/'=' ':z|x<'0'='\\':z|1<2='/':z

```

Takes advantage of the fact that  \< `.` \< `/` \< `0` \< `\` in the ASCII table to save two bytes
> 2 votes

# Answer
# ECMAScript 6 / 2015 (JavaScript), 41 bytes

```
s=>s<'/'?' '+s:s+'\\/'[s.slice(-1)>'/'|0]

```

*Good catch Neil.*
> 1 votes

# Answer
## Python 2, 72 bytes

```
lambda x:x[:-1]+(" .","\/","/\\")[ord(x[-1])/46+(-1,1)[ord(x[-1])%46>0]]

```

Any help golfing more would be greatly appreciated!

This takes the last character in the input and converts it into its ASCII code to get the corresponding index in the list of two characters. Those two characters are appended to all the characters of the input up until the last one.
> 1 votes

# Answer
## C#, ~~80~~ 63 bytes

```
s=>{var c=s[s.Length-1];return c<'/'?" "+s:c>'/'?s+"/":s+"\\";}

```
> 1 votes

# Answer
## Perl, 30 + 1 (`-p`) = 31 bytes

```
s/\./ ./,s|/$|/\\|||s|\\$|\\/|

```

Needs `-p` and `-M5.010` or `-E` to run :

```
perl -pE 's/\./ ./,s|/$|/\\|||s|\\$|\\/|' <<< ".
  .
    .
/
/\/"

```

Straight forward implementation of the challenge. (Note that the `||` between the last two regex are `or`, as it might be hard to read, so the three regex are : `s/\./ ./`, and `s|/$|/\\|`, and `s|\\$|\\/|`)
> 1 votes

# Answer
# SQF, 91

Using the function-as-a-file format:

```
s=_this;switch(s select[(count s)-1])do{case".":{" "+s};case"\":{s+"/"};case"/":{s+"\"};}

```

Call as `"STRING" call NAME_OF_COMPILED_FUNCTION`
> 1 votes

# Answer
## PowerShell v2+, ~~59~~ ~~58~~ ~~52~~ 51 bytes

```
param($n)(" $n","$n/","$n\")['.\/'.IndexOf($n[-1])]

```

Takes input `$n`, dumps it an array index operation. We select the element of the array based on the index `['.\/'.IndexOf($n[-1])` -- i.e., based on the last character of the input `$n`, this will result in `0`, `1`, or `2`. That corresponds to the appropriate string of the array. In any case, the resulting string is left on the pipeline and printing is implicit.

### Test cases

```
PS C:\Tools\Scripts\golfing> 0..7|%{' '*$_+'.'}|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
. =>  .
 . =>   .
  . =>    .
   . =>     .
    . =>      .
     . =>       .
      . =>        .
       . =>         .

PS C:\Tools\Scripts\golfing> '/,\,/\,\/,/\/,\/\,/\/\,\/\/'-split','|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
/ => /\
\ => \/
/\ => /\/
\/ => \/\
/\/ => /\/\
\/\ => \/\/
/\/\ => /\/\/
\/\/ => \/\/\

```
> 1 votes

# Answer
## C#, 54 bytes

```
s=>s.EndsWith(".")?" "+s:s+(s.EndsWith("/")?"\\":"/");

```
> 1 votes

# Answer
# SED, 41 36 27

saved 7 thanks to charlie

```
 s|\.| .|;s|/$|/\\|;t;s|$|/|

```

uses 3 substitutions:
`s/\./ ./` adds a space if there is a `.`
`s|/$|/\\|`,`s|$|/|` adds the appropriate slash to the end
uses `|` instead of `/` as the delimiter

`t` branches to the end if the second regex matches so it doesn't add the other slash
> 1 votes

# Answer
# ARM machine code on Linux, 50 bytes

Hex dump:

```
b580 1e41 f811 2f01 2a00 d1fb 3901 780b 1a0a 4601 2001 2704 df00 2000 a103 2202 f013 0303 2b03 4159 df00 bd80 2e202f5c 5c2f

```

First post here, hope I'm doing this right. This is 32-bit ARM assembly, specifically Thumb-2. The input string is a NUL-terminated string taken in through r0, the output is printed to the stdout. In C-syntax, the prototype for the function would be void func\_name(char\* string). It is AAPCS (ARM calling convention) complaint, if it weren't then 2 bytes could be shaved off.

Here's the equivalent assembly, with comments explaining what's happening:

```
    @Input: r0 is char* (the string)
    @Output: Modified string to console
    push {r7,lr} @Save r7 and the link register
    subs r1,r0,#1 @Make a copy of the char*, subtracting because we're
    @going to pre-increment.
    loop: @This loop is a little strlen routine
            ldrb r2,[r1,#1]! @In C-syntax, r2=*++r1;
            cmp r2,#0
            bne loop
    @Now r1 points to the null character that terminates the string
    subs r1,r1,#1 @Make r1 point to the last character
    ldrb r3,[r1] @Load the last character into r3
    subs r2,r1,r0 @r2=length(r0) - 1;
    mov  r1,r0 @r0 holds the original char*
    movs r0,#1 @1 is the file descriptor for stdout
    movs r7,#4 @4 is write
    swi #0

    @Now all the characters from the initial string have been printed,
    @except for the last one, which is currently in r3.

    movs r0,#1 @1 is stdout, have to reload this since the system call
    @returns in r0.
    adr r1,msg @Load msg into r1 (the pointer to the string)
    movs r2,#2 @We're going to print two more characters.

    @Now the bit magic. The ascii codes for '\', '.', and '/' map onto
    @0, 2, and 3 when bitwise anded with 3 (0b11).
    @This will be the offset into our string. However, since we must print
    @2 characters, we need our offsets to be 0, 2, and 4.
    @Therefore, we only set the carry if our value is >=3, then add with
    @carry (adcs). Thus we get the correct offset into the string msg.
    ands r3,r3,#3
    cmp r3,#3 @Sets carry if r3>=3
    adcs r1,r1,r3 @Add the offset to r1
    swi #0 @Make the system call
    pop {r7,pc} @Return and restore r7
msg:
    .ascii "\\/ ./\\" @The three different sequences of 2 characters that
    @can go at the end.

```
> 1 votes

# Answer
# R, 119 bytes

```
a=scan(,"");if((q=strsplit(a,"")[[1]][nchar(a)])=="."){cat(" ",a,sep="")}else{s=switch(q,"/"="\\","/");cat(a,s,sep="")}

```

**Ungolfed :**

```
a=scan(,"")
if((q=strsplit(a,"")[[1]][nchar(a)])==".")
    cat(" ",a,sep="")

else
s=switch(q,"/"="\\","/")
cat(a,s,sep="")

```
> 1 votes

# Answer
# Turtlèd, 32 bytes (noncompeting)

```
l!-[*+.r_]l(/r'\r)(\r'/)(." .")$

```

Explanation:

```
[implicit]                       first cell is an asterisk

l                                move left, off the asterisk, so the '[*+.r_]' loop runs
 !                               take input into string var, char pointer=0, 1st char
  -                              decrement char pointer, mod length input

   [*    ]                       while current cell isn't *:
     +.                          increment string pointer, and write the pointed char
       r_                        move right, write * if pointed char is last char, else " "

          l                      move left

           (/    )               if the current cell is /
             r'\r                move right, write /, move right

                  (\   )         If the current cell is \
                    r'/          move right, write /

                        (.    )  If the current cell is .
                          " ."   Write " .", the first space overwriting the existing '.'

                               $ Program won't remove leading spaces when printing

    [implicit]                   Program prints grid after finishing execution

```
> 1 votes

# Answer
# Java 7, 76 bytes

```
String c(String i){return i.contains(".")?" "+i:i+(i.endsWith("/")?92:'/');}

```

Pretty straightforward.

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(String i){
    return i.contains(".")
            ? " " + i
            : i + (i.endsWith("/")
                    ? 92
                    : '/');
  }

  public static void main(String[] a){
    System.out.println(c(" ."));
    System.out.println(c("  ."));
    System.out.println(c("   ."));
    System.out.println(c("    ."));
    System.out.println(c("     ."));
    System.out.println(c("      ."));
    System.out.println(c("       ."));
    System.out.println(c("        ."));
    System.out.println(c("/"));
    System.out.println(c("\\"));
    System.out.println(c("/\\"));
    System.out.println(c("\\/"));
    System.out.println(c("/\\/"));
    System.out.println(c("\\/\\"));
    System.out.println(c("/\\/\\"));
    System.out.println(c("\\/\\/"));
  }
}

```

**Output:**

```
  .
   .
    .
     .
      .
       .
        .
         .
/\
\/
/\/
\/\
/\/\
\/\/
/\/\/
\/\/\

```
> 1 votes

# Answer
# Pyth - 16 bytes

```
?}\.Q+dQ+Q-"\/"e

```

Test Suite.
> 0 votes

# Answer
## Javascript: 60 bytes

```
 i=>i.includes(".")?" "+i:i.charAt(i.length-1)=="/"?i+"\\":i+"/"

```
> 0 votes

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


title: String Concatenation

text:
# Question
Title: String Concatenation
**The Challenge**

> Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.
>
> You can assume the strings will always be different lengths.

**Test Cases:**

```
sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)

```

**Rules**

> This is code-golf, so shortest answer in bytes wins!

# Answer
> 5 votes
# Pyth, 13 bytes

```
++hAlDQ\_.-HG

```

Try it online.

# Answer
> 3 votes
## JavaScript (ES6), ~~78~~ ~~75~~ 69 Bytes

```
const
     g=(x,y)=>x[y.length]?g(y,x):[...x].map(c=>y=y.replace(c,''))&&x+'_'+y
;

console.log(g.toString().length + 2);   // 69
console.log(g('sale', 'salinewater'))   // sale_inwater
console.log(g('juggle', 'juggler'))     // juggle_r
console.log(g('jostling','juggle'))     // juggle_ostin
```

### Breakdown

```
x[y.length]?g(y,x):        \\ Make sure that x is the shorter string
[...x]                     \\ Spread string in array of characters
.map(c=>y=y.replace(c,'')) \\ For each character remove its first occurence in y
&&x+'_'+y                  \\ Concat x and changed y

```

# Answer
> 2 votes
# Haskell, ~~56~~ 55 bytes

```
import Data.List
x%y|(0<$y)<(0<$x)=y%x|z<-y\\x=x++'_':z

```

*-1 byte thanks to @xnor*

# Answer
> 1 votes
# Java 7, 262 bytes

```
import java.util.*;String c(String z,String y){int i=0,l=y.length();if(z.length()>l)return c(y,z);List x=new ArrayList();for(;i<l;x.add(y.toCharArray()[i++]));for(Object q:z.toCharArray())x.remove(q);String r="";for(i=0;i<x.size();r+=x.get(i++));return z+"_"+r;}

```

Can probably be golfed some more by just using arrays without the lists..

**Ungolfed & test cases:**

Try it here.

```
import java.util.*;
class M{
  static String c(String z, String y){
    int i = 0,
        l = y.length();
    if(z.length() > l){
      return c(y, z);
    }
    List x = new ArrayList();
    for(; i < l; x.add(y.toCharArray()[i++]));
    for(Object q : z.toCharArray()){
      x.remove(q);
    }
    String r = "";
    for(i = 0; i < (x.size()); r += x.get(i++));
    return z+"_"+r;
  }

  public static void main(String[] a){
    System.out.println(c("sale", "salinewater"));
    System.out.println(c("jostling", "juggle"));
    System.out.println(c("juggle", "juggler"));
  }
}

```

**Output:**

```
sale_inwater
juggle_ostin
juggle_r

```

# Answer
> 1 votes
# Java 8, 156 Bytes

```
String a(String x,String y){int l=x.length(),m=y.length();String b=l>m?x:y,s=m<l?y:x;for(char c:s.toCharArray()){b=b.replaceFirst(""+c,"");}return s+"_"+b;}

```

This can probably be golfed some more.

**Ungolfed & test cases**

```
interface A {
    static String a(String x,String y){
        int l=x.length(),m=y.length();
        String b=l>m?x:y,s=m<l?y:x;
        for(char c:s.toCharArray()){
            b=b.replaceFirst(""+c,"");
        }
        return s+"_"+b;
    }

    static void main(String[]a) {
        System.out.println(a("sale","salinewater"));
        System.out.println(a("jostling","juggle"));
        System.out.println(a("juggle","juggler"));
    }
}

```

# Answer
> 1 votes
## Ruby, 65 bytes

```
->a,b{a,b=b,a if a.size>b.size;a.chars.map{|e|b.sub!e,""};a+?_+b}

```

### ungolfed

```
->a, b{
  a, b = b, a if a.size > b.size
  a.chars.map { |e|
    b.sub! e, ""
  }
  a + ?_ + b
}

```

### 61 bytes(in case the argument is an array of strings)

```
->a{a.sort_by!(&:size);a[0].chars.map{|c|a[1].sub!c,""};a*?_}

```

Thank you, m-chrzan!

# Answer
> 0 votes
# Python 2, ~~81~~ 72 bytes

```
a,b=sorted(input(),key=len)
for c in a:b=b.replace(c,"",1)
print a+"_"+b

```

**Try it online**

# Answer
> 0 votes
# PHP, 154 Bytes

```
list($f,$s)=strlen($b=$argv[2])<strlen($a=$argv[1])?[$b,$a]:[$a,$b];foreach(str_split($f)as$x)$s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s);echo$f."_$s";

```

Instead of `$s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s);` you can also use `if($z=strstr($s,$x))$s=strstr($s,$x,1).substr($z,1);`

# Answer
> 0 votes
## R, 161 bytes

This turned out to be much longer than I expected, albeit, string manipulation is usually tedious in R. I feel that this should easily be golfable by just using another approach.

```
function(x,y){s=strsplit;if(nchar(x)>nchar(y)){v=y;w=x}else{v=x;w=y};v=s(v,"")[[1]];w=s(w,"")[[1]];j=0;for(i in v){j=j+1;if(i==w[j])w[j]=""};cat(v,"_",w,sep="")}

```

### Ungofled

```
function(x,y){
    s=strsplit                      # alias for stringsplit
    if(nchar(x)>nchar(y)){v=y;w=x}  # assign v/w for the short/long strings
    else{v=x;w=y}
    v=s(v,"")[[1]]                  # split short string into vector
    w=s(w,"")[[1]]                  # split long string into vector
    j=0
    for(i in v){                    # for each char in short string, check
        j=j+1                       # if is equal to corresponding char in
        if(i==w[j])w[j]=""          # long, replace long with "" if true
    }
    cat(v,"_",w,sep="")             # insert _ and print
}

```

# Answer
> 0 votes
# Scala, 78 bytes

```
def f(a:String,b:String):String={if(a.size>b.size)f(b,a)else
a+"_"+(b diff a)}

```

Explanation:

```
def f(a:String,b:String):String={ //define a method f which has two String parameters and returns a String
                                  //(because it's recursive, scala can't figure out the return type)
  if (a.size > b.size)            //make sure that a is the shorter string
    f(b, a)
  else
    a+"_"+(b diff a)              //`b diff a` removes all elements/chars of a from b
}

```

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


title: The Decanting Problem

text:
# Question
Title: The Decanting Problem
Given *N* decanters (0 \< *N* \< 10) with that can hold *C0* ... *CN-1* liters (0 \< *C* \< 50) and a goal *G* liters, please determine if it is possible to reach that goal using only the following actions:

* Fill a decanter
* Empty a decanter
* Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount *G* must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

## Examples

*N*: 2
*C0*: 5
*C1*: 12
*G*: 1
Result: Yes

*N*: 3
*C0*: 6
*C1*: 9
*C2*: 21
*G*: 5
Result: No

**Hint:** To calculate if it is possible, check to see if *G* is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is , so the code with the lowest number of bytes wins.

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=94202,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(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){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<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="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Jelly, ~~9 8~~ 7 bytes

-1 byte thanks to @Dennis (use integer division, `:`, rather than not less than, )

```
Ṁ:a⁸g/ḍ

```

**TryItOnline**

How?

```
Ṁ:a⁸g/ḍ - Main link: capacities, goal
Ṁ       - maximum capacity
 :      - integer division with goal (effectively not less than goal since non-0 is True)
  a     - and
   ⁸    - left argument (capacities)
    g/  - gcd reduce over list (gcd of capacities)
      ḍ - divides

```
> 5 votes

# Answer
## Haskell, 35 bytes

```
l%n=n`mod`foldr1 gcd l<1&&any(>=n)l

```

This paper proves a result that vastly simplifies the problem. Prop 1 says that

> You can achieve a goal exactly when it's both:
>
> * A multiple of the greatest common divisor (gcd) of the capacities,
> * At most the maximum capacity

It's clear why both of these are necessary: all amounts remain multiples of the gcd, and the goal must fit in a container. The key of the result is an algorithm to produce any goal amount that fits these conditions.

Call the operator `%` like `[3,6,12]%9`.

A 37-byte alternative:

```
l%n=elem n[0,foldr1 gcd l..maximum l]

```
> 17 votes

# Answer
# 05AB1E, ~~9~~ ~~8~~ 9 bytes

Uses the CP-1252 encoding

```
ZU¿%²X>‹‹

```

**Explanation**

```
          # true if
   %      # target size modulo
ZU¿       # gcd of decanter sizes
        ‹ # is smaller than
    ²X>‹  # target size is less than or equal to max decanter size

```

Try it online!

Saved 1 byte utilizing the less than trick from Luis Mendo's MATL answer
> 6 votes

# Answer
# MATL, 10 bytes

```
&Zd\&G<~a<

```

Try it online!

This uses @xnor's approach.

```
&Zd    % Take array C as input. Compute the gcd of its elements
\      % Take number G as input. Compute that number modulo the above. Call this A
&G     % Push the two inputs again: C, then G
<~a    % Gives 1 if some element of C is at least G; 0 otherwise. Call this B
<      % Gives true if A is 0 and B is 1; otherwise gives false

```
> 5 votes

# Answer
## JavaScript (ES6), 58 bytes

```
(n,a)=>a.some(e=>n<=e)&n%a.reduce(g=(d,e)=>d?g(e%d,d):e)<1

```

Another port of @xnor's answer. Yes, I get to use `reduce` again!
> 5 votes

# Answer
# Excel: 43 bytes

`=AND(MOD(A10,GCD(A1:A9))=0,A10<=MAX(A1:A9))`

Try it online!

**How to use:**
Put this formula anywhere Except A1-A10.
Then input your Decant holding volumes in cells A1:A9 (because the number of decants is fixed) and the goal in A10. cells without decants should be left blank. Wherever you put the formula will contain the result. TRUE if you can achieve the goal, FALSE if you cannot.
> 5 votes

# Answer
## Retina, 39 bytes

```
\d+
$*
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

```

Input should be a comma-separated list of the decanters, followed by a semicolon, followed by the target volume. E.g.:

```
6,9,21;5

```

Output is `0` (falsy) or `1` (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

```
\d+
$*

```

This just converts the input to unary. Afterwards we simply match valid inputs with a single regex:

```
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

```

The part inside `(?>...)` finds the GCD. We do this by finding the largest substring `1+` with which we can match all the decanters (allowing an optional `,` only after a full match of the GCD). The atomic group (the `(?>...)`) itself so that the regex engine doesn't backtrack to divisors of the GCD if the target volume can't be matched (otherwise group `1` will at some point be reduced to matching a single `1` and all inputs will be truthy).

Once we've found the GCD, we try to match the target volume as a multiple of it with a simple `(\1+)$`.

Finally, we check that the target volume not greater than the largest decanter's capacity, by ensuring that the volume can be matched inside any decanter with `(?<=\3.+)`.
> 4 votes

# Answer
# Ruby, 35 bytes

```
->n,g{g<=n.max&&1>g%n.reduce(:gcd)}

```
> 3 votes

# Answer
# PARI/GP, 31 bytes

Pretty much straightforward. Checking the max (`vecmax`) is very costly, I wonder if it can be done better.

```
f(c,g)=g%gcd(c)<1&&vecmax(c)>=g

```
> 2 votes

# Answer
# Perl, 47 bytes

Includes +2 for `-ap`

Run with the jar sizes on the first line of STDIN and the target jar on the second line:

```
decanter.pl; echo
2 5 12
1
^D

```

`decanter.pl`:

```
#!/usr/bin/perl -p
$_=($_<@G)>$_%$=;$=--while@G[@F]=grep$_%$=,@F

```

This solution is unusual in that it processes the input line by line and outputs something for each of them. The output for the first line was carefully designed to be empty while the second line prints the solution. Two bytes are lost on `()` because `<` and `>` are designed to be non-associative in perl.

The regex solution is also nice but 49 bytes:

```
#!/usr/bin/perl -p
s/\d+/1x$&/eg;$_=/^(?>(1+)( |\1)*:)(\1+)$/&/$3./

```

(some parts stolen from the Retina solution)

For this one give input on STDIN as jars separated by spaces and target after a `:`:

```
decanter.pl <<< "2 5 12:1"

```

Hard to beat languages with a builtin `gcd` (21 bytes) and `max` (7 bytes) for this one...
> 2 votes

# Answer
# Scala, ~~90~~ 53 bytes

```
def h(g:Int,a:BigInt*)=a.max>g&&a.reduce(_ gcd _)%g<1

```

Works basically the same as the other answers, ~~but scala doesn't have a built-in gcd function.~~ Scala has a built.in gcd function, but only for BigInt.
> 0 votes

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


title: String Distance

text:
# Question
Title: String Distance
# Challenge

Given an input of an all-lowercase string `[a-z]`, output the total distance between the letters.

## Example

```
Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17

```

## Rules

* Standard loopholes forbidden
* This is - shortest answer in bytes wins.
* The alphabet can be traversed from either direction. **You must always use the shortest path.** (i.e the distance between `x` and `c` is 5).

# Test cases

```
Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35

```

# Answer
# Jelly, ~~11~~ 8 bytes

```
OIæ%13AS

```

Saved 3 bytes thanks to @Martin Ender.

Try it online! or Verify all test cases.

## Explanation

```
OIæ%13AS  Input: string Z
O         Ordinal. Convert each char in Z to its ASCII value
 I        Increments. Find the difference between each pair of values
  æ%13    Symmetric mod. Maps each to the interval (-13, 13]
      A   Absolute value of each
       S  Sum
          Return implicitly

```
> 11 votes

# Answer
## Haskell, ~~57~~ 56 bytes

```
q=map$(-)13.abs
sum.q.q.(zipWith(-)=<<tail).map fromEnum

```

Usage example: `sum.q.q.(zipWith(-)=<<tail).map fromEnum $ "valleys"` -\> `35`.

How it works:

```
q=map$(-)13.abs                -- helper function.
                               -- Non-pointfree: q l = map (\e -> 13 - abs e) l
                               -- foreach element e in list l: subtract the
                               -- absolute value of e from 13

               map fromEnum    -- convert to ascii values
      zipWith(-)=<<tail        -- build differences of neighbor elements
  q.q                          -- apply q twice on every element
sum                            -- sum it up

```

Edit: @Damien saved one byte. Thanks!
> 10 votes

# Answer
# MATL, ~~14~~, 10 bytes

```
dt_v26\X<s

```

Try it online!

*Thanks @Suever for saving 4 bytes!*

Explanation:

```
d           % Take the difference between consecutive characters
 t_         % Make a copy of this array, and take the negative of each element
   v        % Join these two arrays together into a matrix with height 2
    26\     % Mod 26 of each element
       X<   % Grab the minimum of each column
         s  % Sum these. Implicitly print

```

Previous version:

```
d26\t13>26*-|s

```
> 8 votes

# Answer
## Python 3, ~~69~~ 68 bytes

```
lambda s:sum([13-abs(13-abs(ord(a)-ord(b)))for a,b in zip(s,s[1:])])

```

Breakdown:

```
lambda s:
         sum(                                                      )
             [                             for a,b in zip(s,s[1:])]
              13-abs(13-abs(ord(a)-ord(b)))

```
> 6 votes

# Answer
# Java, ~~126~~ ~~120~~ 117 bytes

```
int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=(26+z[i]-z[i-1])%26)<14?e:26-e);return r;}

```

Thanks to @KevinCruijssen for pointing out a bug in the original version and suggesting to make the for-loop empty.

The use of `(26 + z[i] - z[i - 1]) % 26)` is inspired from a comment by @Neil on another answer. `(26 + ...)%26` serves the same purpose as `Math.abs(...)` because of `...? e : 26 - e`.

**Ungolfed**:

```
int f(String s) {
    byte[]z = s.getBytes();
    int r = 0, i = 0, e;
    for (; ++i < z.length; r += (e = (26 + z[i] - z[i - 1]) % 26) < 14 ? e : 26 - e);
    return r;
}

```
> 5 votes

# Answer
## JavaScript (ES6), ~~84~~ ~~82~~ 79 bytes

Saved 3 bytes thanks to Cyoce:

```
f=([d,...s],p=parseInt,v=(26+p(s[0],36)-p(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

```

**Explanation:**

```
f=(
  [d,...s],                    //Destructured input, separates first char from the rest
  p=parseInt,                  //p used as parseInt
  v=(26+p(s[0],36)-p(d,36))%26 //v is the absolute value of the difference using base 36 to get number from char
  )
)=>
  s[0]?                        //If there is at least two char in the input
    f(s)                       //sum recursive call
    +                          //added to
    (v>13?26-v:v)              //the current shortest path
  :                            //else
    0                          //ends the recursion, returns 0

```

**Example:**
Call: `f('golf')`
Output: `17`

---

Previous solutions :

82 bytes thanks to Neil:

```
f=([d,...s],v=(26+parseInt(s[0],36)-parseInt(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0

```

84 bytes:

```
f=([d,...s],v=Math.abs(parseInt(s[0],36)-parseInt(d,36)))=>s[0]?f(s)+(v>13?26-v:v):0

```
> 3 votes

# Answer
## Ruby, 73 bytes

```
->x{eval x.chars.each_cons(2).map{|a,b|13-(13-(a.ord-b.ord).abs).abs}*?+}

```
> 3 votes

# Answer
# PHP, 93 Bytes

```
for(;++$i<strlen($s=$argv[1]);)$r+=13<($a=abs(ord($s[$i-1])-ord($s[$i])))?$a=26-$a:$a;echo$r;

```
> 2 votes

# Answer
# 05AB1E, 12 bytes

```
SÇ¥YFÄ5Ø-}(O

```

**Explanation**

```
SÇ                   # convert to list of ascii values
  ¥                  # take delta's
   YF    }           # 2 times do
     Ä5Ø-            # for x in list: abs(x) - 13
          (O         # negate and sum

```

Try it online!
> 2 votes

# Answer
## Racket 119 bytes

```
(λ(s)(for/sum((i(sub1(string-length s))))(abs(-(char->integer
(string-ref s i))(char->integer(string-ref s(+ 1 i)))))))

```

Testing:

```
(f "golf")

```

Output:

```
17

```

Detailed version:

```
(define(f s)
  (for/sum((i(sub1(string-length s))))
    (abs(-(char->integer(string-ref s i))
          (char->integer(string-ref s(+ 1 i)))))))

```
> 2 votes

# Answer
# Perl, 46 bytes

Includes +3 for `-p` (code contains `'`)

Give input on STDIN without final newline:

```
echo -n zaza | stringd.pl

```

`stringd.pl`:

```
#!/usr/bin/perl -p
s%.%$\+=13-abs 13-abs ord($&)-ord$'.$&%eg}{

```
> 2 votes

# Answer
# Actually, 21 bytes

Based partially on cia\_rana's Ruby answer.

There was a bug with `O` (in this case, map ord() over a string) where it would not work with `d` (dequeue bottom element) and `p` (pop first element) without first converting the map to a list with `#`. This bug has been fixed, but as that fix is newer than this challenge, so I've kept `#` in.

**Edit:** And the byte count has been wrong since September. Whoops.

Golfing suggestions welcome. Try it online!

```
O#;dX@pX♀-`A;úl-km`MΣ

```

**Ungolfing**

```
         Implicit input string.
          The string should already be enclosed in quotation marks.
O#       Map ord() over the string and convert the map to a list. Call it ords.
;        Duplicate ords.
dX       Dequeue the last element and discard it.
@        Swap the with the duplicate ords.
pX       Pop the last element and discard it. Stack: ords[:-1], ords[1:]
♀-       Subtract each element of the second list from each element of the first list.
          This subtraction is equivalent to getting the first differences of ords.
`...`M   Map the following function over the first differences. Variable i.
  A;       abs(i) and duplicate.
  úl       Push the lowercase alphabet and get its length. A golfy way to push 26.
  -        26-i
  k        Pop all elements from stack and convert to list. Stack: [i, 26-i]
  m        min([i, 26-i])
Σ        Sum the result of the map.
         Implicit return.

```
> 2 votes

# Answer
# C#, 87 85 bytes

**Improved** solution - *replaced Math.Abs() with the add & modulo trick to save 2 bytes:*

```
s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;};

```

**Initial** solution:

```
s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

```

**Try it online!**

Full source, including test cases:

```
using System;

namespace StringDistance
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

            Console.WriteLine(f("golf"));   //17
            Console.WriteLine(f("aa"));     //0
            Console.WriteLine(f("stack"));  //18
            Console.WriteLine(f("zaza"));   //3
            Console.WriteLine(f("valleys"));//35
        }
    }
}

```
> 2 votes

# Answer
# Java 7,128 bytes

```
 int f(String s){char[]c=s.toCharArray();int t=0;for(int i=1,a;i<c.length;a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);return t;}

```

# Ungolfed

```
 int f(String s){
 char[]c=s.toCharArray();
 int t=0;
 for(int i=1,a;
     i<c.length;
   a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);
return t;
 }

```
> 1 votes

# Answer
# Pyth, 20 bytes

```
Lm-13.adbsyy-M.:CMQ2

```

A program that takes input of a quoted string on STDIN and prints the result.

Try it online

**How it works**

```
Lm-13.adbsyy-M.:CMQ2  Program. Input: Q
L                     def y(b) ->
 m      b              Map over b with variable d:
  -13                   13-
     .ad                abs(d)
                CMQ   Map code-point over Q
              .:   2  All length 2 sublists of that
            -M        Map subtraction over that
          yy          y(y(that))
         s            Sum of that
                      Implicitly print

```
> 1 votes

# Answer
# C#, 217 bytes

Golfed:

```
IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}}

```

Ungolfed:

```
IEnumerable<int> g(string k)
{
  Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97;
  for (int i = 0; i < k.Length - 1; i++)
  {
    var f = x(k[i]);
    var s = x(k[i + 1]);
    var d = Math.Abs(f - s);
    yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d;
  }
}

```

Output:

```
aa: 0
stack: 18
zaza: 3
valleys: 35

```

'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes!
> 1 votes

# Answer
## dc + od, 65 bytes

```
od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp'

```

**Explanation:**

Because in *dc* you can't access a string's characters, I used *od* to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so:

```
dsN0sT             # initialize N (neighbor) = top ASCII value, and T (total) = 0
[lNrdsNr-          # loop 'R': calculate difference between current value and N,
                   #updating N (on the first iteration the difference is 0)
   d*vdD[26-]sS<S  # get absolute value (d*v), push 13 (D) and call 'S' to subtract
                   #26 if the difference is greater than 13
   d*vlT+sT        # get absolute value again and add it to T
d0<R]dsR           # repeat loop for the rest of the ASCII values
xlTp               # the main: call 'R' and print T at the end

```

**Run:**

```
echo -n "golf" | ./string_distance.sh

```

**Output:**

```
17

```
> 1 votes

# Answer
# C, ~~82 86 83~~ 76 bytes

```
t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;}

```

Assumes input string is at least one character long. This doesn't require `#include<stdlib.h>`

Edit: Argh, sequence points!

Try it on Ideone
> 1 votes

# Answer
# Scala, 68 bytes

```
def f(s:String)=(for(i<-0 to s.length-2)yield (s(i)-s(i+1)).abs).sum

```

Criticism is welcome.
> 1 votes

# Answer
# C, 70 bytes ~~76 bytes~~

```
k,i;f(char *s){for(i=0;*++s;i+=(k=abs(*s-s[-1]))>13?26-k:k);return i;}

```
> 1 votes

# Answer
# Python 3, 126 bytes

With list *in*comprehension.

```
d=input()
print(sum([min(abs(x-y),x+26-y)for x,y in[map(lambda x:(ord(x)-97),sorted(d[i:i+2]))for i in range(len(d))][:-1]]))

```
> 0 votes

# Answer
# PHP, 79 bytes

```
for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s;

```
> 0 votes

# Answer
# Java, 109 bytes

```
int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x;

```
> 0 votes

---
Tags: code-golf, string, number, arithmetic
---


title: Minecraft castle fractal

text:
# Question
Title: Minecraft castle fractal
*Inpsired by a youtube video from a fellow PPCG user...*

You challenge is to use ASCII-art draw a Minecraft castle wall of Andesite and Diorite. The *shape* of the wall is the Cantor Set. For reference, the Cantor Set is made by repeating the following **N** times:

* Triple the current step
* Replace the middle one with blank space
* Add a full line below it

This creates the following for the first four steps:

```
*

* *
***

* *   * *
***   ***
*********

* *   * *         * *   * *
***   ***         ***   ***
*********         *********
***************************

```

However, your challenge is not quite that simple. You see, after the cantor set gets really big, it becomes boring to look at the same character repeated over and over and over. So we're going to change that by overlaying an alternating series of asterisks `*` and pound signs `#`. You should alternate on every three characters horizontally, and on every row vertically. (Of course leaving the spaces the same) For example, the second example will become:

```
* *
###

```

and the third example will become:

```
* *   * *
###   ###
***###***

```

For completeness, here are examples four and five:

```
#4
* *   * *         * *   * *
###   ###         ###   ###
***###***         ***###***
###***###***###***###***###

#5
* *   * *         * *   * *                           * *   * *         * *   * *
###   ###         ###   ###                           ###   ###         ###   ###
***###***         ***###***                           ***###***         ***###***
###***###***###***###***###                           ###***###***###***###***###
***###***###***###***###***###***###***###***###***###***###***###***###***###***

```

And one **mega** example, the 6th iteration:

```
* *   * *         * *   * *                           * *   * *         * *   * *                                                                                * *   * *         * *   * *                           * *   * *         * *   * *
###   ###         ###   ###                           ###   ###         ###   ###                                                                                ###   ###         ###   ###                           ###   ###         ###   ###
***###***         ***###***                           ***###***         ***###***                                                                                ***###***         ***###***                           ***###***         ***###***
###***###***###***###***###                           ###***###***###***###***###                                                                                ###***###***###***###***###                           ###***###***###***###***###
***###***###***###***###***###***###***###***###***###***###***###***###***###***                                                                                ***###***###***###***###***###***###***###***###***###***###***###***###***###***
###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###***###

```

# The challenge

You must write a full program or function that accepts a positive integer for input, and outputs the *N*'th generation of this minecraft castle fractal. You can take Input and output by any reasonable method, and you do not have to worry about invalid inputs (such as numbers less than 1, floating point numbers, non-numbers, etc.).

The shortest answer, measured in bytes wins!

# Answer
> 5 votes
# Jelly, ~~43~~ ~~36~~ 35 bytes

```
ḶṚ3*µ5B¤xÐ€ṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y

```

Just a start, I'm sure this could be shorter.

Try it online!

\*For *n* \> 5, your browser might wrap the output but if you copy-paste it into a non-wrapping editor, you will see the proper output.

## Explanation

```
ḶṚ3*µ5B¤xÐ€ṁ€Ṁ×\Ṛ©1,‘xS$¤ṁ×®ị“*# ”Y  Input: integer n
Ḷ                                    Create the range [0, n)
 Ṛ                                   Reverse it
  3*                                 Raise 3 to the power of each
    µ                                Begin a new monadic chain on the powers of 3
     5B¤                             Nilad. Get the binary digits of 5 = [1, 0, 1]
        xÐ€                          Duplicate each of [1, 0, 1] to a power of 3 times
             Ṁ                       Get the maximum of the powers of 3
           ṁ€                        Reshape each to a length of that value
              ×\                     Cumulative products
                Ṛ©                   Reverse and save the result
                  1,‘xS$¤            Niladic chain.
                  1                    Start with 1
                    ‘                  Increment it
                   ,                   Pair them to get [1, 2]
                       $               Operate on [1, 2]
                      S                  Sum it to get 3
                     x                   Repeat each 3 times to get [1, 1, 1, 2, 2, 2]
                         ṁ           Reshape that to the saved table
                          ×®         Multiply elementwise with the saved table
                            ị“*# ”   Use each to as an index to select from "*# "
                                  Y  Join using newlines
                                     Return and print implicitly

```

# Answer
> 3 votes
## JavaScript (ES7), ~~132~~ 125 bytes

```
n=>[...Array(n)].map((_,i)=>[...Array(3**~-n)].map((_,j)=>/1/.test((j/3**i|0).toString(3))?" ":`*#`[j/3+i&1]).join``).join`\n`

```

Where `\n` represents the literal newline characer. ES6 version for 141 bytes:

```
f=
n=>[...Array(n)].map((_,i)=>[...Array(Math.pow(3,n-1))].map((_,j)=>/1/.test((j*3).toString(3).slice(0,~i))?" ":`*#`[j/3+i&1]).join``).join`
`
;
```

```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```

# Answer
> 2 votes
# Python 2, ~~142~~ ~~138~~ 136 bytes

```
r=range
def f(n):
 for i in r(n+1):
  s="";d=i%2<1
  for k in r(3**i):s+="#*"[(6+d-1+k*(d*2-1))%6<3]
  exec"s+=len(s)*' '+s;"*(n-i);print s

```

This is the piece of code from here, and then edited for this challenge.

Will post an explanation later.

Also, BTW, two spaces are tabs.

**Edit 1: 4 bytes saved thanks to @DJMcMayhem.**

**Edit 2: 2 bytes saved thanks to @daHugLenny.**

# Answer
> 1 votes
# Ruby, ~~115~~ ~~103~~ 102 bytes

```
->n{g=->{T.tr"*#","#*"}
*s=?*
(n-1).times{|i|T=s[-1]
s=s.map{|l|l+' '*3**i+l}+[i<1??#*3:g[]+T+g[]]}
s}

```

Based on jsvnm's solution to the standard Cantor set golf.

-12 bytes thanks to Jordan.

# Answer
> 1 votes
# J, ~~47~~ 45 bytes

```
' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<:

```

Based on my solution to the Cantor set challenge.

## Usage

```
   f =: ' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<:
   f 1
*
   f 2
* *
###
   f 3
* *   * *
###   ###
***###***

```

## Explanation

```
' *#'{~3(]*$@]$1 2#~[)(,:1)1&(,~],.0&*,.])~<:  Input: n
                                           <:  Decrement n
                      (,:1)                    A constant [1]
                           1&(           )~    Repeating n-1 times on x starting
                                               with x = [1]
                                        ]        Identity function, gets x
                                   0&*           Multiply x elementwise by 0
                                      ,.         Join them together by rows
                                ]                Get x
                                 ,.              Join by rows
                           1  ,~                 Append a row of 1's and return
       3                                       The constant 3
        (                 )                    Operate on 3 and the result
                    [                          Get LHS = 3
               1 2                             The constant [1, 2]
                  #~                           Duplicate each 3 times
                                               Forms [1, 1, 1, 2, 2, 2]
           $@]                                 Get the shape of the result
              $                                Shape the list of [1, 2] to
                                               the shape of the result
         ]                                     Get the result
          *                                    Multiply elementwise between the
                                               result and the reshaped [1, 2]
' *#'                                        The constant string ' *#'
     {~                                       Select from it using the result
                                             as indices and return

```

# Answer
> 1 votes
# PHP, 159 bytes

```
for($r=($n=--$argv[1])?["* *","###"]:["*"];++$i<$n;$r[]=$a.$b.$a){$a=strtr($b=end($r),"#*","*#");foreach($r as&$s)$s.=str_pad("",3**$i).$s;}echo join("\n",$r);

```

**breakdown**

```
for(
    $r=($n=--$argv[1])  // pre-decrease argument, initialize result
    ?["* *","###"]      // shorter than handling the special iteration 2 in the loop
    :["*"]              // iteration 1
    ;
    ++$i<$n             // further iterations:
    ;
    $r[]=$a.$b.$a       // 3. concatenate $a, $b, $a and add to result
)
{
                        // 1. save previous last line to $b, swap `*` with `#` to $a
    $a=strtr($b=end($r),"#*","*#");
                        // 2. duplicate all lines with spaces of the same length inbetween
    foreach($r as&$s)$s.=str_pad("",3**$i).$s;  # strlen($s)==3**$i
}
// output
echo join("\n",$r);

```

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


title: Become the Champion

text:
# Question
Title: Become the Champion
# Tic-Tac-Latin!

### This is a true story, so names have been altered.

My latin teacher, Mr. Latin, created his own proprietary (no joke) tic tac toe variant. Let's call it tic-tac-latin. The game is simple, it is essentially tic tac toe played on a four by four grid.

# Formal rule declaration

A line is either a row, column or a diagonal. There are two symbols, 'X' and 'O', but one or both may be substituted for a different symbol.
You score one point when you have three of your symbol and one of the other character.
These arrangements score:

```
---O
-O--
**XXXO**
XOOX

**O**-XX
-**O**--
--**X**-
---**O**

```

These do not score:

```
----
XXXX
----
OOOO

----
XXX-
----
OOO-

```

The game is won whenever one player has more points then another. The game is a draw only if the board gets filled up.

# Challenge

Solve this game. Your job is to provide a way to guarantee a win or tie, whichever is the optimal result.
Your solution may choose to either start first or second (and may therefore choose it's symbol). It is not mandatory to implement an interactive game where the user inputs moves and the corresponding display changes. It may also **be a function or program which takes input as a game state, and outputs a new board or a description of their move**. Either option must run within approximately ten seconds per move made.

---

Playing your player against any sequence of moves must give the optimal result. This means that you may assume the input position is one that it reachable from play with your player. Submissions must be deterministic, and do not necessarily need to supply a proof of optimality, but if they get cracked (by being beaten) your submissions will be considered invalid (you may leave it up, but add (cracked) in the headline).

---

This is a non-trivial task, so any valid submission is impressive and is worthy of an accepted tick, but I will make code golf the primary winning criterion.

The winner is chosen by going down this list till one winner is chosen.

* Shortest solved implemenation which always wins
* Shortest implementation

# Answer
# Perl, 147 bytes (non competing, takes more than 10 seconds per move)

Includes +4 for `-0p`

The program plays `X`. It will play a perfect game.

Input the board on STDIN, e.g.:

```
tictaclatin.pl
-X-O
-X--
X-X-
O--O
^D

```

The ouptut will be the same board with all `X` replaced by `O` and vice versa. The empty spots will be filled with a number indicating the result if X would play there, with `1` meaning the result will be a win, `2` a draw and `3` a loss. A finished game just returns the same position with the colors reversed.

In this example the output would be:

```
1O1X
1O33
O3O3
X33X

```

So the position is a win for `X` if he plays in the 3 spots along the top and the left. All other moves lose.

This confusing output is actually convenient if you want to know how the game continues after a move. Since the program always plays `X` you have to swap `X` and `O` to see the moves for `O`. Here for example it's pretty clear that `X` wins by playing in the top left, but what about if `X` plays in the third position along the top ? Just copy the output, put an `O` in place of the move you select and replace all other numbers by `-` again, so here:

```
-OOX
-O--
O-O-
X--X

```

Resulting in:

```
3XXO
3X33
X3X3
O33O

```

Obviously every move by `O` should lose, so how does he lose if he plays in the top left ? Again do this by putting `O` in the top left and replacing the digits by `-`:

```
OXXO
-X--
X-X-
O--O

```

Giving:

```
XOOX
1O33
O3O3
X33X

```

So X has only one way to go for his win:

```
XOOX
OO--
O-O-
X--X

```

Giving

```
OXXO
XX33
X3X3
O33O

```

The situation for `O` remains hopeless. It's easy to see now that every move allows `X` to immediately win. Let's at least try to go for 3 O's in a row:

```
OXXO
XX--
X-X-
O-OO

```

Giving:

```
XOOX
OO13
O3O3
X3XX

```

`X` plays the only winning move (notice that this makes `XXXO` along the third column:

```
XOOX
OOO-
O-O-
X-XX

```

Here the output is:

```
OXXO
XXX-
X-X-
O-OO

```

because the game was already finished. You can see the win on the third column.

The actual program `tictaclatin.pl`:

```
#!/usr/bin/perl -0p
y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/sx;$@<=>0||s%-%$_="$`O$'";$$_||=2+do$0%eg&&(/1/||/2/-1)

```

Applied to the empty board this evaluates 9506699 positions which takes 30Gb and 41 minutes on my computer. The result is:

```
2222
2222
2222
2222

```

So every starting move draws. So the game is a draw.

The extreme memory usage is mostly caused by the recursion using `do$0`. Using this 154 byte version using a plain function needs 3Gb and 11 minutes:

```
#!/usr/bin/perl -0p
sub f{y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/sx;$@<=>0||s%-%$_="$`O$'";$$_||=2+&f%eeg&&(/1/||/2/-1)}f

```

which is more bearable (but still too much, something must still be leaking memory).

Combining a number of speedups leads to this 160 byte version (5028168 positions, 4 minutes and 800M for the empty board):

```
#!/usr/bin/perl -0p
sub f{y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/osx;$@<=>0||s%-%$_="$`O$'";$a{$_}//=&f+1or return 1%eeg&&/1/-1}f

```

That last one uses `0` for a win (don't confuse with `O`), `1` for a draw and `2` for a loss. The output of this one is also more confusing. It fills in the winning move for X in case of a win without color swap, but if the input game was already won is still does the color swap and does not fill in any move.

All versions of course get faster and use less memory as the board fills up. The faster versions should generate a move in under 10 seconds as soon as 2 or 3 moves have been made.

In principle this 146 byte version should also work:

```
#!/usr/bin/perl -0p
y/XO/OX/,$@=-$@while/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^/sx,--$|;$@<=>0||s%-%$_="$`O$'";$$_||=2+do$0%eg&&(/1/||/2/-1)

```

but on my machine it triggers a perl bug and dumps core.

All versions will in principle still work if the 6 byte position caching done by `$$_||=` is removed but that uses so much time and memory that it only works for almost filled boards. But in theory at least I have a 140 byte solution.

If you put `$\=` (cost: 3 bytes) just before the `$@<=>0` then each output board will be followed by the status of the whole board: `1` for `X` wins, `0` for draw and `-1` for loss.

Here is an interactive driver based on the fastest version mentioned above. The driver has no logic for when the game is finished so you have to stop yourself. The golfed code knows though. If the suggested move returns with no `-` replaced by anything the game is over.

```
#!/usr/bin/perl
sub f{
    if ($p++ % 100000 == 0) {
        local $| = 1;
        print ".";
    }
y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/osx;$@<=>0||s%-%$_="$`O$'";$a{$_}//=&f+1or return 1%eeg&&/1/-1}

# Driver
my $tomove = "X";
my $move = 0;
@board = ("----\n") x 4;
while (1) {
    print "Current board after move $move ($tomove to move):\n  ABCD\n";
    for my $i (1..4) {
        print "$i $board[$i-1]";
    }
    print "Enter a move like B4, PASS (not a valid move, just for setup) or just press enter to let the program make suggestions\n";
    my $input = <> // exit;
    if ($input eq "\n") {
        $_ = join "", @board;
        tr/OX/XO/ if $tomove eq "O";
        $p = 0;
        $@="";
        %a = ();
        my $start = time();
        my $result = f;
        if ($result == 1) {
            tr/OX/XO/ if $tomove eq "O";
            tr/012/-/;
        } else {
            tr/OX/XO/ if $tomove eq "X";
            tr/012/123/;
        }
        $result = -$result if $tomove eq "O";
        my $period = time() - $start;
        print "\nSuggested moves (evaluated $p positions in $period seconds, predicted result for X: $result):\n$_";
        redo;
    } elsif ($input =~ /^pass$/i) {
        # Do nothing
    } elsif (my ($x, $y) = $input =~ /^([A-D])([1-4])$/) {
        $x = ord($x) - ord("A");
        --$y;
        my $ch = substr($board[$y],$x, 1);
        if ($ch ne "-") {
            print "Position already has $ch. Try again\n";
            redo;
        }
        substr($board[$y],$x, 1) = $tomove;
    } else {
        print "Cannot parse move. Try again\n";
        redo;
    }
    $tomove =~ tr/OX/XO/;
    ++$move;
}

```
> 6 votes

# Answer
## JavaScript (ES6) 392 bytes

```
a=>b=>(c="0ed3b56879a4c21f",r=[],k=f=>r.push([a.filter(f),b.filter(f)]),[0,1,2,3].map(i=>k(n=>n%4==i)+k(n=>(n/4|0)==i)),k(n=>n%5==0),k(n=>n&&n-15&&!(n%3)),g=r.find(o=>(o[0].length==1&&o[1].length==2)||(o[0].length==2&&o[1].length==1)),g?parseInt(c[30-[...g[0],...g[1]].map(i=>parseInt(c[i],16)).reduce((p,c)=>p+c)],16):[...a,...b].indexOf(15-a[0])+1?15-a.find(i=>b.indexOf(15-i)==-1):15-a[0])

```

### Usage

The "bot" will play second.

Draw a 4x4 grid which are numbered like this:

```
+----+----+----+----+
|  0 |  1 |  2 |  3 |
+----+----+----+----+
|  4 |  5 |  6 |  7 |
+----+----+----+----+
|  8 |  9 | 10 | 11 |
+----+----+----+----+
| 12 | 13 | 14 | 15 |
+----+----+----+----+

```

Let's run this in the browser console: Just put `f=` before the code

So, if I wanna start at `1`, I would run `f([1])([])` and it will give me `14`.

Nice move... What if I play `2` afterwards? `f([2,1])([14])`. It will return `13`.

Lemme try surrendering. Play `3`. `f([3,2,1])([14,13])`. Oh `0`! You got me!

Play `0`? `f([0,2,1])([14,13])`. `15` Ok let's keep playing...

### Note

1. Play interactively. Start with `f([your-step])([])`.
2. Prepend your next step. (See demo above)
3. Help the "bot" input its steps. It will not give you good results if you give it a random setting. (Like `f([1,2,4])([14,12])` will give `14` \- Hey the bot wanted to play on `13` on its second move!

### Brief Summary

As long as you are not surrendering, the bot will play a mirror move.

Thanks @EHTproductions for telling me that I misread the game rules and golfing tips :P

Now it will also detect if it got checkmate. If yes, block it!

Its priorities: Block \> Mirror \> (fallback) look for ways to reproducing a mirror
> 2 votes

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