title: Stock Time Machine

text:
# Question
Title: Stock Time Machine
# Stock Time Machine

You've gained access to a dataset, `tomorrowStocks`, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.

```
// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22

```

# Output

Your task is to determine the best possible outcome of `1 purchase` and `1 sale` of `1 stock` from the given dataset.

**Gotchas**

* You must buy and sell exactly 1 stock.
* You may not buy *and* sell in the same time slot.
* You must buy *before* you sell.

# Test Data

```
[1,2,3,4,5]    # 4
[1,99,2,105]   # 104
[99,1,99,100]  # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1]    # 0
[5,4,3,1]      # -1
[5,2,1]        # -1
[5,4,1]        # -1
[55,45,20,1]   # -10
[5,1]          # -4
[10,7,5,1]     # -2
[7]            # Invalid input -- assume size >= 2

```

This is a ; submit the shortest answer in your favorite language!

# Answer
> 15 votes
# 05AB1E, 4 bytes

Using FryAmTheEggman's approach. Code:

```
¥ŒOà

```

Explanation:

```
¥     # Calculate the increments of the array.
 Œ    # Get all substring of the array.
  O   # Sum the arrays in the array.
   à  # Get the largest sum and implicitly print that.

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 20 votes
# Python 2, 46 bytes

```
f=lambda x:-min(x.pop(0)-max(x),x[1:]and-f(x))

```

Test it on Ideone.

### How it works

This is a recursive approach that takes advantage of Python 2's beautifully perverse mixed-type comparisons.

The best possible outcome is either the difference of the maximum of the list with its first element removed and that first element, or another difference that does not involve the first element.

After extracting the first element with `x.pop(0)` (which permanently removes it from **x**), we compute `x.pop(0)-max(x)`. Note that this difference has the "wrong" sign.

If the updated list **x** still contains at least two elements, `x[1:]` yields a non-empty list, and `and` replaces it with the negative of a recursive call, computed as `-f(x)`. Once there are too few elements to continue, `x[1:]and-f(x)` evaluates to an empty list.

To select the maximal outcome, we take the *minimum* of the difference and the negative of the recursive call (or `[]`). Since all integers are strictly less than `[]`, `min` will simply return its left argument if the right one is `[]`.

Finally, the unary minus `-` corrects the sign of the computed outcome.

# Answer
> 12 votes
# MATL, 7 bytes

```
2XN!dX>

```

Try it online! Or verify all test cases.

```
2XN  % Take input implicitly. Two-column 2D array with all combinations of 2 elements.
     % Each combination is a row. Elements in each row are in increasing order
!    % Transpose
d    % Difference of the two numbers in each column
X>   % Maximum value. Display implicitly

```

# Answer
> 9 votes
# Jelly, 5 bytes

```
Œcḅ-Ṁ

```

Try it online! or verify all test cases.

### How it works

```
Œcḅ-Ṁ  Main link. Argument: A (integer array)

Œc     Generate all combinations of two elements of A, in order.
  ḅ-   Convert each pair from base -1 to integer.
       This maps [a, b] to b - a.
    Ṁ  Take the maximum of all computed differences.

```

# Answer
> 8 votes
## Pyth, 9

```
eSsM.:-Vt

```

Try it here or run a Test Suite.

Finds the consecutive differences between each element, then finds each substring of that array. Finally, sum the elements and return the maximal one.

### Explanation:

```
eSsM.:-Vt
eSsM.:-VtQQ   ## Auto-fill variables
      -VtQQ   ## Splat subtraction on each element of zip(Q[1:], Q)
    .:        ## Get all substrings
  sM          ## Sum each list
eS            ## Take the largest number

```

It was mentioned to me that that this algorithm works isn't entirely intuitive. Hopefully this example will illustrate why this algorithm works:

```
[a, b, c, d]
difference between each element (reversed because of how Pyth does this)
[b-a, c-b, d-c]
"substrings" or each continuous slice
[b-a], [c-b], [d-c], [b-a, c-b], [c-b, d-c], [b-a, c-b, d-c]
sum each
[b-a], [c-b], [d-c], [b-a+c-b], [c-b+d-c], [b-a+c-b+d-c]
simplify
[b-a], [c-b], [d-c], [c-a], [d-b], [d-a]

```

# Answer
> 6 votes
# Pyth, 9

```
_hS-M.cQ2

```

Yay pfns!

```
_hS-M.cQ2

     .cQ2 # generate all 2-elements combinations of Q (argument)
   -M     # map-splat with -: for each combination, substract the elements together
  S       # tort
 h        # take the first
_         # absolute value

```

# Answer
> 5 votes
## PowerShell v2+, 58 bytes

```
param($n)($n|%{($n[++$i..$n.count]|sort)[-1]-$_}|sort)[-1]

```

Takes input `$n`, pipes each element into a loop `|%{...}`. Each iteration, we slice `$n` based on pre-incremented `++$i` to the end of the input array, `|sort` that, and take the maximal `[-1]`, then subtract the current element `$_`. We then `|sort` all of those differences, and again take the maximal `[-1]`.

Tosses out a verbose array-index error, because we try to slice past the end of the array. But, since STDERR is ignored by default, we don't care.

# Answer
> 4 votes
## JavaScript (ES6), ~~57~~ 54 bytes

```
a=>(m=Math.max)(...a.map((x,i)=>m(...a.slice(i+1))-x))

```

In JavaScript it's easier to take the max of the remainder of the array and subtract the current element. (In the case of the last element the result will still be -Infinity.) Edit: Saved 3 bytes thanks to @CharlieWynn.

# Answer
> 3 votes
# J, 21 bytes

```
[:>./@;i.@#<@{."_1-/~

```

Takes an array of values as an argument and returns the result.

## Explanation

```
[:>./@;i.@#<@{."_1-/~  Input: p
                  -/~  Make a table of all differences between every pair
          #            Get the count of values in p
       i.@             Create a range [0, 1, ..., len(p)-1]
             {."_1     Take that many values from each row of the table
           <@          Box each row of selected values
[:    ;                Unbox and concatenate them
  >./@                 Reduce it by the max and return

```

# Answer
> 2 votes
# Java, 141 bytes

```
a->java.util.stream.IntStream.range(0,a.size()-1).map(i->a.subList(i+1,a.size()).stream().reduce(Math::max).get()-a.get(i)).max().getAsInt();

```

The lambda accepts an ArrayList and returns an Integer.

Ungolfed code with test cases:

```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.IntStream;

class Test {

    public static void main(String[] args) {
        Function<ArrayList<Integer>, Integer> f = a -> IntStream
            .range(0, a.size()-1)
            .map(i -> a.subList(i+1, a.size()).stream().reduce(Math::max).get() - a.get(i))
            .max()
            .getAsInt();

        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,2,3,4,5))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,99,2,105))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,99,100))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,1,2,1,3))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,2,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(55,45,20,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(10,7,5,1))));
    }
}

```

As far as I know, Java doesn't have a way to look forward in a stream, and manipulating the method from which the stream is generated produces strange results. So doing `a.remove(0)` inside a map horribly breaks the stream.

# Answer
> 1 votes
## VBA, 154

Takes in the input in column A starting in A1, outputs in C1. Must be run with the last cell in A selected. Note that Excel auto-adds the spaces between terms in VBA, otherwise this could be golfed further.

```
Sub s
i = Selection.Row
r = "B1:B" + i-1
Range(r).FormulaArray = "MAX(A2:A$" + i + "-A1)"
Range(r).FillDown
Range("C1").Formula = "MAX(" + r + ")"
End Sub

```

# Answer
> 1 votes
# Java, 116

Another java solution, i used this one to prove that, streams might looks nice, but not always useful for golfing.

```
int a(int[]a){int t,d=a[1]-a[0],i,j,l=a.length;for(i=0;i<l;i++)for(j=i+1;j<l;j++){t=a[j]-a[i];d=d<t?t:d;}return d;}

```

there is lot of space for improvements in this solution

# Answer
> 1 votes
# Clojure, 99 bytes

```
(fn[x](apply max(map #(-(apply max(% 1))(apply min(% 0)))(map #(split-at % x)(range 1(count x))))))

```

Splits input list at first position then second and so on, so we get a list which looks like this:

`[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]]` then for each pair subtracts minimum of the first elements from max of the second element and then find max from them. Would be shorter if Clojure's `min` `max` were taking sequences rather than any number of arguments.

See it online: https://ideone.com/b2nllT

# Answer
> 1 votes
# ruby, 52 bytes

```
->a{b=[];(x=a.pop;b+=a.map{|v|x-v})while a[0];b.max}

```

pops possible sell prices and look at all of the previous to find profit. Then gets max profit.

# Answer
> 1 votes
# R, 58 44 bytes

```
max(unlist(sapply(seq(y<-scan()),diff,x=y)))

```

ungolfed

```
y=scan()                #input
s=1:length(y)           #sequence of same length from 1
l = sapply(s,diff,x=y)  #applies the function diff to each 'lag' in sequence s
                        #and differencing on y
max(unlist(l))          #reforms as vector and finds maximum

```

**EDIT:** changed function. original below.

```
f=function(x)max(max(x[-1]-x[1]),if(length(x)-2)f(x[-1]))

```

or, if you're willing to put up with a bunch of warning messages, get rid of the -2 after length, for 56 bytes.

```
f=function(x)max(max(x[-1]-x[1]),if(length(x))f(x[-1]))

```

And if you feel like not trading and losing money when that's the only possibility, you can get down to 52

```
f=function(x)max(max(x-x[1]),if(length(x))f(x[-1]))

```

# Answer
> 1 votes
**C, 101 99 Bytes**

```
int i,j,m,h;int f(int*a){m=1<<31;for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;}

```

Input: null terminated array. E.g. {1,2,3,4,5,0}
Output: returns the best outcome

You can save 8 bytes (93 91 total) if you never want to lose money:

```
int i,j,m,h;int f(int*a){for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;}

```

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


title: Reduce and generalize a list of string

text:
# Question
Title: Reduce and generalize a list of string
The goal of this challenge is to reduce a list of string to a shorter more general list of string.

# Input

The Input is provided with space between the string (a b c) or in list form (\["a","b", "c"\]). It's a list list of string that can be of the following form :

* aaa
* aaaX
* aaaX/Y

With **aaa** any set of non capital alphabetic letter, and **X** or **Y** any digit between 0 and 9.

# Ouput

A list of generalized string that can be separated by anything. String are of the form :

* aaa
* aaaX
* aaaX/Y

With **aaa** any set of non capital alphabetic letter that were in the input list. X and Y stay the same and symbolise the digit. The goal of the challenge is to reduce the input list of string into their generic representation.

# Examples

Two strings can be reduced :

```
Input : regex1 regex2 split1/0
Output : regexX splitX/Y

```

Full example :

```
Input : toto toto titi titi1 titi2 titi5 tutu tutu0 tutu1 tutu1/2 tutu0/1
Output : toto titi titiX tutu tutuX tutuX/Y

```

Another example :

```
Input: ["foo0","bar0","baz0/0","eth0/0","eth0/1","eth1/0","eth1/1","vlan8","modem0"]

Output: ["fooX","barX","bazX/Y","ethX/Y","vlanX","modemX"]

```

# Scoring

This is code-golf; shortest code in bytes wins.

# Answer
# Retina, ~~25~~ ~~18~~ 13 bytes

**6 byte thanks to FryAmTheEggman, and for inspiration of extra 1 byte.**

```
\d
X
/X
/Y
D`

```

Try it online!
> 9 votes

# Answer
# Perl, ~~29~~ 27 bytes

Includes +1 for `-p`

Give input list as seperate lines on STDIN:

```
perl reduce.pl
regex1
regex2
split1/0
^D

```

reduce.pl:

```
#!/usr/bin/perl -p
s/\d/X/&&s//Y/;$_ x=!$$_++

```
> 5 votes

# Answer
# Brachylog, ~~61~~ ~~59~~ ~~44~~ 42 bytes

**2 bytes thanks to Fatalize.**

```
~~:{:ef:{~s"0123456789","X".;?.}ac.}a:{rbh"/",?rbr:"Y"c.;?.}ad.~~
~~:{:ef:{~s"0123456789","X".;?.}ac.L(rbh"/",Lrbr:"Y"c.;.)}ad.~~
~~:{s"/",?rbbbr:"X/Y"c.;.?t~s@A;?rbr:"X"c.}ad.~~
:{s"/",?rbbbr:"X/Y"c.|.t~s@A|rbr:"X"c.}ad.

```

Try it online!
> 3 votes

# Answer
# Dyalog APL, 21 bytes

```
∪'/\d' '\d'⎕R'/Y' 'X'

```

`⎕R` regex replaces the left-side strings with the right-side ones

returns the unique elements

TryAPL online!
> 3 votes

# Answer
# Python, 69 bytes

```
import re
lambda s:set(re.sub("\d","X",s).replace("/X","/Y").split())

```
> 2 votes

# Answer
# Javascript, ~~92~~ 78 bytes

```
a=a=>[...new Set(a.replace(/\d/g,"X").replace(/\/./g,"/Y").split` `)].join` `;

```
> 2 votes

# Answer
# PHP, 104 bytes

```
<?=join(' ',array_unique(explode(' ',preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$argv[1])))))

```

expects input as single argument

I could replace the `join(' ',array_unique(explode(' ',...)))` with `preg_replace('%(\b\w+\b)(?=.*\b\1\b)%','',...)`, but it´s 6 bytes shorter via the array.

**127 bytes for list of arguments:**

```
<?foreach($argv as$i=>$s)if($i)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));echo join(' ',array_unique($r));

```

**120 bytes for a function on an array:**

```
function r($a){foreach($a as$s)$r[]=preg_replace('%\d%','X',preg_replace('%\d/\d%', 'X/Y',$s));return array_unique($r);}

```
> 1 votes

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


# Question
Title: Dyalog's International Problem Solving Competition (Phase I) – Code Golf Edition
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write *good* APL code. However, this is a (common theme is manipulation of data of any type and structure, especially special handling of empty data) version of the Phase I problems – open to any language. Enjoy!

# Objective

Write ten complete programs (or functions, etc.) to solve the below problems using any one language. The point is that you must select a language that is good at various tasks, as opposed to the common golfing strategy of choosing the right tool for the (single) task. You may not use one solution as subroutine in another solution, and your score is the total byte count of all ten programs together.

Passing all the test cases is sufficient to be a valid submission.

# Closing Date

18 August 2016.

# Related: possibility of real world prizes

If you chose to use Dyalog APL (free download), you may also want to participate in the original competition, but note that the objective there is to submit quality code – not necessarily short code. If you are a student, you can win USD 100 for Phase I. Phase II (not included here) can win you up to USD 2000 and a free trip to Scotland.

# The problems

## Problem 1 – Statistics - Mean

Write a program that takes a numeric array and gives the mean (average) of the array.

**Test cases:**
`[1,2,3,4,5,6]``3.5`
`[]``0`
`17``17`
`[[1,2,3,4],[5,9]]``4`

# Problem 2 – Statistics - Median

Write a program that takes numeric data and gives the median of the data. The median is the number separating the higher half of the data from the lower half. The median can be found by arranging all the observations from lowest value to highest value and picking the middle one. If there is an even number of observations, then there is no single middle value; the median is then defined to be the mean of the two middle values.

**Test cases:**
`[1,2,3,4,5,6,7,8,9]``5`
`[[1,8,2],[7,3,6,4,5]]``4.5`
`[]``0`
`7``7`
`[1,1,1,9,1]``1`
`[1,3,9,1]``2`

# Problem 3 – Statistics - Mode

Write a program that takes a numeric list and gives the mode, most common value, of the list. If more than one number occurs the greatest number of times, return all such numbers.

**Test cases:**
`[2,2,1,4,3,2,5,1,2]``2` or `[2]`
`[]``[]`
`[1,2,3,4,1,2]``[1,2]`

# Problem 4 – Just Meshing Around

Write a program that takes strings or two numeric lists and gives the inputs shuffled into a string/list formed by alternately taking successive elements from each input. (This is known as a Faro shuffle.) The inputs do not have to be the same length. Begin with the first input.

**Test cases:**
`'MENS'` `'EKES'``'MEEKNESS'`
`'Dyalog'` `'APL'``'DAyPaLlog'`
`'APL'` `'Dyalog'``'ADPyLalog'`
`[1,3,5,7]` `[2,4,6,8]``[1,2,3,4,5,6,7,8]`
`''` `'Hello'``'Hello'`
`'Hello'` `''``'Hello'`
`''` `''``''`

# Problem 5 – You're Unique, Just Like Everyone Else

Write a program that takes a list or string and gives elements or characters that occur only once in the input.

**Test cases:**
`[1,2,3,4,5]``[1,2,3,4,5]`
`[1,2,3,4,5,4,3,2,1]``[5]`
`'hello world'``'he wrd'`
`'aabbcc'``''`
`''``''`

# Problem 6 – Shorter Ones to the Front

Write a program that takes a list and sorts it by the length of each element. Note: an element of the list can be single number, in which case it must be counted as length 1.

**Test cases:**
`['one','two','three','four','five','six']``['one','two','six','four','five','three']`
`[[2,4,3],[4,5],1,[7,3]]``[1,[4,5],[7,3],[2,4,3]]` (sorting is not necessary)
`[]``[]`
`[[],[2,2],1]``[[],1,[2,2]]`

# Problem 7 – 3's and 5's

Write a program that takes a numeric list and returns all elements that are divisible by 3 or 5.

**Test cases:**
`[1,2,3,4,5,6,7,8,9,10]``[3,5,6,9,10]`
`[]``[]`
`[-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]``[-10,-9,-6,-5,-3]` (sorting is not necessary)

# Problem 8 – Separating Out the Negative

Write a program that takes a numeric list and gives a two element list whose first element contains the values less than 0 (zero) in the input and the second element contains all values greater than or equal to 0 (zero).

**Test cases:**
`[0,1,-2,3,-4,-5,6,7,8,-9,10]``[[-2,-4,-5,-9],[0,1,3,6,7,8,10]]`
`[1,2,3,4,5]``[[],[1,2,3,4,5]`
`[-1,-2,-3,-4,-5]``[[-1,-2,-3,-4,-5],[]]`
`[]``[[],[]]`

# Problem 9 – Delimited Text

Write a program that takes two strings where the first string is delimiter**s** in the second string. The program should give the delimited text as a list of strings.

**Test cases:**
`','` `'comma,delimited,values'``['comma','delimited','values']`
`' '` `'break up words'``['break','up','words']`
`','` `','``['','']`
`','` `'hello world'``['hello world']`
`','` `''``['']`
`',;'` `'multi,delimited;values'``['multi','delimited','values']`

# Order Total

Write a program which takes list of prices and a list which indicates the count ordered of each corresponding item and gives the total cost for the order.

**Test cases:** `[2.99,4.99,1.99]` `[5,0,2]``18.93`
`[2.99,4.99,1.99]` `[0,0,0]``0`
`[123.00]` `[0]``0`
`[2.00 0.00]` `[3,4]``6`
`[]` `[]``0`

---

I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author. I gave the original competition author the link to this page within the minute I posted it, so they can check if I submit someone's answer as my own.

# Answer
> 2 votes
# Pyth, ~~88~~ ~~86~~ 84 bytes

## Problem 1: Mean (6 bytes)

```
.O.n]Q

```

Test suite.

## Problem 2: Median (~~23~~ 21 bytes)

```
~~.O,hJ.x.<S*2K.n]QlK]0eJ~~
.O<.x.<S*2K.n]QtlK]02

```

Test suite.

## Problem 3: Mode (7 bytes)

```
{.x.M/Q

```

Test suite.

## Problem 4: Interleave (3 bytes)

```
.iF

```

Test suite.

## Problem 5: Unique (7 bytes)

```
fq1/QTQ

```

Test suite.

## Problem 6: Sort (6 bytes)

```
ol.n]N

```

Test suite.

## Problem 7: Divisibility (10 bytes)

```
f!*%T3%T5Q

```

Test suite.

## Problem 8: Separate (10 bytes)

```
,Jf<T0Q-QJ

```

Test suite.

## Problem 9: Split (12 bytes)

```
~~AQu.ncRHGG]H~~
u.ncRHGQ]E

```

Test suite.

## Problem 10: Dot-product (4 bytes)

```
s*VF

```

Test suite.

---
Tags: code-golf, string, arithmetic, array, multiple-holes
---


title: I've been alphabet hunting for a while

text:
# Question
Title: I've been alphabet hunting for a while
Y'know, we've had a lot of "alphabet" challenges recently. (one two three four five.) While I love a good challenge, and those challenges were very fun, I think it's time for a change of pace. We need to exclude such challenges in the future. It's time for automation!

You're going to find some alphabets for me, and for automation (and for glory!) Alphabets are tricky and like to disguise themselves.\[citation-needed\] You'll need to account for the following factors:

1. Alphabets can be uppercase or lowercase (but not both). So, you need to look for `ABCDEFGHIJKLMNOPQRSTUVWXYZ` and `abcdefghijklmnopqrstuvwxyz`, but not `AbCdeFGhIJkLmNOpQRsTuvwxyZ`. That is, only look for alphabets that are composed of entirely one case.
2. Alphabets can shift around. they may not always start with `A`, but instead may start with `G` or `U`. So you'll have to look for things like `OPQRSTUVWXYZABCDEFGHIJKLMN`.
3. Alphabets may not always read forwards. They can also read backwards, up, and down. E.g., `ZYXWVUTSRQPONMLKJIHGFEDCBA`is also a valid alphabet.

Here's an example of a string that has an alphabet:

```
JIHGFEDCBAZYXWVUTSRQPONMLK

```

This is a backwards-oriented, shifted alphabet:

```
JIHGFEDCBAZYXWVUTSRQPONMLK
<--------|<---------------

```

This *also* contains an alphabet:

```
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E

```

it's a down-oriented alphabet:

```
F |
G |
H |
I |
J |
K |
L |
M |
N |
O |
P |
Q |
R |
S |
T |
U |
V |
W |
X |
Y |
Z V
A===
B |
C |
D |
E V

```

---

Your challenge is to write a program, function, etc. that, given a string, outputs/returns a truthy value if the string contains at least one alphabet, or a falsey value otherwise. This is a , so the shortest program in bytes wins.

## Test cases

### Truthy

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ

abcdefghijklmnopqrstuvwxyz

ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz

ZABCDEFGHIJKLMNOPQRSTUVWXYghijklmnopqrstuvwxyzabcdef

ZBCDEFGHIJghijklmnopqrstuvwxyzabcdef

AAAAAAAA
BBBBBBBB
CCCCCCCC
DDDDDDDD
EEEEEEEE
FFFFFFFF
GGGGGGGG
HHHHHHHH
IIIIIIII
JJJJJJJJ
KKKKKKKK
LLLLLLLL
MMMMMMMM
NNNNNNNN
OOOOOOOO
PPPPPPPP
QQQQQQQQ
RRRRRRRR
SSSSSSSS
TTTTTTTT
UUUUUUUU
VVVVVVVV
WWWWWWWW
XXXXXXXX
YYYYYYYY
ZZZZZZZZ

 J54
 Igeh
 H
 G
 Fzx6
 E
 Dv
 Cvzxc
 Bs
 Adf
 Z
@Yascvf
 Xsf
 W
 Vfas
 Uw
 Te
~S
 R
 Qasdfasdf
 P
 O
 N
 M
 LMNOPQR
 K

```

### Falsey

```
Hello, World!

KLMNOPQRSTUVWXYZABCDEF

K        ZYXW
 L         V
  M       U
   N     T
    O   S
     P R
      Q

A
 BCDEFGHIJKLMNOPQRSTUVWXYZ

ABCDEFGHIJKLmnopqrstuvwxyz

```

# Answer
# Jelly, ~~28~~ ~~23~~ 22 bytes

**1 byte thanks to Dennis.**

```
26RØAṙ;U$;Œl$
;Zẇ@þ¢FS

```

Try it online!

Takes an array of strings.
> 5 votes

# Answer
# Cheddar, 148 bytes

```
(s,b=65@"90,c?)->(|>27).map(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).map(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower?1:0).sum?1:0).sum

```

Try it online!

## Non-copmeting, ~~146~~ 132 bytes

This is the **exact same** as above except `map(...?1:0).sum` has become `any(...)`.

```
(s,b=65@"90,c?)->(|>27).any(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).any(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower))

```

Rather slow but it works ¯\\\_(ツ)\_/¯ . added `any` function after challenge release date.

The input **does not** need to be padded with whitespaces. But if an input doesn't work, pad it with whitespaces to make rectangle. The `turn` function is really finicky and I'm not sure when it works and when it doesn't

### Explanation

Loops through all possible cycles of alphabet. On each iteration check if the current cycle of alphabet exists in the string, if not, check if any of the possible rotations of the string have the alphabet.

### Ungolfed

```
(str, a = 65@"90)->
  (|>27).any(->
    str has (a = a.slice(1) + a[0]) ||
    str has a.lower                 ||
    (1|>3).any(j ->
      (c = str.lines.turn(j).vfuse) has a ||
      c has a.lower
    )
  )

```
> 2 votes

# Answer
## 05AB1E, 43 bytes

```
AÂ‚Duìvy26FÀD}})U|Dø€J)˜vXDgs`rFysk>ˆ}}¯O__

```

**Explanation in short**

Get different variations of alphabet (caps, no-caps, reversed, normal) and store in X.

```
AÂ‚Duìvy26FÀD}})U

```

Get each row and column of input as a list of strings.

```
                 |Dø€J)˜

```

Check each such string if it contains a variation of the alphabet.

```
                        vXDgs`rFysk>ˆ}}

```

Sum and double negate, giving 1 for true and 0 for false.

```
                                       ¯O__

```

Try it online
> 2 votes

# Answer
# Python, 182 bytes

Doesn't feel very 'golfed', but ...

```
import re
a='abcdefghijklmnopqrstuvwxyz'
P,N='|\n'
p=P.join(a[i:]+a[:i] for i in range(26))
p+=P+p[::-1]
p+=P+p.upper()
lambda s:re.search(p,s+N+N.join(map(''.join,zip(*s.split(N)))))

```

Theory of operation:

First, build a regex pattern combining all the possible alphabets:

`p=P.join(a[i:]+a[:i] for i in range(26))` builds a string of all rotations of 'a' joined with '|'. e.g. "abc...z|bcd...za|..."

`p+=P+p[::-1]` appends a reversed version of itself.

`p+=P+p.upper()` appends an uppercase version.

Then create a long string combining the original `s` and a version of `s` with the columns turned into rows:

`N.join(map(''.join,zip(*s.split(N))))` flips the rows and columns, so 'a\nb\nc' becomes 'abc'

return true if the pattern is in the long string.
> 0 votes

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


title: King of the Torus!

text:
# Question
Title: King of the Torus!
# King of the Torus!

Your job is to conquer the torus, but wait, there are multiple other players banded together in teams facing you! You will need to use your wit's to conquer the torus.

There are three teams: red, blue and green. Teams are self-assigned arbitrarily. If the teams are even you may join the team of your choice, otherwise you must join the smallest team(s). The map is a torus presented as a square of length 640 by 640. Lets take a look at a sample map

```
OOOOOOOOOOOOOOOOOOOOOOOOOOO
RRRRRRRRRRRRRRRRRRRRRRRRRRR
OOOOOOOOOOOOOOOOOOOOOOOOOOO
GGGGGOOOOOOOOBBBBBBBBBBBBBB
GGGGGGGGGGGGGGGGGGGGGOOOOOG
OOOOOOOOOOOOOOOOOOOOOOOOOGG
RRRRRRRRRRRRRRRRRRRRRRRRRRR
OOOOOOOOOOOOOOOOOOOOOOOOOOO

```

as you can see, the red team has built a wall to safely conquer the territory between the two walls. Blue, and green will have to fight it out. This scaled down version of the map is representative of the larger one.

Red would likely win this battle as they would finish the game (once the board is filled or a large number of turns have passed) with the most territory

Now each bot has a location (known only to you). You can only move to an adjacent square if it is owned by your team. At the start of your game, you start on a single square of your teams color. Your goal is to expand this splotch by conquering other land. At any turn you can choose to move to any adjacent color of your own territory or you may alternatively choose to attack an adjacent territory. If the attacked square is unowned it will be captured.

## Java API

You will override the Bot class to return a single number (0-3) for attempted moves and 4-7 for an attempted attack. Your bot's should only take 10 milliseconds to move, but the rule will not be formally enforced unless it becomes a problem. Problematic, malicous, or otherwise obnoxious bots are clearly not in the spirit of this competition and will be disqualified with an immediate low quality flag. Otherwise bots acting in good faith, but otherwise buggy will be given time as needed for bug repairs. Method summary

```
public abstract class Bot{
public final int team;// 0 = red 1 = green 2 = blue
public Bot(int inTeam){team=inTeam}//be sure to call super(inTeam);
public int move(){};//you will override this
}

Methods available

Color Bot.getColor(int x,int y){}//returns a Color object with rgb values where the r g or b value of the team owning it will be 100.
getX(); returns the X position of your bot
getY(); returns the y position of your bot
Bot.getMap();//returns the array representing the map. I.e Bot.getMap[i][j] returns a color with r g b values representing each teams stake in that spot.
//only one r g b value will be greater than 0 as only one team can hold a spot
Do not abuse the map access. Giving direct access (as opposed to a copy) is to speed up access to the map. Abusing it will result in disqualification!

```

A wrapper program may be made available as long as it still allows the program to run smoothly.

## How to play:

Step one: Post your bot here as an answer and ensure it follows the specs.
Step Two Head over to this gitHub repository fork it and add your bot's file in as well as add these two lines after '//init bots' Bot.run. Be sure to choose the team with the least members if applicable.

```
  bots.add(new UniqueBotNameHere(team=choiceOfTeam,x=getRandom(0,map.length),y=getRandom(0,map[0].length)));
    map[x][y].colors[team]=255;

```

Step Three: Make a pull request. I will accept your pull request and your bot will automagically be added to the tournament.
Step Four: Download the source files and copy them into the proper package. Run the build and enjoy watching the bots

---

Good luck and don't let your team down! Team's will be made even by my sample bots. I may also move around teams to ensure equal members.

---

### Interesting trivia

Modifying the Half Hearted flood filling sample bot, gives an interesting map generator.

# Answer
# Waller

He builds a wall, but he can't make the other team pay for it! He makes a nice low level bot to help debug your submissions.

```
public class Trump extends Bot{
int moves;
int direction;
    public Trump(int team, int inX, int inY) {
        super(team, inX, inY);
direction = Bot.getRandom(0, 4);
    }

    @Override
    public int move() {
int ret = direction;
switch(++moves%4){
    case 0:
        ret = direction+4;
        break;
    case 1:
        ret = direction;
        break;
    case 2:
        ret = direction + 1;
        break;
    case 3:
        ret = direction +3;
}
return ret;
    }

}

```
> 1 votes

# Answer
# Half Hearted Flood Filler

Another low level bot. He tries to flood fill the map, but he only puts in 50% effort! I will enter another more competitve bot, but this guy is just to demonstrate one possible approach.

```
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package toroidal.domination;

import java.awt.Color;
import java.util.Stack;

/**
 *
 * @author rohan
 */
public class HalfHeartedFloodFillBot extends Bot{
    public static class Node{
        public final int x,y;
        public Node(int x, int y){
            this.x=x;this.y=y;
        }
    }
private Stack<Integer> nodes = new Stack<>();
    public HalfHeartedFloodFillBot(int team, int inX, int inY) {
        super(team, inX, inY);
    }

    @Override
    public int move() {
        int x,y;

        for(int i = 0;i<4;i++){
    if(isEmpty(Bot.getColorAtSpot(x=getX()+(int) Math.cos(i*Math.PI/2),y= getY()+(int) Math.sin(i*Math.PI/2)))){
        nodes.add((i+2)%4);
        return i+4;
    }
}
        //no empty spots found try to backtrack or just do stuff!
return nodes.isEmpty()?Bot.getRandom(0,2)==0?Bot.getRandom(0, 2)==0?0:1:Bot.getRandom(0, 2)==0?2:3:nodes.pop();
    }
    boolean isEmpty(Color c){
        int r = c.getRed();
        int g = c.getGreen();
        int b = c.getBlue();
        return r == 0 && b == 0&& g == 0;
    }
}

```
> 0 votes

# Answer
# SpiralBot

This bot will go until he hits something that is not neutral, then will turn left, making a spiral in the free space.

```
public class SpiralBot extends Bot{
    int d;

        public SpiralBot (int team, int inX, int inY) {
            super(team, inX, inY);
        d = 0;
        }

    int dx(int move){
        return (int) Math.cos(move * Math.PI / 2);
    }
    int dy(int move){
        return (int) Math.sin(move * Math.PI / 2);
    }

        @Override
        public int move() {
        int x = getX();
        int y = getY();
        Color[]c = new Color[4];
        for(int i = 0;i<4;i++)
            c[i] = Bot.getColor(x+dx(i), y+dy(i));
        if(c[d].equals(Color.black))
            return d;
        if(c[(d+1)%4].equals(Color.black))
            return d = (d+1)%4;
        if(c[(d+3)%4].equals(Color.black))
            return d = (d+3)%4;
        return d + 2;
    }

}

```

I have no account on GitHub, so if someone could push this for me that would be good. Thank you.
> 0 votes

---
Tags: king-of-the-hill, path-finding, java
---


title: Medieval orthography

text:
# Question
Title: Medieval orthography
# Task

Your task is to convert a text into medieval orthography.

# Details

1. `j` is converted to `i` and `J` to `I`.
2. `u` and `U` at the beginning of words are converted to `v` and `V` respectively.
3. `v` and `V` at anywhere except the beginning of words are converted to `u` and `U` respectively.
4. `s` is converted to `ſ` (U+017F) unless at the end of the word or preceded by another `s`.

# Specs

* A word is defined as a sequence of letters in `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`.
* All words will have at least two letters.
* The input will only consist of **printable ASCII characters** (U+0020 - U+007E).
* There will be no occurrences of more than two consecutive `s`. That is, `sss` will not be a substring of the input.

# Testcases

Individual words:

```
Input       Output
------------------------
Joy         Ioy
joy         ioy
Universe    Vniuerſe
universe    vniuerſe
Success     Succeſs
successfull ſucceſsfull
Supervise   Superuiſe
supervise   ſuperuiſe
Super-vise  Super-viſe
I've        I've
majors      maiors
UNIVERSE    VNIUERSE
0universe   0vniuerſe
0verify     0verify
I0ve        I0ve
_UU_          _VU_
_VV_          _VU_
ss_         ſs_

```

Whole paragraph:

```
Input:  Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.

Output: Chriſtian Reader, I haue for thy vſe collected this ſmall Concordance, with no ſmall labour. For being to compriſe much in little roome, I was to make choyſe of the moſt principall and vſefull places, and to rank them vnder ſuch words as I thought moſt eſsentiall and materiall in the ſentence, becauſe the ſcant roome allotted vnto me, would not permit that I ſhould expreſse them vnder euery word in the verſe, as it is the manner in large Concordances.

```

The SHA-256 hash of the output of the last testcase is:

```
5641899e7d55e6d1fc6e9aa4804f2710e883146bac0e757308afc58521621644

```

# Disclaimer

Medievall orthographie is not that conſtante. Pleaſe do not complayne if you ſhall ſee olde bookes with a different orthographie.

# Answer
# SED, 144 140 111 Bytes

saved 29 bytes thanks to NoOneIsHere

```
-r -e'y/j/i/g;y/J/I/g;s/ u/ v/g;s/ U/ V/g;s/^u/v/g;s/^U/V/g;s/([^s])s(\w)/\1ſ\2/g;s/(\w)v/\1u/g;s/(\w)V/\1U/g'

```
> 3 votes

# Answer
## Python 3 (128 126 bytes)

```
import re;lambda k:re.sub("(?<!s)s(?=[a-zA-Z])",'ſ',re.sub("(?i)j|(?<![a-z])u|(?<=[a-z])v",lambda c:chr(ord(c.group())^3),k))

```

`chr(ord(c.group())^3)` feels excessive to xor a single-character string, but maybe a real Pythonista can suggest a golf. However, it's very convenient that `^3` suffices to interchange `i <-> j` and `u <-> v`.

NB The only thing here which requires Python 3 is the Unicode character: Python 2 complains `Non-ASCII character '\xc5' <snip> but no encoding declared`.
> 2 votes

# Answer
## Retina, ~~55~~ ~~54~~ 50 bytes

```
T`jJvV`iIuU
Ti01`uUp`vVp`[a-z]+
s(s*[a-zA-Z])
ſ$1

```

Try it online! (The first line enables a linefeed-separate test suite.)
> 2 votes

# Answer
# Python 3.5, ~~124~~ ~~116~~ ~~111~~ ~~118~~ ~~125~~ ~~144~~ 142 bytes:

```
import re;lambda k:re.sub("J|j|(?<![a-zA-Z])[uU]|(?<=[a-zA-Z])[Vv]|(?<!s)s(?=[a-zA-Z])",lambda g:dict(zip('jJuUvVs','iIvVuUſ'))[g.group()],k)

```

Well, this seems like the perfect job for *regular expressions*!
> 1 votes

# Answer
# JavaScript (ES6), 154

Using parseInt to identify alphabetic characters. Note: casually but luckily `parseInt('undefined',36)|0` is \< 0

```
s=>[...s].map((c,i)=>((n=v(c))-19?n==31&p>9?'uU':n!=30|p>9?c=='s'&s[i-1]!=c&v(s[i+1])>9?'?':c+c:'vV':'iI')[p=n,c<'a'|0],p=0,v=c=>parseInt(c,36)|0).join``

```

**Less golfed**

```
s=>
  [...s].map(
  (c,i)=>
  ((n=v(c))-19
  ?n==31&p>9
    ?'uU'
    :n!=30|p>9
      ?c=='s'&s[i-1]!=c&v(s[i+1])>9
        ?'ſ'
        :c+c
      :'vV'
  :'iI')[p=n,c<'a'|0],
  p=0,
  v=c=>parseInt(c,36)|0
).join``

```

**Test**

```
F=
s=>[...s].map((c,i)=>((n=v(c))-19?n==31&p>9?'uU':n!=30|p>9?c=='s'&s[i-1]!=c&v(s[i+1])>9?'ſ':c+c:'vV':'iI')[p=n,c<'a'|0],p=0,v=c=>parseInt(c,36)|0).join``

out=(a,b,c)=>O.textContent+=a+'\n'+b+'\n'+c+'\n\n'

ti='Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.'
to='Chriſtian Reader, I haue for thy vſe collected this ſmall Concordance, with no ſmall labour. For being to compriſe much in little roome, I was to make choyſe of the moſt principall and vſefull places, and to rank them vnder ſuch words as I thought moſt eſsentiall and materiall in the ſentence, becauſe the ſcant roome allotted vnto me, would not permit that I ſhould expreſse them vnder euery word in the verſe, as it is the manner in large Concordances.'
r=F(ti)
out(to==r?'OK':'KO',ti,r)

test=`Joy         Ioy
joy         ioy
Universe    Vniuerſe
universe    vniuerſe
Success     Succeſs
successfull ſucceſsfull
Supervise   Superuiſe
supervise   ſuperuiſe
Super-vise  Super-viſe
I've        I've
majors      maiors
UNIVERSE    VNIUERSE
0universe   0vniuerſe
0verify     0verify
I0ve        I0ve
_UU_          _VU_
_VV_          _VU_
ss_         ſs_`
.split('\n').map(t=>{
  var [i,o]=t.split(/\s+/),r=F(i)
  out(o==r?'OK':'KO',i,r)
})
```

```
#O {width:90%; overflow:auto; white-space: pre-wrap}
```

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

# Answer
## JavaScript (ES6), 111 bytes

```
s=>s.replace(/[a-z]+/gi,w=>w.replace(/j|J|^u|^U|\Bv|\BV|ss|s(?!$)/g,c=>"iIvVuUſ"["jJuUvVs".search(c)]||"ſs"))

```

Explanation: Because JavaScript regexp has no lookbehind, I instead break up the string into words, which then allows me to use `^` and `\B` as negative and positive letter lookbehinds. `ss` is dealt with by matching separately, with the slightly awkward replacement expression which takes fewer bytes than either replacing only the first character of `c` or adding an extra `s` to both strings and using the matching substring.
> 1 votes

# Answer
## CJam (89 88 bytes)

```
{32|_'`>\'{<*}:A;SqS++3ew{_1="jJuUvVs"#[-4_{_0=A!3*}_{_0=A3*}_{_)A\0='s=>268*}W]=~f^1=}%

```

Online demo

I never understood why CJam doesn't have regexes, but since it doesn't here's a solution which doesn't use them.
> 0 votes

# Answer
# Ruby, 85 + 1 = 86 bytes

Run with `ruby -p` (+1 byte for `p` flag). Takes input on stdin.

```
gsub(/j|(?<=^|[^a-z])u|(?<=[a-z])v|(?<=^|[^s])s(?=[a-z])/i){$&.tr"jJsUuVv","iIfVvUu"}

```

Run the tests on ideone (wrapped in a lambda there because you can't give flags to ideone): http://ideone.com/AaZ8ya
> 0 votes

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


title: Concise Grading

text:
# Question
Title: Concise Grading
Write a program or a function in your favorite programming language that will take as input a number `n` (integer or non-integer) between `0` and `100` inclusive, and output the corresponding grade as outlined below:

* If `0 < n <= 40`, then output `E`.
* If `40 < n <= 55`, then output `D`.
* If `55 < n <= 65`, then output `C`.
* If `65 < n <= 70`, then output `C+`.
* If `70 < n <= 75`, then output `B-`.
* if `75 < n <= 80`, then output `B`.
* If `80 < n <= 85`, then output `B+`.
* If `85 < n <= 90`, then output `A-`.
* If `90 < n <= 95`, then output `A`.
* If `95 < n <= 100`, then output `A+`.

You are guaranteed that there are no other cases to test, and that `n` is guaranteed to be within `0` and `100`.

The input `n` can be provided via `stdin` or as an argument to the program.

Lines in the output are **not** allowed to have trailing spaces and/or newlines. You must output **exactly** the corresponding grade, nothing else.

Shortest code in bytes wins!

# Answer
# Python, ~~74~~ ~~66~~ 73 bytes

```
lambda n,l="E "*8+"D D D C C C+ B- B B+ A- A A+ A+":l.split()[int(n-1)/5]

```

Unnamed lambda, uses a list of all grades in groups of 5. (I'm sure there's a way to handle n=100 without adding the extra 'A+' at the end, I'm just not sure how)

Edit: Thanks to @LeakyNun for 8 bytes
> 2 votes

# Answer
## JavaScript (ES6), 57 bytes

```
n=>`A+ A A- B+ B B- C+ C C D D D`.split` `[20-n/5|0]||`E`

```
> 1 votes

# Answer
# Pyth, 36 bytes

```
?<Q41\E+C/-1075Q15?<Q66k-@"-+ "/_Q5d

```

Test suite.

### Explanation

Here is the equivalent program in Python 3.

```
lambda Q:[chr(int(1075-Q)//15)+["-+ "[int(99-Q/5)%3],""][Q<66],"E"][Q<41].split()[0]

```

Ideone it!
> 0 votes

---
Tags: code-golf
---


title: A tiny adventure

text:
# Question
Title: A tiny adventure
Text adventure games have a pretty set formula; there's a world composed of a series of rooms / spaces, the player can move around these rooms, and there are some items in the rooms. Items can be picked up by the player, put down, used to access other rooms (e.g. keys), and combined with other items to make new items.

# Challenge

Your challenge is to write a text adventure runtime in the fewest bytes (code golf). To keep things simple, all you need to do is output a truthy or falsey value depending on whether a given series of commands would win a given game or not (no interactivity, no human friendly output, etc.)

# Game Rules

* The world is always composed of a corridor with 10 connected rooms. Each room requires a key to enter, but can be exited at any time without a key (so it's some kind of latch lock I guess);
* The player begins in room 0, and wins if they ever enter room 9 (once they reach room 9 they can do whatever they like, including go to another room, and they will still have won);
* Each room can contain any number of items;
* There are up to 26 items, named A-Z, and no item will appear more than once in the world;
* The player can pick up items from the current room and place them in their inventory (they can also drop items from their inventory into the current room);
* The player's maximum inventory size is finite, and will be provided with the level details;
* At the beginning of the game, the player's inventory is always empty;
* There is no limit to the maximum number of items in a room (though the implicit limit would be 26, since that is the total number of items);
* Items A-J are keys which can be used to **enter** rooms 0-9 (i.e. the player can move to room 0 if they have item A, to room 1 if they have B, etc. note that keys are **not** required to leave a room, and the player begins in room 0, so the key "A" is only required if the player wants to *return* to room 0);
* Items in the player's inventory can be combined to create new items (which will be created in the player's inventory) — the permitted combinations will be provided with the level details;
* Combining items consumes the original items (i.e. if one of the items was a key, it will no-longer be possible to use that key);
* If the player tries to do something impossible (e.g. pick up an item which is not in the current room / drop an item they don't have / combine items they don't have / go to a room they don't have the key for), nothing happens and they can continue;
* The player will never give a nonsense command (e.g. go to room 11).

So a simple game might look like this:

```
  v
+---+---+---+---+---+---+---+---+---+---+
| C |   | J |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|               CORRIDOR                |
+---------------------------------------+
Inventory capacity: 99

```

Room 0 contains item "C" (which is the key to room 2). Room 2 contains item "J" (which is the key to room 9). The player can win the game by picking up C, moving to room 2, picking up J, then moving to room 9.

A more complex game might be:

```
  v
+---+---+---+---+---+---+---+---+---+---+
| C |   | X |YZ |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|               CORRIDOR                |
+---------------------------------------+
Inventory capacity: 10
C+X => D
Y+Z => J

```

Now the player can win by picking up C, moving to room 2, picking up X, combining C with X to create D, then moving to room 3. They can now pick up and combine Y and Z to get J, allowing them to go to room 9.

---

# Input Format

There's a fair bit of input to handle, and that's a pretty boring task, so the input format is very flexible. You will get the following data, and how it should be sent to your program is largely up to you:

* The initial contents of each room (list of 0 or more items for each room);
* A collection of permitted item combinations (each contains 2 input items and their output item — note that the input items are unordered);
* The maximum inventory size (integer, 0 \<= size \<= 26);
* The list of commands the player attempted.

The player's commands can be:

* `[P]ick up <item>` \- picks up an item from the room and puts it into the player's inventory (if there is space)
* `[D]rop <item>` \- drops an item from the player's inventory into the current room
* `[C]ombine <item1> <item2>` \- combines 2 items in the player's inventory to produce a new item
* `[G]o to <room>` \- travels to the chosen room if the player has the required key

For example, the input format I used for testing was simple program arguments:

```
./adventure YZ '' '' '' '' '' '' '' '' ''  1 YZJ         2          PY PZ CYZ G9
#           r0 r1 r2 r3 r4 r5 r6 r7 r8 r9  combinations  inv. size  commands...
# means:
#  room 0 starts with items Y & Z, all other rooms start empty
#  1 combination is possible: Y+Z => J
#  max inventory size is 2
#  player commands are [P]ick up Y, [P]ick up Z, [C]ombine Y and Z, [G]o to room 9
#  (in this example, the player wins)

```

But if some other format makes it easier, that's fine (e.g. special delimiter characters / multiple lines / different ordering / serialised to JSON / etc.)

# Output Format

Your program should return some truthy output if the player's commands cause them to win the game, and some falsey output otherwise. This could be a recognisable message to stdout, a program return code, or whatever your language of choice provides. All other output will be ignored.

# Test Cases

The following bash script provides a test harness which will check most situations. It has been written to use the format described above, but modifying it to use a different format is just a case of adding a conversion in the `invoke` function.

```
#!/bin/sh

PROG="$1";

if [[ -z "$PROG" ]]; then
    echo "Usage: $0 <program-to-test>";
    exit 1;
fi;

function invoke {
    "$PROG" "$@"
}

RED="\033[1;31m";
GREEN="\033[1;32m";
RESET="\033[m";
FAILURES="0";

function pass {
    if ! invoke "$@" >/dev/null 2>&1; then
        echo "${RED}Expected pass, got fail:${RESET} $*" >&2;
        (( FAILURES = "$FAILURES" + 1 ));
        invoke "$@" 2>&1;
    fi;
}

function fail {
    if invoke "$@" >/dev/null 2>&1; then
        echo "${RED}Expected fail, got pass:${RESET} $*" >&2;
        (( FAILURES = "$FAILURES" + 1 ));
        invoke "$@" 2>&1;
    fi;
}

echo "Running tests...";

#    R0  R1  R2  R3  R4  R5  R6  R7  R8  R9  C      I  Cmd...
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ G9;
fail ''  J   ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  G9 PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      0  PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ PJ DJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ PJ G9;
pass B   CJ  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PB G1 DB PC PJ G9;
fail B   CJ  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PB G1 DB PB PC PJ G9;
pass AJ  ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PA PJ G9;
pass B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 DB PJ G9;
fail B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G2 DB PJ G9;
fail B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 PJ G9;
fail B   D   J   C   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 PJ G9;
pass AJ  ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PA PJ G9 G0;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 G3 PJ G9;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 DD G3 PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ DD G3 DJ G0 DD G3 PJ G9;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PA DA DA PD PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PA DA DA PJ G9;
fail ABCDEFGHIKLMNOPQRSTUVWXYZ  J  '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9;
pass ABCDEFGHIJKLMNOPQRSTUVWXYZ '' '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9;
fail YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PY PZ CYZ PJ G9;
pass YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PJ G9;
pass YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PJ CWJ G9;
fail XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX PJ G9;
fail XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX DY DZ PJ G9;
pass XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX DW PJ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  CYZ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ DJ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ DJ PY PZ CYZ G9;
fail WZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PW PZ CYZ G9;
fail WZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CZY G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 ZYJ  2  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ PJ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PJ G9;
pass BW  UV  ''  ''  ''  ''  ''  ''  ''  ''  3 BUR WVS RSJ  2  PB PW G1 DW PU CBU DR PW PV CVW PR CRS G9;
fail BW  AUV ''  ''  ''  ''  ''  ''  ''  ''  3 BUR WVS RSJ  2  PB G1 PU CBU DR PA PB G0 DA PW G1 PV CVW PR CRS G9;
pass BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW UV  ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA PB G0 DA G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA PB G0 DA PW G1 DB CVW PR CRS G9;
pass BFK LG  M   N   O   CDE PQR U   W   ''  10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ  5 \
  PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G2 PM G6 DM DC G3 PN G4 PO G6 DN DO DD DE \
  PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9
fail BFK LG  M   N   O   CDE PQR U   W   ''  10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ  5 \
  PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G6 DM DC G3 PN G4 PO PM G6 DN DO DD DE \
  PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9

if (( "$FAILURES" == "0" )); then
    echo "${GREEN}All tests passed${RESET}";
else
    echo "${RED}Total failures: $FAILURES${RESET}";
fi;

```

# Winning

Standard code golf: shortest code (in bytes) wins. Entries must follow the game rules, which in practice means they must pass all test cases (more tests may be added if necessary).

# Answer
> 5 votes
# JavaScript (ES6), 244 ~~249 267 280~~

**Edit** Saved 18 (!) bytes thx @Neil

A function with input:

* r = room content (array of 10 strings)
* k = combinations (array of string of 3 chars - source1, source2, result)
* s = inventory max size (number)
* c = commands (array of strings)

Returns true or false

```
(r,k,s,c,p=0,j={})=>c.some(([c,a,b])=>c<'D'?j[a]>0&j[b]>0&&!k.map(([t,u,v])=>u+t==a+b|u+t==b+a?j[j[a]=j[b]=v]=++s:0):c<'G'?j[a]>0&&!(j[++s,a]=~p):c>'G'?s&&j[a]==~p&&!(j[a]=s--):j['ABCDEFGHIJ'[a]]>0&&(p=a)>8,r.map((o,n)=>[...o].map(c=>j[c]=~n)))

```

See the test snippet below for a newline separated version

**Test**

```
Exec=
(r,k,s,c,p=0,j={})=>
c.some(
  ([c,a,b])=>
   c<'D'?j[a]>0&j[b]>0&&!k.map(([t,u,v])=>u+t==a+b|u+t==b+a?j[j[a]=j[b]=v]=++s:0)
   :c<'G'?j[a]>0&&!(j[++s,a]=~p)
   :c>'G'?s&&j[a]==~p&&!(j[a]=s--)
   :j['ABCDEFGHIJ'[a]]>0&&(p=a)>8
  ,r.map((o,n)=>[...o].map(c=>j[c]=~n))
)

console.log = (...x) => O.textContent += x + '\n';

;`pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ G9;
fail ''  J   ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  G9 PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      0  PJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ G9;
fail J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ PJ DJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ PJ G9;
pass J   ''  ''  ''  ''  ''  ''  ''  ''  ''  0      9  PJ DJ PJ G9;
pass B   CJ  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PB G1 DB PC PJ G9;
fail B   CJ  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PB G1 DB PB PC PJ G9;
pass AJ  ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PA PJ G9;
pass B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 DB PJ G9;
fail B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G2 DB PJ G9;
fail B   D   ''  J   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 PJ G9;
fail B   D   J   C   ''  ''  ''  ''  ''  ''  0      2  PB G1 PD G3 PJ G9;
pass AJ  ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PA PJ G9 G0;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 G3 PJ G9;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ G3 DJ G0 DD G3 PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      3  PA PD PJ DD G3 DJ G0 DD G3 PJ G9;
fail ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PA DA DA PD PJ G9;
pass ADJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      1  PA DA DA PJ G9;
fail ABCDEFGHIKLMNOPQRSTUVWXYZ  J  '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9;
pass ABCDEFGHIJKLMNOPQRSTUVWXYZ '' '' '' '' '' '' '' '' '' 0 26 PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ G9;
fail YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  0      2  PY PZ CYZ PJ G9;
pass YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PJ G9;
pass YZJ ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PJ CWJ G9;
fail XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX PJ G9;
fail XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX DY DZ PJ G9;
pass XYZJ '' ''  ''  ''  ''  ''  ''  ''  ''  1 YZW  2  PY PZ CYZ PX DW PJ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  CYZ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ DJ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ DJ PY PZ CYZ G9;
fail WZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PW PZ CYZ G9;
fail WZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CYZ G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  2  PY PZ CZY G9;
pass YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 ZYJ  2  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ PY PZ CYZ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PY PZ CYZ PJ G9;
fail YZ  ''  ''  ''  ''  ''  ''  ''  ''  ''  1 YZJ  1  PJ G9;
pass BW  UV  ''  ''  ''  ''  ''  ''  ''  ''  3 BUR WVS RSJ  2  PB PW G1 DW PU CBU DR PW PV CVW PR CRS G9;
fail BW  AUV ''  ''  ''  ''  ''  ''  ''  ''  3 BUR WVS RSJ  2  PB G1 PU CBU DR PA PB G0 DA PW G1 PV CVW PR CRS G9;
pass BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW UV  ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PC PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU PA PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PB G0 DA PW G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA PB G0 DA G1 DB PV CVW PR CRS G9;
fail BCW AUV ''  ''  ''  ''  ''  ''  ''  ''  3 CUR WVS RSJ  2  PB PC G1 DB PU CCU DR PA PB G0 DA PW G1 DB CVW PR CRS G9;
pass BFK LG  M   N   O   CDE PQR U   W   ''  10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G2 PM G6 DM DC G3 PN G4 PO G6 DN DO DD DE PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9
fail BFK LG  M   N   O   CDE PQR U   W   ''  10 BPT CQS TSH HUI IWV VFA GRX MXZ ANY YZJ 5 PB PF PK G1 PL PG G6 DB DK DL G5 PC PD PE G6 DF G6 DM DC G3 PN G4 PO PM G6 DN DO DD DE PB PP CBP PC PQ CCQ CTS G7 PU CUH G8 PW CWI G6 PF CVF PR PM PN CGR CMX CAN CYZ G9`
.split(/;*\n/).map((srow,i)=>{
  var row=srow.split(/\s+/),
  rooms=row.slice(1,11).map(x=>x=="''"?"":x),
  ncomb=+row[11],
  comb=row.slice(12,12+ncomb),
  isize=+row[12+ncomb],
  commands=row.slice(13+ncomb),
  start='['+rooms+'] ['+comb+'] '+isize+' ['+commands+']';
  var result=Exec(rooms,comb,isize,commands),
     ok = row[0] == ['fail','pass'][~~result]
  console.log(i, ok ? 'ok':'ko', start, row[0], result)
})
```

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

# Answer
> 3 votes
# C, 338 bytes

I had a go at minifying my own test program. I think it went quite well, even if it is the longest answer so far!

```
#define P c[(i<j?i:j)*25+i+j]
#define F for(q=atoi(*++v);r
#define X c[r*91+i]
r,i,j,c[2405];main(q,v)char**v;{for(r=10;--r;)for(++v;i=**v;++*v)++X;++v;F<q;++r)i=**++v,j=1[*v],P=2[*v];r=9;F&&*++v;c[i=1[*v]]&&j==68?c[i]=!++X,++q:j>79&&q*X?c[i]=!--X,--q:j==71&&c[i+17]?r=57-i:j<68&&c[i]*c[j=2[*v]]&&P?c[i]=c[j]=0,c[P]=++q:0)j=**v;return r;}

```

This uses a few tricks to save space:

* Rooms are loaded in reverse so that checking for room 9 becomes checking for room 0, which is cheaper
* Room 9's contents never matter, so it is skipped when reading the input and used to store the inventory instead
* The room contents and item combinations are stored in the same array. Because items are stored at their ascii values, they never overlap.

Breakdown:

```
#define P c[(i<j?i:j)*25+i+j]       // item combination lookup (input: i,j)
#define X c[r*91+i]                 // room item lookup (input: r,i)
r,i,j,c[2405];                      // globals default to 0
main(q,v)char**v;{                  // K&R syntax to save bytes
    for(r=10;--r;)                  // Load rooms 0-8, store as 9-1
        for(++v;i=**v;++*v)
            ++X;
    ++v;                            // Skip room 9
    for(q=atoi(*++v);r<q;++r)       // For each combination
        i=**++v,
        j=1[*v],                    // Use index[array] syntax to avoid (brackets)
        P=2[*v];                    // Record combination
    r=9;                            // Begin in room 0 (9 in memory)
    for(q=atoi(*++v);               // Load inventory size
                     r              // While not in room 9 (0 in memory)...
                      &&*++v;       // ...and still have user commands
                                    // (ISO C promises a NULL at the end of argv)
        c[i=1[*v]]&&j==68?          // If 'D'rop, and we have the item:
            c[i]=!++X,              //  Drop it
            ++q:                    //  Increase our inventory capacity
        j>79&&                      // If 'P'ick up, and...
              q                     // ...we have capacity in our inventory and...
               *X?                  // ...the item is in the room:
            c[i]=!--X,              //  Pick it up
            --q:                    //  Decrease our inventory capacity
        j==71&&c[i+17]?             // If 'G'o to room, and we have the key:
            r=57-i:                 //  Go to the room
        j<68&&                      // If 'C'ombine, and...
              c[i]*c[j=2[*v]]       // ...we have the items and...
                             &&P?   // ...they can be combined
            c[i]=c[j]=0,            //  Remove the items
            c[P]=++q:               //  Add the combined item and increase capacity
        0                           // Unrecognised or invalid command
    )
        j=**v;                      // 'j' is the command letter (happens first)
    return r;                       // Return the final room (0 = truthy in shell)
}

```

Partially inspired by @edc65's answer.

---

I was so close to getting `;*++*v;` and `c[P][c]` into the code for ultimate confusion, but unfortunately other options turned out to be shorter :(

# Answer
> 2 votes
## Haskell, ~~354~~ ~~325~~ 323 bytes

```
(#)=elem
(#)=elem
(%)=filter.(/=)
m!s=g""0.zip[0..]where g _ p _[]=p>8;g i p r(c:d)|p>8=1<2|'P':[k]<-c,k#x,length i<s=g(k:i)p((p,k%x):r)d|'D':[k]<-c,k#i=g(k%i)p((p,k:x):r)d|'C':q@[k,l]<-c,k#i,l#i,[y]<-[f|[d,e,f]<-m,q==[d,e]||q==[e,d]]=g(y:k%(l%i))p r d|'G':n<-c,y<-read n,['A'..]!!y#i=g i y r d|1<2=g i p r d where Just x=lookup p r

```

Defines a function `!` which takes in order

* the possible combinations as a list of 3 letter strings
* the maximum size of the inventory
* the rooms as a list of 9 strings
* the player commands as a list of strings

Returns `True` or `False`. Example call:

```
*Main> (!) ["YZW"] 2 ["YZJ","","","","","","","","",""] ["PY","PZ","CYZ","PJ","CWJ","G9"]
True

```

All test cases.

Many bytes are spent in carrying the game state around. Haskell cannot destructively update data structures like the rooms and inventory.

The work is done by function `g` which takes 4 parameters: the inventory (String), the current room (Integer), the rooms (Assoc-List, with key: room number and value: items) and the commands left (List of String).

```
g _ p _[] = p>8                     -- base case. if no commands left, return
                                    -- True if we are in room 9
g i p r(c:d)
  | p>8 =   1<2                     -- reached room 9
  | 'P':[k]<-c,                     -- 'Pickup', if
        k#x,                        --   key is in room and
        length i<s                  --   inventory not full
        = g(k:i)p((p,k%x):r)d       --   adjust inventory and room
  | 'D':[k]<-c,                     -- 'Drop', if
        k#i                         --   key is in inventory
        = g(k%i)p((p,k:x):r)d       --   adjust inventory and room
  | 'C':q@[k,l]<-c,                 -- 'Combine', if
        k#i,l#i,                    --   both keys are in inventory and
        [y]<-[f|[d,e,f]<-m,q==[d,e]||q==[e,d]]
                                    --   combination is possible
        = g(y:k%(l%i))p r d         --   adjust inventory
  | 'G':n<-c, y<-read[n],           -- 'Goto', convert digit to integer
        ['A'..]!!y#i                --   key for room is in inventory
        = g i y r t                 --   go to room
  | 1<2                             -- impossible command
        = g i p r d                 --   ignore it

```

Maybe the following things can save some bytes

* State Monad for the game state
* ~~A single Assoc-List for the keys (key: letter of key, value: room number with `-1` for inventory) instead of rooms/inventory~~ No, constructing such an initial Assoc-List and the check for max inventory size costs more than it saves dealing with one less parameter.

# Answer
> 1 votes
# Python 3, ~~321~~ 311 bytes

-10, thanks Dave

```
S,F=set,frozenset
def f(r,c,i,m):
 w,v,r,c=0,S(),list(map(S,r)),{F(k):S(x)for*k,x in c}
 for a,*q in m:
  p=F(q)
  if a<'D'and p in c and p<=v:v-=p;v|=c[p]
  elif a=='D'and p<=v:r[w]|=p;v-=p
  elif a=='G'and F(chr(65+int(q[0])))<=v:w=int(q[0])
  elif a>'G'and p<=r[w]and len(v)<i:r[w]-=p;v|=p
  if w==9:return 1

```

Rooms (r), combinations (c) and moves (m) are all lists of strings. Max inventory (i) is an int.

Fairly straight forward implementation. Used set()s for the room contents and inventory to make updating easy. Used frozensets to key a dictionary of the combinations, so that the order of the 2 input items is irrelevant.

---
Tags: code-golf, simulation
---


title: Given a table, place in the chairs

text:
# Question
Title: Given a table, place in the chairs
# Challenge

You will be given a table as input, drawn with ASCII `|` and `_`. Your task is to set the chairs around it.

# Example

Input:

```
 ____
|    |
|    |
|    |
|    |
|____|

```

Output:

```
 _^_^_
<     >
|     |
<     >
|     |
<_ _ _>
  v v

```

Those chairs are made of `<>` and `v^`.

Another example:

The line must have as many chairs as possible in it.

```
  _____
 |     |_____
 |           |
 |           |
 |           |
 |      _____|
 |_____|

  _^_^_
 <     |_^_^_
 |           >
 <           |
 |           |
 <      _ _ _>
 |_ _ _| v v
   v v

```

There must be spaces between every chair. And `>_^_^_<` is invalid, it should be `|_^_^_|`.

```
  _____       _____
 |     |_____|     |
 |                 |
 |                 |
 |                 |
 |      ___________|
 |_____|

  _^_^_       _^_^_
 <     |_^_^_|     >
 |                 |
 <                 >
 |                 |
 <      _ _ _ _ _ _>
 |_ _ _| v v v v v
   v v

```

No chairs may be on the inside of a "donut".

```
  _________________
 |      _____      |
 |     |     |     |
 |     |     |     |
 |     |_____|     |
 |_________________|

  _^_^_^_^_^_^_^_^_
 <      _____      >
 |     |     |     |
 <     |     |     >
 |     |_____|     |
 <_ _ _ _ _ _ _ _ _>
   v v v v v v v v

```

`^` and `v` prioritise `<` and `>`. No chair on it's own (it has to have at least one `|` or `_` in the row).

```
  _________________
 |      _____      |
 |     |     |     |
 |     |     |_____|
 |     |_____
 |___________|

  _^_^_^_^_^_^_^_^_
 <      _ _ _      >
 |     | v v |     |
 <     >     <_ _ _>
 |     |_^_^_  v v
 <_ _ _ _ _ _|
   v v v v v

```

This is code golf, so shortest code wins.

# Answer
# Python 2, ~~1033~~ ~~1007~~ ~~924~~ ~~879~~ ~~829~~ ~~787~~ ~~713~~ ~~699~~ ~~692~~ ~~691~~ ~~688~~ ~~687~~ ~~672~~ ~~670~~ ~~664~~ ~~659~~ ~~654~~ ~~648~~ ~~643~~ ~~642~~ ~~630~~ ~~625~~ ~~623~~ ~~620~~ ~~570~~ ~~560~~ ~~554~~ ~~545~~ ~~518~~ ~~514~~ ~~513~~ ~~510~~ ~~505~~ ~~492~~ ~~476~~ ~~454~~ ~~451~~ 443 bytes

*6 bytes saved thanks to Riley*

*6 bytes saved thanks to Adnan*

Since this question is over a year old and still has no answers I thought I'd give it a try.

```
n,i,o,u="\nI _";R=lambda x:range(1,x-1)
b=open(i).read()
s=b.split(n)
z=max(map(len,s))+3
a=[list(i+x.ljust(z,i))for x in[i]+s+[i]]
for x in R(len(a))*len(b):
 A=a[x];B=a[x+1];C=a[x-1]
 for y in R(z):
    D=A[y-1:y+2];k=B[y];j=A[y+1]
    if(i in[C[y],k]+D+(k==u)*B[y-1:y+2]or"V"==j)&(A[y]==o):A[y]=i
    if"|"==A[y]==C[y]:A[y]={i:"|",j:">",A[y-1]:"<"}[i]
    if[u]*3==D:A[y],B[y]={i:u+k,C[y]:"^"+k,k:" V"}[i]
print n.join(`y`[2::5]for y in a).replace(i,o)

```

Try it online!

The program reads the table a file named `I` and prints the table with its chairs to `std::out`. I was not sure about a bunch of the edge cases so I took my best judgement (whatever took the least effort) but it seems to pass all the test cases. Some of the outputs don't match exactly but they all have the same number of chairs.

## Explanation

The first line pretty simply sets up some definitions that will save us bytes in the future:

*(I will unpack these macros for readability in future lines)*

```
n,i,o="\nI ";R=lambda x:range(1,x-1)

```

Then we will open a file named `I` because we already have a variable that is short for that so it saves a few bytes.

```
b=open("I").read().split("\n")

```

We split along newlines to create a list of strings (The rows of the image)

```
s=b.split(n)

```

I then find the length of the longest line so that I can pad all lines to that length. (I also add 3 because we need a bit of additional padding)

```
 z=max(map(len,s))+3

```

Then we perform the actual padding and create a border of `I` characters around the edge. This is because we will need to tell the difference between the inside and the outside of the shape later on. We will also change the data type from a list of strings to a list of list of characters (length 1 strings).

```
a=[list("I"+x.ljust(z,"I"))for x in["I"]+s+["I"]]

```

The next line is just another byte saving definition.

*(I will also unpack this one)*

```
B=R(len(a))

```

Now we want to spread `I` characters to everywhere outside of the shape. We can do this with a pseudo-cellular automaton. Each `I` will spread to any adjacent  characters. We could loop until the automaton stabilizes however this cannot take more iterations than there are characters so we just loop through every character in `b` (the original input)

```
for _ in b:

```

For each iteration we want to pass over every character in the 2D list (excluding the outermost padding)

```
 for x in range(1,len(a)-1):
    A=a[x]  #<--Another definition I will fill in for clarity
    for y in range(1,z-1):

```

For each position we run the following code:

```
if("I" in[a[x+1][y],a[x-1][y]]+a[x][y-1:y+2])&(a[x][y]==" "):a[x][y]=" "

```

Lets break this down.

We have an if with two conditions separated by a `&` (bitwise `and`)

The first one simply checks if there is an `I` in any of the adjacent cells and the second one just checks if the current cell is a `" "`. If we pass those conditions we set the current cell to be an `I`.

---

Now that we have determined the outside and inside of the shape we can start to place the chairs around the table.

Once again we loop through all of the cells (and set some more shorthands)

```
for x in range(1,len(a)-1):
 A=a[x]
 for y in range(1,z-1):
        k=a[x+1][y]

```

Now here's my favorite part. If you have trudged through my boring, mostly definition based, golfing so far I am going to reward you with a nice tidbit of clever golfing (if I do say so myself).

A little background in python:

In Python if you attempt to assign an dictionary key twice it asigns the latter one. For example

```
>>> {1:"a",1:"b"}[1]
'b'

```

We will abuse this property to assign the current cell to a particular character.

The first condition is

```
if["_"]*3==a[x][y-1:y+2]:a[x][y],a[x+1][y]={"I":"_"+a[x+1][y],a[x-1][y]:"^ ",a[x+1][y]:" V"}["I"]

```

If the cell is in the middle of an edge of 3 `_` characters we will reassign the current cell and the cell below it. We will assign it to the result of indexing an overloaded dictionary by `I`. We first set our default with the pair `"I":"_"+a[x+1][y]` this means if there is no change we will assign the two cells back to their original values. Next we add the pair `a[x-1][y]:"^ "`. This wont do anything (important) unless the cell above the current one (`a[x-1][y]`) is filled with an `I`. If it has an `I` in it it will override the default telling us to place a chair at the current cell. Next we move on to the cell below the current cell if that cell is `I` we again override to place an upwards facing chair below the current spot.

The next condition is a tad simpler

```
if"|"==a[x][y]==a[x-1][y]:a[x][y]={"I":"|",A[y+1]:">",A[y-1]:"<"}["I"]

```

We check if the current cell and the cell above it are both `|`. If so we set up a dictionary.

The first pair in the dictionary `"I":"|"` sets the default. Since we are going to access the key `I` if `I` does not get reassigned it will default back to `|` (the character it already is) and do nothing.

We the add the two keys `A[y+1]:">",A[y-1]:"<"` If either of the two cells to the left and right are `I` then it will reassign the current cell to a chair pointing in the direction of the outside.

---

Now we just have to output. However we can't just print, there are a couple of housekeeping things we have to do first. We have to convert back to a string and remove all of the `I`s we created. This is done in one line.

```
print "\n".join(`y`[2::5]for y in a).replace("I"," ")

```
> 33 votes

---
Tags: code-golf
---


title: Be respectful in the restroom

text:
# Question
Title: Be respectful in the restroom
Of course, the SE network is very knowledgeable about how to be respectful in the restroom, but for those of you who need a recap, being respectful means flushing the toilet, etc. Most importantly, though, it means using the stall as far away from others as possible.

**The challenge**

Given a blueprint of a set of stalls with indications of which ones are in use as a string, you must return or print from a function or program where the most respectful place to do your business is.

**The input**

```
 0 1 2 3 4 5    <- The stall number which is not actually visible in the input.
| | |-| |-|-|   <- the stalls

```

The stalls are numbered in ascending order from left to right. There will always be at least one empty stall. There can be up to 50 stalls in an input. You can also take the input as an array or string of `0`s and `1`s or booleans if you prefer to do so.

Stalls in use have `-` in them (in between the pipes).

**The output**

The most respectful stall to go to is the one that is on average farthest away from the ones in use. The distance between two stalls is the absolute value of the difference of the numbers above them.

Just to be clear: you are finding the average distance from *all* of the stalls—not just the neighboring ones.

You must output the lowest number of the most respectful stall to go to **that is empty**.

**Examples**

```
Input:
|-| |-| OR 101
Output:
1

Input:
| | |-| |-|-| OR 001011
Output:
0

Input:
|-| |-| | | | |-|-| OR 101000011
Output:
1

Input:
|-| | | | | |-|-| | | | | OR 100000110000
Output:
11

Input:
|-|-|-|-| | | | | | |-| OR 11110000001
Output:
9

Input:
|-| | OR 10
Output:
1

Input:
|-| | |-| OR 1001
Output:
1

```

This is , so shortest code in bytes wins!

You can use 0 or 1 based indexing in your answer — whichever you prefer; if you use 1 based indexing, then you must say so explicitly in your answer.

# Answer
> 12 votes
# Jelly, ~~10~~ 9 bytes

```
JạþTS×¬MḢ

```

Uses 1-based indexing. Try it online! or verify all test cases.

### How it works

```
JạþTS×¬MḢ  Main link. Argument: A (array of Booleans)

J          Yield all indices of A.
   T       Yield all truthy indices of A.
 ạþ        Compute the table of absolute differences.
    S      Compute the sums of all columns.
           For each index, this yields the sum of all distances to occupied stalls.
     ×¬    Multiply each sum by the logical NOT of the corresponding Boolean in A.
           This zeroes sums that correspond to occupied stalls.
       M   Maximal; yield an array of all indices of maximal sums.
        Ḣ  Head; extract the first index.

```

# Answer
> 6 votes
# Swift, ~~158, 157, 128,~~ 100 Bytes

Takes input from the `Array<Bool>` variable `i`, returns answer from the last expression.

```
let e=i.characters.map{$0>"0"}.enumerate()
e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0

```

Edit 1:

Saved a byte by converting to bools via string comparison

```
let e=i.characters.map{$0=="1"}.enumerate()
e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0

```

Edit 2:

Reworked my algorithm:

```
let e=i.characters.map{$0=="1"}.enumerate()
e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0

```

Edit 3:

Took advantage of new rule that allows taking input directly from a boolean array.

```
let e=i.enumerated()
e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0

```

Ungolfed:

<pre><code>// for the sake of easier copy/pasting of input, take it as string
let s = "100000110000"

// convert input to true for taken, false for free
// this is the input the golfed version actually uses
let input = s.characters.map{$0>"0"}

// Returns an array of tuples storing the array values (vacancy of the stall) and their index (their location)
let valueIndexPairs = bools.enumerated()

// Returns an array of pairs of locations and their avg distance to others
let locationDistancePairs = valueIndexPairs.map{(valueIndexPair: (Int, Bool)) -> (Int, Int) in

    let averageDistance = valueIndexPairs.reduce(0) {partialSum, otherStall in

        let otherStallIsTaken = otherStall.1

        if otherStallIsTaken {
            //don't let other stalls effect average if they're taken
            return partialSum
        }
        else {
            let thisStallLocation = valueIndexPair.0
            let otherStallLocation = otherStall.0
            let distanceToOtherStall = abs(thisStallLocation - otherStallLocation)
            return partialSum + distanceToOtherStall
        }
    }

    //if this stall is taken, treat its average distance to others as 0
    let thisStallsLocation = valueIndexPair.0
    let isThisStallTaken = valueIndexPair.1
    return (thisStallsLocation, isThisStallTaken ? 0 : averageDistance)
}

//find location where average distance is maxiumum
let bestLocationIndexPair = locationDistancePairs.max{$0.1 < $1.1}!

let bestLocation = bestLocationIndexPair.0

print(bestLocation)
```
</code></pre>

# Answer
> 5 votes
# Jelly, 13 bytes

1-indexed.

```
³Tạ⁸S
JUÇÞḟTṪ

```

Try it online!

### Algorithm

Naive implementation of the question.

# Answer
> 5 votes
# Java "only" ~~270 200 196 187 196 138 148~~ 146 bytes!

saved  ~~4 13~~ countless bytes thanks to Leaky Nun! ~~1 byte thanks to Micheal~~ Golfed

```
int m(boolean[]b){int r=0,l=b.length,i,j,k=0,z=r;for(i=0;i<l;i++){if(b[i])for(j=0,k=0;j<l;j++)if(!b[j])k+=i>j?i-j:j-i;if(k>z){r=i;z=k;}}return r;}

```

Ungolfed

```
int m(int[] s) {
        int l=s.length,i,j=0,k=0;
    boolean[] b = new boolean[l];
    int[] a = new int[l];
    //see what stalls are open
    for (i = 0; i < s.length; i++) {
        if (s[i] == 0){
            b[i] = true;
        }
    }
    //assign the sum of distance to the a[]
    for (i = 0; i < l; i++) {
        if (b[i]) {
            for (j = 0; j < l; j++) {
                if (!b[j]) {
                    a[i]+= Math.abs(i - j);
                }
            }
        }
    }
    //find the stall the greatest distance away breaking ties based on the furthest left
    for (i = 0; i < l; i++) {
        if (b[i] && (a[i] > k || k == 0)) {
            k = a[i];
            j=i;
        }
    }
    //return the index
    return j;
}

```

input as an boolean array where true implies an open stall.

# Answer
> 4 votes
# Ruby, ~~79~~ ~~78~~ 76 + `n` flag = 77 bytes

Output is 0-based indexing. Input is STDIN line of 0's and 1's.

```
p (r=0...~/$/).max_by{|i|k=0;$_[i]>?0?0:r.map{|j|k+=$_[j]<?1?0:(j-i).abs};k}

```

# Answer
> 2 votes
## Perl 84 + 3 (`-alp` flags) = 87 bytes

```
for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]}

```

Needs `-alp` flags to run. Takes a string of 1 and 0 separated by spaces as input. For instance :

```
perl -alpe '$m=0;for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]}' <<< "1 0 1
0 0 1 0 1 1
1 0 1 0 0 0 0 1 1
1 0 0 0 0 0 1 1 0 0 0 0
1 1 1 1 0 0 0 0 0 0 1
1 0"

```

Note that I added `$m=0` at the begining, but that's only to test it on multiple entries.

# Answer
> 2 votes
# MATL, 14 bytes

```
~ftGf!-|Xs&X>)

```

**Try it online!**

Output is 1-based.

### Explanation

```
~f     % Implicitly take input. Compute row vector with indices of zeros
t      % Duplicate that
Gf!    % Push input again. Compute column vector of indices of ones
-|     % Absolute differences with broadcast. Gives 2D array with all combinations
Xs     % Sum of each column
&X>    % Arg max. Gives the index of the first maximizer if there are several
)      % Index into row vector of indices of zeros. Implictly display

```

# Answer
> 2 votes
## JavaScript (ES6), ~~87~~ ~~86~~ ~~82~~ 75 bytes

```
a=>a.map((u,i)=>u||(a.map((v,j)=>u+=v*(i>j?i-j:j-i)),u>x&&(x=d,r=i)),x=0)|r

```

Takes a boolean array (true/false or 1/0). No point calculating the average distance since they're all using the same common factor, so just calculating the total distance for each stall and finding the first index of the highest one. Edit: Saved 1 byte by using `*` instead of `&&`. Saved 5 bytes by finding the highest distance manually based on a comment by @Dendrobium. Saved 7 bytes by reusing `u` as the pseudo-reduce accumulator based on a comment by @edc65.

# Answer
> 2 votes
## Matlab, 87 bytes

```
n=input('');k=numel(n);[a b]=ndgrid(1:k);[x y]=max(sum(abs(a-b).*repmat(n,k,1)').*~n);y

```

Takes array of ones and zeros; uses 1-based indexing.
Like some other answers maximises total not average distance.
Probably there's some more golfing possible...

# Answer
> 1 votes
# Ruby, ~~87~~ 76 bytes

Threw this first draft quickly together, but in the meantime Value Ink had already posted an 80 byte Ruby answer...

edit: took off some bytes with help from Value Ink:

```
->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}}

```

It's an anonymous function that takes an array of truthy/falsy values, like for instance so:

```
f=->->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}}
# Test case number 5:
p f[[1, 1, 1, 1, nil, nil, nil, nil, nil, nil, 1]] # => 9

```

# Answer
> 1 votes
# J, 27 bytes

```
(#{:@-.~]/:[:+/]|@-/~#)i.@#

```

Online interpreter.

# Answer
> 1 votes
# Mathematica, 53 bytes

```
MaximalBy[a=PositionIndex@#;a@0,Tr@Abs[#-a@1]&][[1]]&

```

Uses 1-based indexing and takes input as a list of 0s and 1s.

# Answer
> 0 votes
# Javascript ES6 - ~~98~~ ~~95~~ ~~91~~ ~~86~~ ~~84~~ 88 bytes

Edit: Seems that the leftmost-stall should be used in the case of a tie. Squared distances no longer work, reverted to absolute distance.

```
(r,x=0,f=g=>r.reduce(g,0))=>f((p,o,i)=>x<(o=f((p,c,j)=>p+c*!o*Math.abs(i-j)))?(x=o,i):p)

```

Ungolfed:

```
(r,                            // string input
 x=0,                          // current max distance
 f=g=>r.reduce(g,0))=>         // iterator function
   f((p,o,i)=>                 // for each stall
     x<(o=f((p,c,j)=>          // iterate through all stalls and
       p+c*!o*Math.abs(i-j)))? //   calculate sum of distances from current stall
     (x=o,i):                  // if total dist is greater than x, update x, return index
     p)                        //   else return previous max index

```

Test runs:

```
f=(r,x=0,f=g=>r.reduce(g,0))=>f((p,c,i)=>x<(c=+c?0:f((p,c,j)=>p+c*Math.abs(i-j)))?(x=c,i):p)
f([1,0,1])                   // 1
f([0,0,1,0,1,1])             // 0
f([1,0,1,0,0,0,0,1,1])       // 1
f([1,0,0,0,0,0,1,1,0,0,0,0]) // 11
f([1,1,1,1,0,0,0,0,0,0,1])   // 9
f([1,0])                     // 1

```

# Answer
> 0 votes
# Lua, 165150 Byes

```
n=arg[1]n=n:gsub("%|%-","1"):gsub("%| ","0")i=0 for s in n:gmatch("0+")do i=(i<#s)and(#s)or(i)end n,l=n:find(("0"):rep(i))print(n+math.floor((l-n)/2))

```

This cheats a little using the fact that generally, lua passes a table called arg containing any command line inputs to it.

I'm a bit disappointed that I used a for in loop, but I couldn't think of a smaller way to pull it off.

Also, Because lua, 1 based indexing was used.

Edit Snipped 15 bytes from a wasteful gsub.

# Answer
> 0 votes
# C#, 127 bytes

```
public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();}

```

# Test Bed

```
public static void Main() {
    var respectful = new Respectful();
    foreach (var kvp in testCases) {
        $"{kvp.Key}: Expected {kvp.Value} Actual {respectful.G(kvp.Key.ToCharArray())}".Dump();
    }
}

public static readonly List<KeyValuePair<string, int>> testCases = new List<KeyValuePair<string, int>> {
    new KeyValuePair<string, int>("101", 1),
    new KeyValuePair<string, int>("001011", 0),
    new KeyValuePair<string, int>("101000011", 1),
    new KeyValuePair<string, int>("100000110000", 11),
    new KeyValuePair<string, int>("11110000001", 9),
    new KeyValuePair<string, int>("10", 1),
    new KeyValuePair<string, int>("1001", 1),
};

public class Respectful {
    public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();}
}

```

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


title: Fix my IPv4 address's missing periods

text:
# Question
Title: Fix my IPv4 address's missing periods
Sometimes when I'm typing out an IPv4 address, I get all the numbers right, but I forget to type one or more periods. I'd like to have a program (or function) that takes my broken IPv4 address and outputs all possible valid placements of the missing periods.

## Input

The input will always be a string that is a transformation of a valid IPv4 address (see particulars below). It will always have been transformed solely by the elimination of one or more period characters.

You submission does not need to handle inputs outside of this format.

## Output

A collection or list, in no particular order or format, of strings representing all valid IPv4 addresses that can be created from the input by the insertion of period characters into the input.

* The output may be a language-native list or other ordered or unordered collection type.
* Alternatively, it may be a string sequence of IPv4 address delimited in some clear way.
    + If you use a single-character delimiter to delimit your string, periods and digits are not allowed as that single-character delimiter. I realize that, unlike numbers, periods as delimiters are not *ambiguous* (since every fourth period would necessarily be a delimiter) but for the sake of readability, I am disallowing it.

## IPv4 address format

While IPv4 addresses are really just a sequence of four binary octets, this challenge uses a restricted dotted decimal format.

* An IPv4 address is a four decimal values separated by three periods.
* Each of the four values are in the range `0` to `255`, inclusive.
* **Leading zeros are not allowed** in any number value. (Standalone one-character `0` is allowed; any other number beginning with a zero is not: `052`, `00`, etc.)

## Test Cases

Input is on the first line, output on second line (here, structured as a comma-separated list of quoted strings, separated by commas, surrounded by `[` `]`, but you may use any reasonable format or structure, as specified above). Some examples have notes on a third line to highlight the application of a particular rule.

```
192.168.1234
["192.168.1.234", "192.168.12.34", "192.168.123.4"]

192.1681234
["192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]
(Note: 192.1681.2.34 (etc.) is illegal because 1681 is greater than 255)

1921681.234
["19.216.81.234", "192.16.81.234", "192.168.1.234"]

1921681234
["19.216.81.234", "192.16.81.234", "192.168.1.234", "192.168.12.34", "192.168.123.4"]

192.168.1204
["192.168.1.204", "192.168.120.4"]
(Note: 192.168.12.04 is illegal because of leading zero)

192.168.123
["1.92.168.123", "19.2.168.123", "192.1.68.123", "192.16.8.123", "192.168.1.23", "192.168.12.3"]

192.168.256
["192.168.2.56", "192.168.25.6"]
(Note: Any combination that would leave 256 intact is illegal)

120345
["1.20.3.45", "1.20.34.5", "1.203.4.5", "12.0.3.45", "12.0.34.5", "120.3.4.5"]
(Note: 12.03.4.5 (etc.) is illegal due to leading zero.)

012345
["0.1.23.45", "0.1.234.5", "0.12.3.45", "0.12.34.5", "0.123.4.5"]
(Note: the first segment must be 0, because `01` or `012` would be illegal.)

000123
["0.0.0.123"]

```

(I made these examples by hand, so please alert me to any mistakes you may find.)

# Answer
# Pyth, 24 bytes

```
f&q4lJcT\.!-J`M256jL\../

```

Try it online

### How it works

```
                      ./Q   all partitions of input
                  jL\.      join each on .
f                           filter for results T such that:
      cT\.                    split T on .
     J                        assign to J
    l                         length
  q4                          equals 4
 &                            … and:
           -J`M256              J minus the list of representations of [0, …, 255]
          !                     is false (empty)

```

# Pyth, 17 bytes, very slow

```
@FjLL\.,^U256 4./

```

**Warning. Do not run.** Requires approximately 553 GiB of RAM.

### How it works

```
       ,             two-element list of:
        ^U256 4        all four-element lists of [0, …, 255]
               ./Q     all partitions of input
  jLL\.              join each element of both on .
@F                   fold intersection

```
> 9 votes

# Answer
# C (gcc/linux), 125 121 bytes

```
i;f(char*a){do{char*y=a,s[99],*x=inet_ntop(2,&i,s,99);for(;*x&&!(*x^*y&&*x^46);++x)y+=*x==*y;*x|*y||puts(s);}while(++i);}

```

Loops over **all** possible IPv4 addresses, and does a custom comparison that skips over extra dots in the generated ip address (but not in the main comparison address) to decide whether to print or not. **Very slow, but should finish within 1 hour on a reasonable PC**.
> 16 votes

# Answer
# Perl 5, 91 bytes

```
<>=~/^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$(?{print"$1.$3.$4.$5 "})^/

```

The program expects a single line of a single input and outputs space-delimited list of candidates.

### Explanation

The program exploits the backtracking feature of regex to loop over all possibilities of forming a valid IPv4 address from the input string.

```
^(([1-9]?|1\d|2[0-4])\d|25[0-5])\.?((?1))\.?((?1))\.?((?1))$

```

The IPv4 regex with optional `.`, nothing of note here.

```
(?{print"$1.$3.$4.$5 "})

```

A code evaluation expression which prints out the content of the capturing groups.

```
^

```

Make the match fails and force backtracking.

### Example run

```
$ echo "012345" | perl G89503.pl
0.12.34.5 0.12.3.45 0.1.23.45 0.1.234.5 0.123.4.5

```
> 6 votes

# Answer
## JavaScript (ES6), ~~147~~ ~~141~~ 135 bytes

```
f=(s,n=0)=>(a=s.split`.`)[3]?a.every(s=>s==`0`|s[0]>0&s<256)?s+' ':'':[...s].map((_,i)=>i>n?f(s.slice(0,i)+`.`+s.slice(i),i):``).join``
```

```
<input placeholder=Input oninput=o.textContent=f(this.value)><div id=o style=font-family:monospace;width:1em>Output
```

Edit: saved 6 bytes thanks to @apsillers. Saved another 6 bytes by copying @YOU's validity test.
> 5 votes

# Answer
# Python 3, 232 bytes

```
import re,itertools as t,ipaddress as k
R=range
i=input()
for d in R(5):
 for p in t.combinations(R(len(i)),d):
  n=i;o=0
  for a in p:n=n[:a+o]+'.'+n[a+o:];o+=1
  try:k.ip_address(n);print(n*(not re.search(r'\D?0\d',n)))
  except:0

```

Pretty simple: We place periods everywhere and print if the IP address with the periods placed is valid. We check the validity of the IP adresses by (ab)using `ipaddress.ip_address`, which raises an exception if the input is not a valid IP address. The challenge defines some additional rules that `ip_address` doesn't handle (namely, that there can be no leading zeroes), so we check for those too with a regular expression, then print.

Outputs each solution on a new line, mixed with an arbitrary number of blank lines.

Example run:

```
$ echo 012345 | python fixip.py
0.1.23.45
0.1.234.5
0.12.3.45
0.12.34.5
0.123.4.5

$ echo 000123 | python fixip.py
0.0.0.123

_

```

Here's my older, 248-byte Python 2 solution. The second and third indent levels are `\t` (raw tab) and `\t`  (raw tab plus space) respectively. This plays *really* badly with Markdown, so the tabs have been replaced by two spaces.

```
import socket,re,itertools as t
R=range
i=input()
for d in R(5):
 for p in t.combinations(R(len(i)),d):
  n=i;o=0
  for a in p:n=n[:a+o]+'.'+n[a+o:];o+=1
  try:
   socket.inet_aton(n)
   if n.count('.')==3and not re.search(r'\D?0\d',n):print n
  except:0

```

Requires the input surrounded with quotes (e.g. `"123.456.789"`). Outputs each generated IP address on a new line.

*Saved 9 bytes thanks to @grawity!*
> 4 votes

# Answer
# Brachylog, 110 bytes

```
:ef:{".",@N.|.}ac:3f:{@n:"."rz:cacb.}a.
,4yeN,?:N:6i.@nMl4,M:{:7&<256}a
~c[A:B]h:@N:Bc.
:ef:{,"0":"9"y:.m?}ac.

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~262~~ 260 bytes

```
p,l,L,T=set(),-1,len,tuple
while l<L(p):l=L(p);p|={T(z[:i]+(y[:j],y[j:])+z[i+1:])for z in set(p)or[T(input().split("."))]for i,y in enumerate(z)for j in range(1,L(y))}
print(['.'.join(x)for x in p if L(x)==4and all(y=='0'or y[0]!='0'and int(y)<256for y in x)])

```

No libraries used, but late and longer, may be I am missing some obvious golfing techniques.

Results anyway.

```
for x in 192.168.1234 192.1681234 1921681.234 1921681234 192.168.1204 192.168.123 192.168.256 120345 012345 000123; do
echo $x | python3 ipv4.py
done;

['192.168.123.4', '192.168.1.234', '192.168.12.34']
['192.16.81.234', '192.168.1.234', '192.168.123.4', '192.168.12.34']
['19.216.81.234', '192.168.1.234', '192.16.81.234']
['19.216.81.234', '192.168.123.4', '192.168.12.34', '192.16.81.234', '192.168.1.234']
['192.168.1.204', '192.168.120.4']
['192.16.8.123', '19.2.168.123', '1.92.168.123', '192.168.1.23', '192.168.12.3', '192.1.68.123']
['192.168.25.6', '192.168.2.56']
['1.20.3.45', '1.203.4.5', '12.0.34.5', '120.3.4.5', '1.20.34.5', '12.0.3.45']
['0.1.23.45', '0.12.3.45', '0.12.34.5', '0.123.4.5', '0.1.234.5']
['0.0.0.123']

```
> 2 votes

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