title: CGAC2022 Day 17: Present Heap

text:
# Question
Title: CGAC2022 Day 17: Present Heap
Part of **Code Golf Advent Calendar 2022** event. See the linked meta post for details.

---

*Inspired by https://xkcd.com/835*

In the midst of his mid-life crisis, Santa has impulsively purchased a Sports Sleigh™ for present delivery this year. The only problem is that this sleigh has a specially designed Infinite Present Trunk with rigid sides instead of a present bag with flexible ones. This means Santa must pack the presents optimally so there is as little empty space as possible.

## The Challenge

Write a program that takes as input a list of positive integers (representing the widths of the presents) and outputs a list of lists of positive integers (representing rows of presents) where each row follows these two rules:

* There are never *fewer* presents in each row than the one before it
* The *total width* of each row is the same as the width of the widest present

Your program must return any constant value if it is impossible to fulfill these rules. There may be multiple valid solutions; your program may output any of them.

## Examples

```
Input: [5, 1, 2, 6, 4, 3, 3]
Possible output: [[6], [5, 1], [2, 4], [3, 3]]
Visualization:
vvvvvv
+++++=
xx----
___ooo

Input: [9, 4, 2, 4, 5, 3]
Possible output: [[9], [4, 5], [3, 4, 2]]
Visualization:
+++++++++
vvvv=====
xxxoooo--

```

*I don't actually know if there exist any inputs with multiple possible outputs; it doesn't seem like it to me, but if you can prove there are or aren't please leave a comment! (I'm not counting trivial differences with different orderings of presents on a single row.)*

# Answer
> 4 votes
# 05AB1E, 14 bytes

```
æʒO¹àQ}éæ.Δ˜ÃQ

```

Try it online!

Explanation:

```
æʒO¹àQ}éæ.Δ˜ÃQ
æ               # powerset
 ʒ    }         # filter:
  O             #   sum
   ¹à           #   maximum of input
     Q          #   are equal
       é        # sort by length
        æ       # powerset
         .Δ     # first where the following is true:
           ˜    #   flatten
            Ã   #   intersect with implicit input
             Q  #   is equal to implicit input

```

# Answer
> 3 votes
# Vyxal, 16 bytes

```
ṖvøṖÞf'Ṡ?G=A;hÞṡ

```

Try it Online!

Extremely inefficient. Simply brute-forces it.

```
ṖvøṖÞf'Ṡ?G=A;hÞṡ
Ṗ                 # All permutations
 vøṖ              # For each, get a list of all ways to partition the list
    Þf            # Shallow flatten
      '           # Filter:
       Ṡ          #  Sum each
        ?G=A      #  All are equal to the max of the input?
            ;     # End filter
             h    # First item
              Þṡ  # Sort by length

```

# Answer
> 2 votes
# Japt, 21 bytes

Returns `undefined` if there is no result.

```
n
à f@Ì¶XxÃà æ@eXÔc n

```

Try it

```
n\nà f@Ì¶XxÃà æ@eXÔc n     :Implicit input of array U
n                          :Sort
 \n                        :Reassign to U
   à                       :Combinations
     f                     :Filter by
      @                    :Passing each X through the following function
       Ì                   :  Last element of U
        ¶                  :  Is equal to
         Xx                :  X reduced by addition
           Ã               :End filter
            à              :Combinations (in descending order of length)
              æ            :First element to return true
               @           :When passed through the following function as X
                e          :  U is equal to
                 XÔ        :    Reverse X (mutates the original)
                   c       :    Flatten
                     n     :    Sort

```

# Answer
> 2 votes
# Jelly, 16 bytes

```
ŒPS⁼¥ƇṀŒPFṢ⁼ɗƇṢṪ

```

A monadic Link that accepts a list of integers and yields a list of lists of integers representing the present rows, or the integer `0` if not possible.

**Try it online!**

### How?

```
ŒPS⁼¥ƇṀŒPFṢ⁼ɗƇṢṪ - Link: list of integers, Widths
ŒP               - power-set (Widths) (results are ordered by length, ascending)
      Ṁ          - maximum (Widths)
     Ƈ           - filter (the sets) keeping those for which:
    ¥            -   last two links as a dyad - f(set, max_width):
  S              -     sum (set)
   ⁼             -     (that) equals (max_width)?
       ŒP        - power-set (those)
              Ṣ  - sort (Widths)
             Ƈ   - filter (the sets of valid-sum sets) keeping those for which:
            ɗ    -   last three links as a dyad - f(set_of_sets, sorted_widths):
         F       -     flatten (the set_of_sets)
          Ṣ      -     sort (that)
           ⁼     -     (that) equals (sorted_widths)?
               Ṫ - tail

```

# Answer
> 2 votes
# JavaScript (ES2020), 140 bytes

Returns `0` if there's no solution.

```
f=(a,m=Math.max(...a),t,o=[],...p)=>a.some((v,i)=>f(a.filter(_=>i--),m,~~t+v,o,...p,v),t^m|p[o[0]?.length]||(o=[p,...o],p=t=[]))?O:a+p?0:O=o

```

Attempt This Online!

### Commented

```
f = (                   // f is a recursive function taking:
  a,                    //   a[] = input array
  m = Math.max(...a),   //   m   = highest value in a[]
  t,                    //   t   = sum of the current sub-array
  o = [],               //   o[] = array of sub-arrays
  ...p                  //   p[] = current sub-array
) =>                    //
a.some((v, i) =>        // for each value v at index i in a[]:
  f(                    //   do a recursive call:
    a.filter(_ => i--), //     remove the i-th element from a[]
    m,                  //     pass m unchanged
    ~~t + v,            //     add v to t
    o,                  //     pass o[] unchanged
    ...p, v             //     append v to p[]
  ),                    //   end of recursive call
                        //   loop initialization:
  t ^ m |               //     do nothing if t is not equal to m
  p[o[0]?.length] ||    //     or p is longer than o[0] (which is either the
  (                     //     previous sub-array or still undefined)
    o = [p, ...o],      //     otherwise, insert p[] at the beginning of o[]
    p = t = []          //     and start with p[] empty and t zero'ish
  )                     //
) ?                     // end of some(); if truthy:
  O                     //   return the solution O[]
:                       // else:
  a + p ?               //   if either a[] or p[] is non-empty:
    0                   //     incomplete or invalid solution: do nothing
  :                     //   else:
    O = o               //     save the solution in O[]

```

# Answer
> 2 votes
# Pyth, 18 bytes

```
MfqSsTSGyHlDhgQgeS

```

Try it online!

Returns an index error when there is no solution.

Somehow only used alphabetical characters as well, which is neat.

### Explanation

Power set is the poor man's partition. This solution is brute force, but a rather elegant one, I think. First we take the power set of the input and filter for elements whose sum is equal to the desired width. This means we now have a list of all possible rows (often with duplicates). Then we take the power set of the rows, and filter for elements which use the exact same elements as the input. This will give us all sets of rows that are valid solutions. From here it's simple, just pick any set and sort the rows by number of elements. The beauty comes from the fact that both of these steps look the same if you squint, and so by being clever we can write a single "power set and filter" function and just apply it twice.

```
MfqSsTSGyHlDhgQgeSQQ    # implicitly add QQ to the end
                        # implicitly assign Q = eval(input())
M                       # define g(G, H):
 f      yH              #   filter powerset(H) on lambda T
  qSsTSG                #   when H is a list and G is a number, this will check if T sums to G
                        #   but when H is a list of lists and G is a list, this will check if T and G use the same elements
          lD            # sort using length as the key
            h           # the first element of
             gQ         # power set filter Q,
               geSQQ    # power set filter max(Q), Q

```

# Answer
> 1 votes
# JavaScript (Node.js), 167 bytes

```
f=(x,i=z=[],...y)=>z=x.map((v,j)=>f(j=x.filter(_=>j--),[...i,v],...y)|f(j,[v],i,...y),L=[i,...y])+x?z:L.some((e,j)=>e.length<(y[j-1]||i).length|eval(e.join`+`)!=i)?z:L

```

Try it online!

# Answer
> 1 votes
# Charcoal, 58 bytes

```
Ｗ⁻Ｅ⊟ΦＥＸＬθＬθΦＥθΦθ⁼ν﹪÷κＸＬθπＬθμ⬤κ⁼Σμ⌈θ⁺⟦Ｌκ⟧κυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Try it online! Link is to verbose version of code. Explanation: Lots and lots of brute force (takes minutes on the examples) so link only has three presents.

61 bytes for a slightly less inefficient version that can just about complete the examples on TIO:

```
≔Ｅ⊟ΦＥＸＬθＬθΦＥθΦθ⁼μ﹪÷ιＸＬθξＬθλ⬤ι⁼Σλ⌈θ⁺⟦Ｌι⟧ιηＷ⁻ηυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Try it online! Link is to verbose version of code. Explanation: Calculates all `nⁿ` permutations of `n` presents in `n` rows, filters for valid answers, picks one, then sorts it. (But unlike the first version, it doesn't perform the calculation each pass of the sorting loop.)

65 bytes for a slightly less inefficient version:

```
≔÷Σθ⌈θη≔Ｅ⊟ΦＥＸηＬθΦＥθΦθ⁼μ﹪÷ιＸηξηλ⬤ι⁼Σλ⌈θ⁺⟦Ｌι⟧ιηＷ⁻ηυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Try it online! Link is to verbose version of code. Explanation: Still exponential time, but since we know the width of each row then we can calculate the number of rows, and take the `n`th power of that instead.

71 bytes for a version that's less inefficient for a large enough number of rows:

```
≔⟦⟦⟧⟧ηＦθ≔ΣＥηＥ⊞ＯκυΦＥκ⎇⁼νπ⁺ξ⟦ι⟧ξξη≔Ｅ⊟Φη⬤ι⁼Σλ⌈θ⁺⟦Ｌι⟧ιηＷ⁻ηυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Attempt This Online! Link is to verbose version of code. Explanation: Uses dynamic programming to generate integer partitions directly instead of filtering permutations, so `O(A000110(n))` instead of `O(kⁿ)`. This means that it can handle the example in @JonathanAllan's comment.

72 bytes for a version that's somewhat efficient for a small enough number of rows:

```
≔⟦Ｅ÷Σθ⌈θυ⟧ηＦθ≔ΣＥηΦＥκＥκ⎇⁼νπ⁺ξ⟦ι⟧ξ¬›Σ§μν⌈θη≔Ｅ⊟η⁺⟦Ｌι⟧ιηＷ⁻ηυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Attempt This Online! Link is to verbose version of code. Explanation: Based on the third version but using dynamic programming to to generate only matching integer partitions, but still generates all permutations of all integers in all rows.

85 bytes for an efficient version:

```
≔⟦υ⟧ηＦθ≔ΣＥη⁺ΦＥκＥκ⎇⁼νπ⁺ξ⟦ι⟧ξ⬤μ¬›Σξ⌈θ…⟦⁺κ⟦⟦ι⟧⟧⟧‹Ｌκ÷Σθ⌈θη≔Ｅ⊟η⁺⟦Ｌι⟧ιηＷ⁻ηυＦ№ι⌊ι⊞υ⌊ι⭆¹Ｅυ✂λ¹

```

Attempt This Online! Link is to verbose version of code. Explanation: Combination of the previous two so it avoids considering multiple empty rows for the same integer.

# Answer
> 1 votes
# Pip, 43 bytes

```
@(DNa=DNFL_FI(Ma=$+_FIaCB_MF,#a)CB_MF,#a)|0

```

Try It Online!

Pip doesn't have a command for powersets (that I could find), so I had to construct them manually. Explanation:

```
Ma=$+_FIaCB_MF,#a

```

All combinations of the input list where the sum of the combination equals the input max i.e. all possible row combinations

```
DNa=DNFL_FI(   )CB_MF,#a

```

All valid combinations of all possible row combinations, determined by comparing the sorted flattened combination with the sorted input

```
@()|0

```

Outputs the first valid combination, or `0` if no combination is found. No reordering is required, as the combination operator `aCBb` in pip automatically orders lists by ascending length.

# Answer
> 1 votes
# 05AB1E, 11 bytes

```
àÅœéæʒ˜œ€Qà

```

Extremely slow. Will output all possible results (replace filter `ʒ` with find\_first  to only output one - although that will still timeout for the second test case).

Try it online.

**Explanation:**

```
à            # Get the maximum of the (implicit) input-list
 Åœ          # Get lists of all positive integers that sum to this maximum
   é         # Sort those lists by length (shortest to longest)
    æ        # Get the powerset of this list of lists
     ʒ       # Filter this list of lists of rows by:
      ˜      #  Flatten the list of rows to a single list
       œ     #  Get all permutations of this flattened list
        €Q   #  Check for each permutation whether it's equal to the (implicit) input
          à  #  Check if any is truthy
             # (after which the filtered list is output implicitly)

```

---
Tags: code-golf, sorting, data-structures
---


title: Flip the order of operations

text:
# Question
Title: Flip the order of operations
Scientists have made contact with a parallel universe. Just one problem: They write math differently. Help the scientists make a program that can convert normal math expressions to their equivalent in alternate universe math. The connection through the portal is bad so your code needs to be as short as possible

Given a expression, containing only the operators `*`, `+`, parenthesis, and variables represented by single lower case ASCII letters, convert it from normal order of operations (`*` first then `+`) to inverse order of operations used in a parallel universe (`+` first then `*`). You must remove any redundant parenthesis.

Note: The expression will stay exactly the same. All you need to change is the position of the parenthesis.

Variable names are guaranteed to be unique. Expressions are guaranteed to be valid, be matched, and contain no invalid characters. There will never be redundant parenthesis in the input.

You may substitute `*` and `+` with any other 2 unique characters if you prefer. You may substitute `()` with `[]` or `{}` if you prefer.

## Test cases

| Before | After |
| --- | --- |
| `a+b` | `a+b` |
| `a+b*c` | `a+(b*c)` |
| `(a+b)*c` | `a+b*c` |
| `((a+b)*(c+d)+e)*f` | `(a+b*c+d)+e*f` |
| `(a*b+c*d)*e+f` | `((a*b)+(c*d)*e)+f` |
| `a+b+c` | `a+b+c` |
| `a*b*c` | `a*b*c` |

# Answer
> 6 votes
# Charcoal, 100 bytes

```
Ｆ²⊞υ⟦⟧ＦＳ«Ｆ№)+ι«≔⊟υη⊞§υ±¹⎇⊖Ｌη⪫()⪫η*⊟η»Ｆ№⁺)βι«Ｆ№)ι≔⪫⊟υ+ι⊞§υ±¹ι»Ｆ№((+ι⊞υ⟦⟧»≔⊟υη≔⊟υθ⊞θ⎇∧θ⊖Ｌη⪫()⪫η*⪫η*⪫θ+

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ²⊞υ⟦⟧

```

Start with two lists, one for the `+` group and one for the `*` group.

```
ＦＳ«

```

Loop over the characters in the input string.

```
Ｆ№)+ι«

```

If the current character is a `)` or `+`, then:

```
≔⊟υη

```

Remove the `*` group.

```
⊞§υ±¹⎇⊖Ｌη⪫()⪫η*⊟η

```

Join it with `*`s and wrap it in `()`s if there is more than one expression in the group, otherwise just push the expression to the `+` group.

```
»Ｆ№⁺)βι«

```

If the current character is a `)` or lowercase letter:

```
Ｆ№)ι

```

If it's a `)`, then...

```
≔⪫⊟υ+ι

```

... remove the `+` group and join it on `+`.

```
⊞§υ±¹ι

```

Push it to the (previous) `*` group.

```
»Ｆ№((+ι

```

If it's a `(` or `+`, then...

```
⊞υ⟦⟧

```

... for `+` restore the previously popped `*` group while for `(` push two new groups for `+` and `*`.

```
»≔⊟υη≔⊟υθ

```

Get the final `*` and `+` groups.

```
⊞θ⎇∧θ⊖Ｌη⪫()⪫η*⪫η*

```

Join the final `*` group on `*` and push it to the `+` group, wrapping it in `()`s if the `+` group is not empty.

```
⪫θ+

```

Join the `+` group on `+` and output the result.

# Answer
> 5 votes
# JavaScript (Node.js), 193 bytes

```
x=>g(eval(`[${x.replace(/./g,x=>x=='['|x==']'?x+',':`"${x}",`)}]`))
g=x=>x[1]?x.map(h=c=>h|=c==1?!!u.push(v=[]):v.push(c)&&c,u=[v=[]])|h-3?x.map(g).join``:u.map(v=>v[1]?`[${g(v)}]`:v).join`1`:x

```

Try it online!

# JavaScript (Node.js), 207 bytes

```
x=>g(eval(`[${x.replace(/./g,x=>x=='('?'[':x==')'?'],':`"${x}",`)}]`))
g=x=>x[1]?x.map(h=c=>h|=c=='+'?!!u.push(v=[]):v.push(c)&&c=='*'?2:0,u=[v=[]])|h-3?x.map(g).join``:u.map(v=>v[1]?`(${g(v)})`:v).join`+`:x

```

Try it online!

Was strongly messing `+` and `*`

# Answer
> 3 votes
# Python 3, 162 bytes

```
lambda s:g(compile(s,'','eval',1024).body,0)
def g(n,p):
 if'N'in'%s'%n:return n.id
 x='A'in'%s'%n.op;s=g(n.left,x)+'*+'[x]+g(n.right,x);return[s,f'({s})'][p-p*x]

```

Try it online!

Uses ast.

# Answer
> 2 votes
# JavaScript (Node.js), 116 bytes

```
s=>(M=o=>s[(q=s[i++])<')'&&A(),i++]=='*'?q+='*'+M``:o&&q,A=o=>s[q=M()&&o+s[i]?`(${q})`:q,i-1]>')'?q+='+'+A``:q)(i=0)

```

Try it online!

A simple recursive descent parser with syntax

```
A ::= M ["+" A]?
M ::= ("a" .. "z" | "(" A ")") ["*" M]?

```

```
s=> // s: input expression
    // i: index of current character (cursor)
(
  M= // Function for parsing M ::= ("a" .. "z" | "(" A ")") ["*" M]?
    o=> // o is undefined if invoked from A
        // o is empty array if invoked from M
      s[
        (q=s[i++])<')'&&A(), // read next character as token "a" .. "z"
                             // or if we got a '(', read an expression A
                             // save the result to variable `q`
      i++]=='*'? // if the following character is `*`
        q+='*'+M``: // we read the optional `"*" M` part
                    // save the result to variable `q` and return it
                    // returns something truthy
        o&&q, // we don't have the extra "*"
              // if o is undefined (invoked from A), return undefined
              //    which means we do not need "()" pairs
              //    if we add `q` with other expressions
              // if o is empty array (invoked from M), return the result
              //    so "q+='*'+M``" could work as expected
  A= // Function for parsing A ::= M "+" A | M
    o=> // o is undefined if invoked from from M
        // o is 0 if invoked from outer
        // o is empty array if invoked from A
        //   which means currently we are parsing a part of addition
        //   and we may need "()" in such case
      s[
        q=M()&& // read the M and the result is saved it to variable q
                // M() returns truthy if we need "()" in case of adding it
                // M() returns falsy if we do not need "()"
          o+s[i]? // if o is undefined (from M) or 0 (from outer)
                  //   and s[i] is undefined (the expression ends)
                  //     so we do not have more things to add
                  //   o+s[i] is NaN (falsy), means we do not need "()"
                  // in all other cases, o+s[i] is some non-empty string
                  //   (truthy), means we need "()"
            `(${q})`:q, // wrap `q` with "()" if needed, save result to `q`
        i-1]>')'? // if we have more thing to add
                  //   s[i-1] is "+" instead of ")"
          q+='+'+A``:q // add them and parse following additions if needed
)(i=0) // initial cursor to 0

```

# Answer
> 2 votes
# Rust + syn + quote, 315 bytes

```
use{syn::{*,Expr::*,BinOp::*},quote::*};
fn g(e:Expr,p:usize)->String{match
e{Path(e)=>e.to_token_stream().to_string(),Paren(e)=>g(*e.expr,p),Binary(e)=>{let
x=matches!(e.op,Add(_))as _;let
r=g(*e.left,x)+["*","+"][x]+&g(*e.right,x);[&r,&format!("({r})")][!x&p].into()}_=>loop{}}}let
f=|s|g(parse_str(s).unwrap(),0)

```

A port of gsitcia's python answer. Handling ASTs in Rust is actually really nice, but a little verbose compared to python.

Playground

---
Tags: code-golf, string, balanced-string, expression-building
---


# Question
Title: Count the shared substrings with 2 programs
Write 2 programs in the same language which count the number of shared subsequences of consecutive elements from 2 given sequences.

For example, given `"test"` and `"enter"`, there are 5 shared subsequences of consecutive elements:

```
t
t
e
e
te

```

One possible algorithm consists in counting, for each subsequence of consecutive elements of one sequence, the number of times it appears in the list of subsequences of the other one.

In our previous example, for `"test"`, `"t"` appears once in `"enter"`, `"e"` appears twice, `"t"` appears once, and `"te"` appears once; therefore we get 5 as output. (it does not matter if you pick `"test"` or `"enter"` as the "first" sequence).

### Scoring

Your score will be the result of one of your programs, when given your 2 programs as input. That is, the number of shared subsequences of consecutive elements between both programs.

Lowest score wins. In case of a tie, the lowest byte count of the sum of your 2 programs wins.

### Inputs

Both sequences will have at least 1 element.

The two input sequences can either be strings, or lists of chars, or lists of numbers, or any other fitting format for your language.

For example, if you take lists of numbers as inputs, your will transform your programs as lists of char codes according to your language’s code page.

### Test cases

```
a, b                  -> 0
test, enter           -> 5
hello, hello          -> 17
yes, yeyeyeah         -> 9

```

# Answer
# Python, score 0, 520 bytes

-25 from @Grain Ghost
-78 from @Jonathan Allan
-61 from @RootTwo
-4 from @Grain Ghost

```
class l:__class_getitem__=len
class r:__class_getitem__=range
class s:__class_getitem__=sum
f=lambda a,b:s[[b[g:h]==a[i:j]for j in r[l[a]+True]for i in r[j]for h in r[l[b]+True]for g in r[h]]]

```

```
("\x67\x3D\x6C\x61\x6D\x62\x64\x61\x20\x61\x2C\x62\x3A\x61\x3E\x27\x27\x61\x6E\x64\x20\x73\x75\x6D\x28\x62\x2E\x63\x6F\x75\x6E\x74\x28\x61\x5B\x3A\x70\x5B\x30\x5D\x2B\x31\x5D\x29\x66\x6F\x72\x20\x70\x20\x69\x6E\x20\x65\x6E\x75\x6D\x65\x72\x61\x74\x65\x28\x61\x29\x29\x2B\x66\x28\x61\x5B\x31\x3A\x5D\x2C\x62\x29")

```

Attempt This Online!

It was a team effort.
> 13 votes

# Answer
# 05AB1E, score 0 (15 bytes)

**Program 1 (3 bytes):**

```
Œ¢O

```

Try it online or verify all test cases.

**Program 2 (12 bytes):**

```
•K&}Í•3ôçJ.V

```

Try it online or verify all test cases.

The second program is pretty unimpressive, so I'll see if I can find a more original shorter approach.

**Explanation:**

```
Œ        # Get all substrings of the first (implicit) input-string
 ¢       # Count how many times each substring occurs in the second (implicit) input-string
  O      # Sum those counts together
         # (after which the result is output implicitly)

•K&}Í•   # Push compressed integer 388162079
 3ô      # Split it into parts of size 3: [338,162,079]
   ç     # Convert each to a character with this codepoint: ["Œ","¢","O"]
    J    # Join it to a string: "Œ¢O"
     .V  # Evaluate and execute as 05AB1E code (basically the program above)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•K&}Í•` is `388162079`.
> 7 votes

# Answer
# Jelly, 14 bytes, score 0

##### 6 bytes

```
ẆċⱮẆ}S

```

**Try it online!**

##### 8 bytes

```
⁼þŒD§RF§

```

**Try it online!**

### How?

```
ẆċⱮẆ}S - Link a, b:      e.g.  "tent", "spent"
Ẇ      - sublists (a)          ["t","e","n","t","te","en","nt","ten","ent","tent"]
   Ẇ}  - sublists (b)          ["s","p","e","n","t","sp","pe","en","nt","spe","pen","ent","spen","pent","spent"]
  Ɱ    - map with:
 ċ     -   (left) count occurrences (of right)
                               [0,0,1,1,2,0,0,1,1,0,0,1,0,0,0]
     S - sum                   7

⁼þŒD§RF§ - Link a, b:    e.g.  'tent', 'spent'
 þ       - table of:
⁼        -   equals?           [[0,0,0,0],[0,0,0,0],[0,1,0,0],[0,0,1,0],[1,0,0,1]]
  ŒD     - diagonals           [[0,0,0,0],[0,0,0],[0,0],[0],[1],[0,0],[0,0,0],[0,1,1,1]]
    §    - sums                [0,0,0,0,1,0,0,3]
     R   - range               [[],[],[],[],[1],[],[],[1,2,3]]
      F  - flatten             [1,1,2,3]
       § - sums                7

```
> 6 votes

# Answer
# Java 8, score 0 (~~1287~~ ~~1263~~ ~~1248~~ 1243 bytes)

**Function 1 (~~261~~ ~~237~~ ~~234~~ 229 bytes):**

```
a->b->{int l=a.length,z=l-l,r=z,i=z,j,L=b.length,I,J,x;for(String s,t;i<l;i++)for(j=i;j++<l;)for(I=z;I<L;I++)for(J=I;J++<L;r+=s.contains(t)&j-i==J-I?1:0){for(s=t="",x=i;x<j;)s+=a[x++];for(x=I;x<J;)t+=b[x++];}System.err.print(r);}

```

Inputs as character-arrays. Outputs the result to STDERR.

-3 bytes thanks to *@ceilingcat*
-5 bytes thanks to *@l4m2*

Try it online.

**Function 2 (~~1026~~ 1014 bytes):**

```
\u0061\u002D\u003E\u0062\u002D\u003E\u007B\u0069\u006E\u0074\u0020\u0072\u003D\u0030\u002C\u006C\u003D\u0061\u002E\u006C\u0065\u006E\u0067\u0074\u0068\u0028\u0029\u002C\u0069\u003D\u0030\u002C\u006A\u002C\u004C\u003D\u0062\u002E\u006C\u0065\u006E\u0067\u0074\u0068\u0028\u0029\u002C\u0049\u002C\u004A\u003B\u0066\u006F\u0072\u0028\u003B\u0069\u003C\u006C\u003B\u0069\u002B\u002B\u0029\u0066\u006F\u0072\u0028\u006A\u003D\u0069\u003B\u006A\u002B\u002B\u003C\u006C\u003B\u0029\u0066\u006F\u0072\u0028\u0049\u003D\u0030\u003B\u0049\u003C\u004C\u003B\u0049\u002B\u002B\u0029\u0066\u006F\u0072\u0028\u004A\u003D\u0049\u003B\u004A\u002B\u002B\u003C\u004C\u003B\u0029\u0069\u0066\u0028\u0061\u002E\u0073\u0075\u0062\u0073\u0074\u0072\u0069\u006E\u0067\u0028\u0069\u002C\u006A\u0029\u002E\u0065\u0071\u0075\u0061\u006C\u0073\u0028\u0062\u002E\u0073\u0075\u0062\u0073\u0074\u0072\u0069\u006E\u0067\u0028\u0049\u002C\u004A\u0029\u0029\u0029\u0072\u002B\u002B\u003B\u0072\u0065\u0074\u0075\u0072\u006E\u0020\u0072\u003B\u007D

```

Inputs as Strings. Returns the integer-result.

-12 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

The golfed function is this:

```
a->b->{int r=0,l=a.length(),i=0,j,L=b.length(),I,J;for(;i<l;i++)for(j=i;j++<l;)for(I=0;I<L;I++)for(J=I;J++<L;)if(a.substring(i,j).equals(b.substring(I,J)))r++;return r;}

```

This golfed version is also the direct translation of the second function above using a simple converter.

In order to use the unicode escaped Java function, we'll have to prevent using the characters `\u0123456789ABCDEF` in the other function. We're currently using three `0` and four `u`:

* To get rid of the three `0`, I've added an additional `z=l-l` integer to reuse;
* To get rid of the two `u` in `substring`, I create the substrings manually using `,x ... String s,t; ... for(s=t="",x=i;x<j;)s+=a.split("")[x++];for(x=I;x<J;)t+=b.split("")[x++];` (minor note: I couldn't use `.charAt(x++)` instead of `.split("")[x++]` here, since it contains an `A`);
* To get rid of the `u` in `equals`, I've used `s.contains(t)&j-i==J-I`;
* And to get rid of the `u` in `return`, I've printed to STDERR with `System.err.print(r);`.

After that, both `.split("")` were removed and both `.length()` were golfed to `.length` by taking the arguments as character-arrays instead of Strings.

*Explanation of the golfed base function:*

```
a->b->{                       // Method with two string arguments
  int r=0,                    //  Result-count integer, starting at 0
      l=a.length(),           //  Length of the first input-String
      i=0,j,                  //  Index-integers for the substrings of the first input
      L=b.length(),           //  Length of the second input-String
      I,J;                    //  Index-integers for the substrings of the second input
  for(;i<l;i++)               //  Loop `i` in the range [0,l):
    for(j=i;j++<l;)           //   Inner loop `j` in the range (i,l]:
      for(I=0;I<L;I++)        //    Inner loop `I` in the range [0,L):
        for(J=I;J++<L;)       //     Inner loop `J` in the range (J,L]:
          if(a.substring(i,j) //      If the [i,j)-substring of the first input
             .equals(b.substring(I,J)))
                              //      equals the [I,J)-substring of the second:
            r++;              //       Increase the result-count by 1
  return r;}                  //  After the loops, return the result

```
> 5 votes

# Answer
# Stax, score 0 (23 bytes)

### 12 bytes

```
:e{n:es|#m|+
:e              all substrings of b
  {      m      map over them:
   n:e            all substrings of a
      s|#         count occurrences
          |+    sum

```

Run and debug it at staxlang.xyz!

### 11 bytes

```
ü╪ ·§╢┌Æ=gy

```

Run and debug it at staxlang.xyz!

The second is the same as the first, but with a `$` (number to string) appended before packing to get rid of a pesky `m` that was trying to give me a positive score.
> 4 votes

# Answer
# Vyxal, 21 bytes, Score = 0

Program 1 (14 bytes):

```
wJƛfÞS;Π'÷⁼;żt

```

Try it Online!

Program 2 (7 bytes):

```
ǎ$ǎẊ~≈L

```

Try it Online!

I'm very good at golfing language design as you can tell by the fact that there's multiple built-ins to do the same thing.

Both programs take 2 strings.

## Explained

```
wJƛfÞS;Π'÷⁼;żt
wJ             # Put the two inputs into a list
  ƛfÞS;        # Get the sublists of each - returns a list of lists
       Π       # Cartesian product of the two lists
        '÷⁼;   # Keep only those where all the items are equal
            żt # Length of list

```

```
ǎ$ǎẊ~≈L
ǎ       # Get the substrings of the first input
 $ǎ     # and of the second input - leaves two strings on the stack
   Ẋ    # Cartesian product of the two lists
    ~≈  # Keep only those where all the items are equal
      L # Length of list

```
> 3 votes

# Answer
# Python, ~~542~~ ~~533~~ 479

## A, 89 bytes

```
def g(a,b):h=range;return sum(b.count(a[c:][:1+d])for c in h(len(a))for d in h(len(a)-c))

```

## B, 80 bytes

```
lambda i,l:sum(l.count(i[j:k+1]) for j in range(len(i)) for k in range(j,len(i)))

```

Not really sure how to optimize this. Will play a bit more. Submitting the same program twice would give me a score of 3,160 bytes.
> 3 votes

# Answer
# Haskell, ~~67~~, ~~58~~, 57 score

```
a((f,j):q)|(9>8)>(f>j)&&(9>8)>(j>f)=a(q)+1
a(f)=0
f!h=scanr(+)0(((a.).zip)<$>scanr(:)[]f<*>scanr(:)[]h)!!0

```

```
x%y|t:u<-x,w:e<-y,t==w=1:u%e;_%_=mempty;k t|_:m<-t=t:k m;k _=mempty;t?u= sum$do{x<-k t;e<-k u;x%e}

```

Attempt This Online!

~~I really wanted to get this under 64. But it just seems like it is not going to happen.~~ Got it under 64!

The characters that cause overlap are:

```
,|1=p$<s:

```
> 3 votes

# Answer
# Charcoal, 56 bytes, score = 0

First program, 31 bytes:

```
ＩΣＥθΣＥ⊕κ№ＥηΦη№…ξ⁻⊕κ⁻λξρΦθ№…λ⊕κξ

```

Try it online! Link is to verbose version of code. Explanation: Generates all substrings of the first input in order of last character index followed by first character index, for each substring extracts all substrings of that length from the second input, counts the number of matches, then takes the grand total.

```
   θ                            First input
  Ｅ                             Map over characters
       κ                        Current index
      ⊕                         Incremented
     Ｅ                          Map over implicit range
          η                     Second input
         Ｅ                      Map over characters
            η                   Second input
           Φ                    Filtered where
              …                 Range from
               ξ                Inner index to
                     ξ          Inner index
                   ⁻            Subtracted from
                    λ           Outer value
                ⁻               Subtracted from
                  κ             Outermost index
                 ⊕              Incremented
             №                  Contains
                      ρ         Innermost index
        №                       Count matches of
                        θ       First input
                       Φ        Filtered where
                          …     Range from
                           λ    Inner value to
                             κ  Outer index
                            ⊕   Incremented
                         №      Contains
                              ξ Innermost index
    Σ                           Take the sum
 Σ                              Take the sum
Ｉ                               Cast to string
                                Implicitly print

```

Second program, 25 bytes:

```
ＳζＳε⭆ψＬ⭆ζ⭆⁺¹μ⭆⌕Ａε✂ζν⁺¹μ¹ψ

```

Try it online! Link is to verbose version of code. Explanation: Generates all substrings of the first input as before, then maps the indices of overlapping matches in the second input to null bytes, concatenates everything and takes the total length.

```
Ｓζ                          Rename first input
  Ｓε                        Rename second input
     ψ                      Null byte
    ⭆                       Map over characters and join
        ζ                   First input
       ⭆                    Map over characters and join
            μ               Current index
          ⁺                 Plus
           ¹                Literal integer `1`
         ⭆                  Map over implicit range and join
                ε           Second input
              ⌕Ａ            Find all matching indices of
                  ζ         First input
                 ✂    ¹     Sliced from
                   ν        Inner value to
                      μ     Outer index
                    ⁺       Plus
                     ¹      Literal integer `1`
             ⭆              Map over indices and join
                        ψ   Null byte
      Ｌ                     Take the length
                            Implicitly print

```

Using `StringMap` to stringify the count has the added bonus of renaming the loop variables thereby reducing the number of shared substrings. Other techniques I used:

* The second program uses `StringMap` instead of `Map`. I can do this by representing integers in unary as the length of the resulting string.
* The second program uses `Plus(1, k)` instead of `Incremented(k)`, as it needs a `1` for `Slice()` anyway.
* The first program uses `Minus(Incremented(k), Minus(l, x))` to avoid having to add `k` and `x` (because the second program is now using `Plus`).
* The first program uses `Filter` to extract substrings to avoid using `Slice`.
> 3 votes

# Answer
# Go, 265 bytes, score 772

thanks golang for not giving you that many ways of doing things (reasonably)

## A, 113 bytes

```
import."strings"
func f(v,b string)(z int){for i:= range v{for j:=i+1;j<= len(v);j++{z+=Count(b,v[i:j])}}
return}

```

Attempt This Online!

## B, 152 bytes

```
import."regexp"
func g(x,y[]byte)(q int){for w:=range x{for p:=1+w;p<=len(x);p++{q=len(MustCompile(QuoteMeta(string(x[w:p]))).FindAll(y,-1))+q}}
return}

```

Attempt This Online!

## Changelog

* A/B: Some changes (@Kevin Cruijssen)
* (footers): Make sure they use the same inputs (@Grain Ghost)
> 2 votes

# Answer
# Brachylog, Score: 0 (15 + 38 = 53 bytes)

```
tT⁰&hsᶠ{∋~sT⁰}ᶜ

```

Try it online!

```
↰₁ᵐẋ=ˢl
↰₂ᵇbᵐ²
l⟦₁;?zZ∧[A,.,C]cZ∧.l>0∧

```

Try it online!

Program 1 with programs as input.

Program 2 with programs as input

## Explanation

Brachylog doesn't actually have that many built-ins; in addition, certain control flow symbols are used all the time. This makes it harder to write 2 programs that don't share symbols, which means we have to do some plumbing for the second program.

The main difficulty is that the direct way to generate substrings of consecutive elements is `s`, and getting substrings with another method that also doesn't generate duplicates (but works for strings with duplicate symbols!) is not that obvious.

### Program 1

This is a fairly straightforward declarative implementation of the problem:

```
tT⁰                Call the second input T⁰
   &hsᶠ            Find all subsequences of consecutive elements of the first input
       {     }ᶜ    Count:
        ∋~sT⁰        The number of such subsequences which are also subsequences of T⁰

```

### Program 2

We use a more imperative approach, computing all subsequences of consecutive elements and checking how many equal couples we get after cartesian product.

We can't use brackets to declare predicates, so we have to declare them using linebreaks. Predicate 3 computes the subsequences. Predicate 2 cleans up some plumbing set up in Predicate 3 to avoid duplicate subsequences.

We can't use `ᶠ - findall` to generate stuff, so we use `ᵇ - bagof` which does the same in cases where we're not generating unbounded variables.

```
                          - Predicate 0
↰₁ᵐ                       Map predicate 1 on each of the 2 inputs
   ẋ                      Cartesian product
    =ˢ                    Select the couples of equal elements
      l                   Output the length of this list

                          - Predicate 1
↰₂ᵇ                       Find all outputs of Predicate 2
   bᵐ²                    Remove the indices

                          - Predicate 2
l⟦₁;?zZ                   Zip the string with indices [1,...,N]; call it Z
       ∧[A,.,C]cZ∧       [A, Output, C] concatenates into Z
                          We avoid duplicate situations with the zipped indices
                   .l>0∧  This Output has length > 0
                          This avoids all cases where the output is the empty string

```
> 1 votes

# Answer
# JavaScript (Node.js), score 0, 322 bytes

# JavaScript (Node.js), 129 bytes

```
x=>y=>[g=_=>j--?[h=_=>j%z-v-z?x[j%z-v]==y[j/z-v|0]?--v|--Z|h``:0:0][v=0][h``]|g``:-Z][Z=0][j=y[l='l\x65\x6Eg\x74h']*[z=x[l]]]|g``

```

Try it online!

# JavaScript (Node.js), 193 bytes

```
function(A,B){return A.reduce(function(M,K,I){return B.reduce(function(M,L,N){return A.reduce(function(M,K,J){return(I<++J)*Array(A.slice(I,J)+1).includes(B.slice(N,J+~I+1+N)+1)+M},M)},M)},!1)}

```

Try it online!
> 1 votes

---
Tags: subsequence, self-scoring
---


title: Rock Paper Scissors

text:
# Question
Title: Rock Paper Scissors
Implement the classic rock paper scissors.

Conditions:

* user will input 'r', 'p' or 's'
* program will output 'r', 'p' or 's' and the result
* program choice ('r', 'p' or 's') has to be pseudo random (**I'm looking at you Howard**)
* result can be represented with any printable character, there should always be three possible results for what the user has input (the user wins, lose or is a tie).
* what happens if the user inputs nothing, or something different that 'r', 'p' or 's' should be not important.

You need to:

* Provide the golfed code.
* The ungolfed code
* How do you invoke the program
* A sample run

**I will choose the answer with less characters, if a tie presents the most up voted answer will be chosen.**

Good golfing and may luck be ever in your favor.

I will be posting an answer my self, in Java.

For the ones that live in a mountain under a rock:

> r = rock
>
> p = paper
>
> s = scissors
>
> rock: wins to scissors, loses with paper, a tie with rock.
>
> paper: wins to rock, loses with scissors, a tie with paper.
>
> scissors: wins to paper, loses with rock, a tie with scissors.

Current Positions:

* UN: Username
* PL: Programming Language
* CC: Character Count
* UV: Up votes

> ```
> ╔══════════════════╦════════════╦══════╦════╗
> ║        UN        ║     PL     ║  CC  ║ UV ║
> ╠══════════════════╬════════════╬══════╬════╣
> ║ Howard           ║ GolfScript ║    6 ║ 15 ║
> ║ primo            ║ Perl       ║   27 ║  7 ║
> ║ TwiNight         ║ APL        ║   31 ║  4 ║
> ║ primo            ║ Perl       ║   33 ║  7 ║
> ║ marinus          ║ APL        ║   36 ║  5 ║
> ║ primo            ║ Perl       ║   38 ║  7 ║
> ║ primo            ║ Perl       ║   48 ║  7 ║
> ║ yehuda-schwartz  ║ javascript ║   49 ║  1 ║
> ║ manatwork        ║ Ruby       ║   54 ║ 13 ║
> ║ w0lf             ║ GolfScript ║   62 ║  4 ║
> ║ tmartin          ║ K          ║   67 ║  2 ║
> ║ Abhijit          ║ Python 3   ║   74 ║  5 ║
> ║ beary605         ║ Python 3   ║   76 ║  4 ║
> ║ rlemon           ║ javascript ║   85 ║  4 ║
> ║ ugoren           ║ C          ║   86 ║  3 ║
> ║ Egor Skriptunoff ║ LUA        ║   87 ║  4 ║
> ║ Fors             ║ Befunge    ║  107 ║  3 ║
> ║ Vi.              ║ Clojure    ║  129 ║  1 ║
> ║ Henrik           ║ C#         ║  167 ║  4 ║
> ║ dystroy          ║ Go         ║  169 ║  1 ║
> ║ primo            ║ ferNANDo   ║  259 ║  5 ║
> ║ anakata          ║ Java       ║  259 ║  1 ║
> ║ epoch            ║ Java       ║  387 ║  1 ║
> ║ jdstankosky      ║ LOLCODE    ║ 1397 ║ 15 ║
> ╚══════════════════╩════════════╩══════╩════╝
>
> ```

I can't select Howards answer, since it was a (successful) attempt to bend the rules, but I change them, to make them extra explicit.

primo 27 character answer can't be selected because it's not pseudo random per se

primo -p answer, I'm gonna go with "-p would be counted as 3 bytes: one for the -, one for the p, and one more the necessary whitespace."

**Thanks to all who answered, I hope you have had a good time!**

***NOTE: I will be trying to edit this every other week, to adjust the table, and change my selected answer if someone beats the current one, so If you just got here, post your answer if you want!***

# Answer
> 10 votes
## APL, 31

```
'TWL'[1+3|-/x⍳⎕←⍞,(?3)⌷x←'rps']

```

`x←'rps'` Assign string `'rps'` to `x`

`(?3)⌷` Choose random integer 1~3, choose that index of `x`

`⍞,` Prepend user input to machine choice

`⎕←` Output resulting string

`x⍳` Convert to numerical array by indexOf in `x`

`-/` Difference of the two numbers

`1+|3` Modulus 3 and plus 1

`'TWL'[...]` indexing from `'TWL'`

**Sample**

```
r
rp
L

```

User choose rock, program choose paper: Lose

# Answer
> 43 votes
# LOLCODE, 1397

***Note:** I submitted this before I noticed the winning requirement was changed from popularity with golf tie-break to golf with popularity tie-break.*

There's not really any strict syntax, but I'm sure this is acceptable.

```
HAI
    I HAS A CRAZY, LUCKY, CHALLENGE, TREAT
    I HAS YUMMY ITZ "LOL U LOZED"
    I HAS MEH ITZ "NOWAI TIED"
    I HAS GROSS ITZ "OMG U WONNED"
    I HAS BURNT ITZ "LAME"
    GIMMEH CHALLENGE
    BTW I HOPE I R TEH WINZ
    LOL CRAZY IZ BETWEEN 1 AN 3
    I HAS A SUPA ITZ A BUKKIT
    LOL SUPA'Z 1 R "ROCK"
    LOL SUPA'Z 2 R "PAPER"
    LOL SUPA'Z 3 R "SCIZZORS"
    LOL LUCKY R SUPA'Z CRAZY
    GOT CHALLENGE, WTF?
        OMG "Rock"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R MEH, GTFO
                OMG PAPER, LOL TREAT R YUMMY, GTFO
                OMG SCIZZORS, LOL TREAT R GROSS, GTFO
            OIC
        OMG "Paper"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R GROSS, GTFO
                OMG PAPER, LOL TREAT R MEH, GTFO
                OMG SCIZZORS, LOL TREAT R YUMMY, GTFO
            OIC
        OMG "Scissors"
            GOT LUCKY, WTF?
                OMG ROCK, LOL TREAT R YUMMY, GTFO
                OMG PAPER, LOL TREAT R GROSS, GTFO
                OMG SCIZZORS, LOL TREAT R MEH, GTFO
            OIC
        OMGWTF
            VISIBLE "WHAT U SAYZ?", LOL TREAT R BURNT
            GTFO
    OIC
        BOTH SAEM TREAT AN BURNT, O RLY?
            YARLY
                VISIBLE "YOU BURNTED MAH TREAT!"
            NOWAI
                VISIBLE SMOOSH "I GUESSED " AN LUCKY
                VISIBLE TREAT
        KTHX
KTHXBAI

```

If this were to be successfully executed as `RockPaperScissors.LOL`, here's what some possible random outcomes could be:

* Input: `Rock` \- Output: `I GUESSED SCIZZORS U WONNED`
* Input: `Paper` \- Output: `I GUESSED PAPER NOWAI TIED`
* Input: `Scissors` \- Output: `I GUESSED ROCK LOL U LOZED`
* Input: `Tuna` \- Output: `WHAT U SAYZ? YOU BURNTED MAH TREAT!`

# Answer
> 26 votes
### GolfScript

```
n"Draw"

```

Above code implements the required functionality. Additionally, it ensures that the player will never be left angry because of a (perceived) unfairness of computer's strategy.

**Ungolfed version**

```
n"Draw"

```

**How to invoke the program**

The input (a single character of 'r', 'p', 's') has to be provided on STDIN, possibly terminated with newline.

**A sample run**

```
> echo r | ruby golfscript.rb rockpaperscissors.gsc
r
Draw

```

**Explanation of the code**

For all those not familiar with GolfScript I'll add an detailed explanation of how this code works. The code essentially exists of three parts.

```
### Computer's strategy ###
# The strategy used to play r/p/s.
# The computer is so fast, it can really guess in an instance
# what the player has played. Since the computer should
# not play unfair, the best strategy is to always go for a
# draw and choose the same move.
        # on the stack is player's move
        # choose to play the same -> now the computer's move is on the stack

### Fiddle with input ###
# The input may of may not be delimited by newline.
# In order to make the output readable, we'll give
# a newline here.
n       # Push a newline onto the stack

### Give the result ###
# We can skip a complicated calculation of the result
# since we chose to play draw anyways.
"Draw"  # Push the result onto the stack

# Output is printed automatically when GolfScript code terminates.

```

**Notes**

Since this is not code-golf but popularity contest I didn't choose the shortest version. Maybe in case of a tie a shorter code will knock out my solution. Nevertheless, for those interested in golfing, the following possibilities are given:

* Deal only with proper input and force user to provide a newline. This will save one character.
* The rules have a small insufficiency which allows to save another character by bending the rules. The result can always be printed as "Win" - it was not specified that the correct result has to be printed. But note that players will soon get angry if you choose to implement a cheating program.
* The output format is not well specified. We can choose `0` as output for draw. Thus, the shortest valid program is the single-character code `0`.

# Answer
> 20 votes
# Ruby: ~~61~~ 54 characters

```
o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]

```

Somehow explained:

The entire problem is reduced to calculating the following results:

```
  ╲ machine
h  ╲| 0 1 2
u ──┼──────
m 0 │ 0 1 2
a 1 │ 2 0 1
n 2 │ 1 2 0

```

Where the numbers mean:

* choice: 0 rock, 1 paper, 2 scissor
* result: 0 draw, 1 win, 2 lose

For this I used the formula: machine\_choice - human\_choice. This occasionally results negative value, but as it is only used as index and negative index is counted backward, will pick the correct array element.

```
# ┌── choosable object type
# │           ┌── machine's choice numeric code
# │           │                  ┌── result type
# │           │                  │                   ┌── human's choice
# │           │          ┌───────┴───────┐           │
  o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]
#           └─────┬────┘                   └─────┬────┘
#                 └── machine's choice letter    │
#                                                └── result numeric code

```

Used methods (others then `Fixnum`'s obvious ones):

Ungolfed:

```
object_type = "rps";
result_type = %w{Draw Win Lose}

machine_choice = rand(3)
human_choice = $_

p object_type[machine_choice]

result_code = machine_choice - object_type.index(human_choice)
p result_type[result_code]

```

Sample run:

```
bash-4.2$ ruby -nle 'o="rps";p o[c=rand(3)],%w{Draw Win Lose}[c.-o.index$_]'
r
"p"
"Win"
p
"p"
"Draw"
s
"p"
"Lose"

```

# Answer
> 9 votes
## Perl 48 bytes

```
$%=rand 3;print"$%
"^B,(Draw,Lose,Win)[$%-=<>^B]

```

The script prints the result from the computer's perspective, for example if the player chooses `r` and the computer chooses `s`, the result is `Lose`. `$%` (format page number) is used to store the computer's move, as it may only contain an integer value, which saves an int cast.

Ungolfed:

```
# choose a random move index 0, 1, or 2
$cindex = int(rand 3);
# convert this index to a move
# 0 => r, 1 => s, 2 => p
$cmove = "$cindex" ^ B;

# read the player's move
$pmove = <>;
# convert this move to its index
$pindex = $pmove ^ B;

# print computer's move
print $cmove, $/;
# compare indices, and output result
@result = (Draw, Lose, Win);
print $result[$cindex - $pindex];

```

Sample usage:

```
$ echo p | perl rps.pl
s
Win

$ echo r | perl rps.pl
r
Draw

$ echo s | perl rps.pl
p
Lose

```

The script may also be run interactively, by typing your move followed by `Enter`:

```
$ perl rps.pl
r
s
Lose

```

---

## Rule Stretching

### Perl 35 +3 bytes

```
$_=($%=rand 3).(D,L,W)[$%-($_^B)]^B

```

Requires the `-p` command line switch (counted as 3 bytes). Each of the outcomes `Win`, `Lose` and `Draw` have been mapped to `W`, `L`, `D`. The newline between the computer's choice and the result has been excluded.

Sample usage:

```
$ echo r | perl -p rps.pl
sL

```

---

### Perl 30 +3 bytes

```
$_=($%=rand 3).($%-($_^B))%3^B

```

Once again requires `-p`. Here `Win`, `Lose` and `Draw` have been mapped to `2`, `1` and `0` respectively. This is still technically compliant, as they are printable characters.

Sample usage:

```
$ echo r | perl -p rps.pl
s1

```

---

### Perl 24 +3 bytes

```
$_=$^T%3 .($^T-($_^B))%3^B

```

Requires `-p`, WLD mapped to `2`, `1`, `0` as before. Each `^T` should be replaced with a literal ascii character 20. This one is admittedly a bit of a stretch; `$^T` returns the number of seconds since epoch from when the script was started. All outcomes are possible, but it doesn't quite qualify as pseudo-random.

Sample usage:

```
$ echo r | perl -p rps.pl
s1

```

# Answer
> 9 votes
## C# (167 characters)

My very first try at golfing.

**Golfed**

`using System;class P{static void Main(string[] i){var m="rspr";var a=m[Environment.TickCount%3];Console.WriteLine(a+" "+(i[0][0]==a?"T":m.Contains(i[0]+a)?"W":"L"));}}`

**Un-golfed**

```
using System;

class P
{
    static void Main(string[] i)
    {
        var m = "rspr";
        var a = m[Environment.TickCount % 3];
        Console.WriteLine(a + " " + (i[0][0] == a ? "T" : m.Contains(i[0] + a) ? "W" : "L"));
    }
}

```

**Sample Run** The app requires single char inputs as argument 1 to the application, either `r`, `s` or `p`.

```
cmd > app.exe r

```

**All possible outcomes**

* `cmd > app.exe r` gives output `r T` (rock, tie)
* `cmd > app.exe r` gives output `p L` (paper, lost)
* `cmd > app.exe r` gives output `s W` (scissors, win)
* `cmd > app.exe p` gives output `r W` (rock, win)
* `cmd > app.exe p` gives output `p T` (paper, tie)
* `cmd > app.exe p` gives output `s L` (scissors, lost)
* `cmd > app.exe s` gives output `r L` (rock, lost)
* `cmd > app.exe s` gives output `p W` (paper, win)
* `cmd > app.exe s` gives output `s T` (scissors, tie)

# Answer
> 7 votes
## APL (~~38~~ 36)

```
c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]

```

Outputs 'T', 'W' and 'L' for tie, win and lose.

Sample run:

```
      c[i],(⌽↑⌽∘'TWL'¨⍳3)[⍞⍳⍨c←'rps';i←?3]
p
rW

```

(User types 'p' for paper. Computer chooses 'r' (rock), user wins)

Explanation:

* `⌽↑⌽∘'TWL'¨⍳3`: generates the following matrix:

```
TLW
WTL
LWT

```
* `⍞⍳⍨c←'rps'`: set `c` to the string `'rps'`, read user input and get the index of the user input in the string (this will be a value from 1 to 3). This index is used as the Y coordinate into the matrix.
* `i←?3`: get a random number from 1 to 3 and store it in `i`, this is the computer's choice. This is used as the X coordinate into the matrix.
* `c[i]`: use `i` as an index into `c`, displaying the computer's choice as 'r', 'p', or 's'.

# Answer
> 6 votes
## ferNANDo 1184 (259 golfed) bytes

*An interpreter written in Python can be found at the bottom of the linked page.*

ferNANDo is a esoteric language which supports only one variable type, boolean, and only one operation, NAND. As you might imagine, this can lead to some fairly long logic to accomplish seemingly simple tasks. It has support for reading from stdin (one byte at a time), writing to stdout (also one byte at a time), conditional loops, and also a random boolean generator.

There are no keywords whatsoever; everything is a variable. A statement's function is determined solely by the number of variables it contains. There are also no comments, so I've done my best to make the code self-commenting. The last four lines might be a bit confusing, but it will probably suffice to say that it prints `Win!`, `Lose`, or `Draw` depending on the outcome.

```
not sure, but right now i'm guessing you're_not_paper you're_scissors
you're_paper not you're_not_paper
you're_not_scissors not you're_scissors
you're_rock you're_not_paper you're_not_scissors
you're_rock you're_rock

o_shi-
i'm_not_paper right ?
i'm_scissors right ?
i'm_paper not i'm_not_paper
i'm_not_scissors not i'm_scissors
o_shi- i'm_paper i'm_scissors
o_shi- o_shi-
o_shi-
i'm_rock i'm_not_paper i'm_not_scissors
i'm_rock i'm_rock

print right now but only if i'm_not_paper i'm_scissors
print a newline here, not more, not less

i_win_if i'm_scissors you're_paper
or_if i'm_rock you're_scissors
or_even_if i'm_paper you're_rock

i_win i_win_if or_if
i_win i_win
i_win or_even_if

i_lose_if i'm_paper you're_scissors
or_if i'm_scissors you're_rock
or_even_if i'm_rock you're_paper

i_lose i_lose_if or_if
i_lose i_lose
i_lose or_even_if

i_don't_win not i_win
i_don't_lose not i_lose
we_tie i_don't_win i_don't_lose
we_tie we_tie
we_don't_tie not we_tie

print now if i_win i_lose not i_win i_win
print but not we_tie we_don't_tie i_lose i_don't_win we_don't_tie
print right now i_lose i_win i_win we_don't_tie i_don't_win
print i_don't_win but we_tie or i_don't_win we_tie now

```

The script can be run interactively, by typing your move followed by `Enter`.

Sample usage (assuming you've named the interpreter `nand.py`):

```
$ python nand.py rps.nand
p
s
Win!

$ python nand.py rps.nand
r
r
Draw

$ python nand.py rps.nand
s
p
Lose

```

---

**Edit:** Just to prove that ferNANDo can compete with Java, here's a 'golfed' version at **259 bytes**. The logic is sightly different; it checks `not win` and `not tie`, which saves a few NAND gates (because then I only need the `not` versions of the player's moves, and because `not lose` wasn't required for the output). Not nearly as interesting to read, though.

```
1 _ _ _ _ _ _ A b
B 1 b
C A B
o
P 1 ?
s 1 ?
p 1 P
S 1 s
o p s
o o
o
r P S
r r
0 1 1 1 0 0 P s
0 0 0 0 1 0 1 0
t s A
u r B
v p C
W t u
W W
W v
t p A
u s B
v r C
D t u
D D
D v
w 1 W
d 1 D
l W D
l l
0 1 0 w l 1 w w
0 1 1 d D l W D
0 1 1 l w w D W
0 W 1 d 0 W d 1

```

# Answer
> 6 votes
# Python 3, 55 bytes

```
q={*'rps'}.pop()
print(q,'rrppssrpsr'.count(q+input()))

```

Try it online!

With the release of Python 3.3 came default hash randomization. As such, we can use the `set.pop` method to get a random character from the string `'rps'`.

The program appends the input character to the randomly generated character and counts how often the combination appears in the string `'rrppssrpsr'`.

Outputs `0` for program win, `1` for tie and `2` for player win.

# Answer
> 5 votes
**Python 3.x: 74 Characters**

```
import time
A,f="psr",time.gmtime()[5]%3
print(A[(A.find(input())+f)%3],f)

```

How it works

```
Before Machine Proceeds it determines the outcome of the game and based
on the outcome, it determines the choice which would result in the outcome
viz Human's choice

\     Outcome
 \    0  1  2
  \_____________
H  |
U 0|  0  1  2
M 1|  1  2  0
A 2|  2  0  1
N  |

Where Choices are represented as
0 --> Paper
1 --> Scissor
2 --> Rock

Outcome (From Computer's Perspective)
0 --> Draw
1 --> Win
2 --> Fail

Given the sequence of choices as a string
"psr"
So its easy to see, if computer needs to win, it needs to choose the character
next to what human chooses.
If computer needs to loose, it needs to choose the previous character to what
human chooses

MACHINE's|      CHOICES    |  Formulation
FATE     |-----------------|  For Machine's
         |  P     S      R |  Choice
---------|-----------------|-----------------------------
WIN(1)   |        H ---> M | (CHOICE+1) % 3 = (CHOICE+WIN)%3
---------|-----------------|-----------------------------
LOSS(2)  |  M     H -----\ | (CHOICE+2)%3   = (CHOICE+LOSS)%3
         |  ^            | |
         |  |____________| |
---------|-----------------|------------------------------
DRAW(0)  |        H        | (CHOICE+0)%3   = (CHOICE+DRAW)%3
         |        M        |
---------|-----------------|

Combining all the above we have

MACHINE's CHOICE = (HUMAN CHOICE + MACHINE's FATE) % 3

```

Based on the fate, it determines what should it's choice be based on the formula

```
result = (User_choice + machines_fate) % no_of_choices

machine_choice = "psr"[result]

```

Un-golfed Version

```
import time
choices = "psr"
#time.gmtime() returns the time structure in gmt
#time.gmtime()[5] is the current second tick
fate = time.gmtime()[5]%3
user_choice = input()
result = (choices.find(user_choice)+fate)%len(choices)
machine_choice = choices[result]
print(machine_choice, fate)

```

Sample run

```
D:\temp\rivalry>rps.py
r
r 0

D:\temp\rivalry>rps.py
r
p 1

D:\temp\rivalry>rps.py
p
r 2

D:\temp\rivalry>rps.py
p
r 2

D:\temp\rivalry>rps.py
p
s 1

D:\temp\rivalry>rps.py
p
s 1

D:\temp\rivalry>rps.py
p
p 0

```

# Answer
> 4 votes
## Lua, 87

```
c,n=os.time()%3+1,'rps'print(n:sub(c,c),({'Draw','Win','Defeat'})[(n:find(...)-c)%3+1])

```

Usage:

```
$ lua rps.lua p
s   Defeat

```

Ungolfed:

```
names = 'rps'
comp_idx = os.time()%3 + 1                -- 1, 2 or 3 (depends on timer)
comp_move = names:sub(comp_idx, comp_idx) -- 'r', 'p' or 's'
user_move = ...                           -- input parameter: 'r', 'p' or 's'
user_idx = names:find(user_move)          -- 1, 2 or 3
delta_idx = (user_idx - comp_idx) % 3     -- 0, 1 or 2
all_results = {'Draw', 'Win', 'Defeat'}   -- [1]=='Draw', [2]=='Win', [3]=='Defeat'
game_result = all_results[delta_idx + 1]
print(comp_move, game_result)

```

# Answer
> 4 votes
## Python 2 (~~86~~ ~~84~~ ~~80~~ 78), Python 3 - 76 chars

0 - tie, 1 - lose, 2 - win

```
from random import*
a=raw_input()
b=choice('psr')
print(a!=b)+(b+a in'rpsr'),b

from random import*
a=input()
b=choice('psr')
print((a!=b)+(b+a in'rpsr'),b)

```

Ungolfed

```
from random import*
moves = 'psr'
inp   = raw_input()
comp  = choice(moves)
match = comp+inp
is_not_tie = inp!=comp
wins = 'r' + moves         #rpsr; rock beats scissors, scissors beats paper, paper beats rock
print is_not_tie + (match in wins), comp

```

How to run: `python file_name_here.py`

Problems:
Computer AI: 35 characters

# Answer
> 4 votes
## GolfScript 62

An alternative GolfScript solution, much more boring than Howard's :).

The program chooses a move randomly and displays the result from the perspective of the user.

### The Code

```
'rssppr'.[6rand=]''+:§@+..&,({?)§\'Lose''Win'if}{;;§'Draw'}if`

```

### Sample run

> \> echo s | ruby golfscript.rb rps.gs
>
> r"Lose"

### Online test

You can run the program and experiment with different inputs here: http://golfscript.apphb.com/?c=OydzJwoKJ3Jzc3BwcicuWzZyYW5kPV0nJys6wqdAKy4uJiwoez8pwqdcJ0xvc2UnJ1dpbidpZn17OzvCpydEcmF3J31pZmA%3D

Note, however, that the parameter (user move) that's usually passed in the command line is now added to the stack in the code itself (there's no way to provide "real" command line parameters in this online tool).

### "Ungolfed" version

I don't have any idea what *ungolfed* means when it comes to GolfScript, so I tried to add comments. Hopefully that will clarify how the code works and make it a bit more readable:

```
# initially, the input (user's move) is on the stack

'rssppr'                # push the string 'rsspr' on the stack...
.                       # ...twice.

[
    6rand               # get a pseudo-random integer in the [0-5] range
    =                   # use the random index to get
                        # a letter from the string above

]''+                    # workaroud to get the actual letter instead of the
                        # ASCII code

:§                      # assign the randomly chosen letter (computer's move)
                        # to a nice variable called "§"

@                       # rotates last 3 elements on the stack, bringing
                        # the user input in the uppermost position
                        # So, now we have: "rssppr" <computer_move> <user_move>
                        # on the stack

+                       # concatenate the two moves, so now we have a string
                        # that contains both (ex: "rs")

..                      # copy the move string twice
&                       # do a setwise AND to get the DISTINCT elements
,(                      # get the length of the resulting string and subtract 1
                        # (now we have 0 if the letters were equal and non-zero otherwise)

{                       # beginning of block to execute when the moves are different:

                        # now we have on the stack two strings:
                        #     - the string 'rssppr'
                        #     - the string containing the moves (ex: 'rs')

    ?                   # find the second string inside the first one,
                        # and get the index at which it occurs
                        # (or -1 if it does not)

    )                   # increment that number (we now get 0 if no occurrence, 1 otherwise)

    §                   # recall the § variable (so we display the computermove)
    \                   # rotate the uppermost two stack entries

    'Lose''Win'if       # if the move pair is found in the 'rssppr' string,
                        # then print 'Lose', otherwise print 'Win'
}

{                       # beginning of block to execute when the moves are identical:

    ;;                  # discard the latest two stack items (not needed in this case)
    §                   # display computer's move
    'Draw'              # display the text 'Draw'
}
if                      # if computer's and user's moves were NOT equal,
                        # execute the first block.
                        # if they were, execute the second block

`                       # put the last word in quotes to separate it from computer's move

```

# Answer
> 4 votes
## C, 92 86 chars

```
main(y){
    srand(time(0));
    y="rps"[rand()%3];
    printf("%c%c\n",y,"LWWTLLW"[getchar()-y+3]);
}

```

Prints the computer's choice, and the result from the user's point of view - W=you win, L=you lose, T=tie.
The simple formula `x-y`, given the ASCII values of the choices, gives 0 on draw (obviously) and a unique value in each other case.

# Answer
> 4 votes
First try without reviewing others.

golfed: 107 85 bytes

```
i=prompt(),c="rps"[new Date%3],w={r:"s",p:"r",s:"p"};alert(c+(i==w[c]?2:w[i]==c?1:3))

```

output is \[npc-choice\]\[1:win, 2:loss, 3:tie\]

ungolfed:

```
var input = prompt(),
    choices = ["r","p","s"],
    computer_choice = choices[Math.floor(Math.random() * 3)],
    outcomes = {'r':'s','p':'r','s':'p'},
    winner;

    if( input == outcomes[computer_choice] ) {
        winner = 'NPC';
    } else if ( computer_choice == outcomes[input] ) {
        winner = 'You';
    } else {
        winner = 'No one, it was a Tie!';
    }

    alert('Computer chose: ' + computer_choice + '\n' +
          'The winner is: ' + winner);

```

# Answer
> 4 votes
## PowerShell: 144 133 117 111 92 73

> **Changes from original:**
>
> * Completely re-wrote script after seeing Danko Durbic's three-player even or odd solution.
> * Changed $s to a single string instead of a character array.
> * Used IndexOf as a direct method on $s, instead of spelling out the .NET class & method.
> * Removed redundant `%3`s.
>
> All told, nearly cut the length in half from my original answer!

**Golfed code:**

```
$p=($s='rps').IndexOf((read-host));$s[($c=Random 3)];"TWLLTWWLT"[$p+$c*3]

```

Can be run straight from the console.

**Ungolfed, with comments:**

```
# Variable $p will store the player's selection as a ternary digit by finding its position in a string containing the possible choices.
$p=(
    # Possible choices will be stored in a variable, $s, for later reuse.
    $s='rps'
# Get the position of the player's choice from $s.
).IndexOf((read-host));

# Express the computer's choice by outputting the appropriate character from $s.
$s[(
    # Computer's choice will be stored as a ternary digit in $c.
    $c=Random 3
)];

# Outcome for the player will be chosen from a string of possible outcomes by looking up the decimal repesentation of a two-digit ternary number.
# The threes digit is represented by $c, ones digit by $p.
"TWLLTWWLT"[$p+$c*3]

# Variable cleanup - do not include in golfed code.
rv p,s,c

```

Some sample runs at the console:

# Answer
> 3 votes
**JAVA 259 :(**

```
class c {public static void main(String[]a){char y=a[0].charAt(0);char m="rps".charAt(new java.util.Random().nextInt(3));if(y==m)a[0]="T";else if((y=='r'&& m=='s')||(y=='s'&& m=='p')||(y=='p'&& m=='r'))a[0]="1";else a[0]="0";System.out.println(m+":"+a[0]);}}

```

Highly ungolfed code:

```
class c {
    public static void main(String[] a) {
        char y = a[0].charAt(0);
        char m = "rps".charAt(new java.util.Random().nextInt(3));
        if (y == m) {
            a[0] = "T";
        } else if ((y == 'r' && m == 's') || (y == 's' && m == 'p') || (y == 'p' && m == 'r')) {
            a[0] = "1";
        } else {
            a[0] = "0";
        }
        System.out.println(m + ":" + a[0]);
    }
}

```

Sample runs:

> C:\>java c r
>
> s:1
>
> C:\>java c p
>
> p:T
>
> C:\>java c s
>
> s:T

# Answer
> 3 votes
# Befunge: 107 characters

```
~v@,"w"<   <   <  <
v?v3.14159265@,"l"<
"""358979323846>3-|
rps26433832>:1+|
"""7950>:2+|
>>>:,-:|
28@,"t"<

```

Slightly clunky. It is shrinkable, the question is by how much.

# Answer
> 3 votes
## JavaScript (87)

Golfed:

```
o='LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)];alert(b+o)

```

Ungolfed:

```
var player = prompt(),
    computer = 'prs'[new Date%3], // Date mod 3 "pseudo-random"
    outcome = 'LDW'[2*(player+computer != 'ps'
                    & player < computer
                    | player + computer == 'sp') // convert boolean W/L outcome to int (0,2)
              +
              +(player == computer)]; // convert D outcome to int (0,1)
alert(computer + outcome);

```

You can simply paste the code in your browser's javascript console to run it.

If I'm allowed to print the result before printing the computer's selection **(83)**:

```
alert('LDW'[2*((a=prompt())+(b='prs'[new Date%3])!='ps'&a<b|a+b=='sp')+ +(a==b)]+b)

```

# Answer
> 3 votes
# Jelly, 13 bytes

```
“rps”ɓ3XṄ+i@ị

```

Try it online!

Decides and prints the outcome (3 for a tie, 2 for a win, 1 for a loss) *before* determining its own move, so the validity might be somewhat dubious.

```
“rps”            Set the left argument to "rps",
     ɓ           then start a dyadic link with reversed arguments:
      3X         choose 1, 2, or 3,
        Ṅ        print that number with a newline,
         +       add it to
          i@     the index of the left argument in the right argument,
            ị    and take the element of the right argument at that modular index.

```

Without going backwards:

# Jelly, 14 bytes

```
“rps”ðXṄ⁸i_i%3

```

Try it online!

0 for tie, 2 for win, 1 for loss.

```
“rps”             Set the left argument to "rps",
     ð            then start a dyadic link:
      X           choose a random element of the left argument,
       Ṅ          print it,
        ⁸i        find its index in the left argument,
          _       subtract
           i      the right argument's index in the left argument,
            %3    and mod 3.

```

# Answer
> 3 votes
## x86-64 machine code (Linux), 98 bytes

```
00000000  54 5d 31 c0 31 ff 48 8d  75 f0 6a 02 5a 0f 05 8a  |T]1.1.H.u.j.Z...|
00000010  5d f0 b8 3e 01 00 00 48  8d 7d f0 6a 01 5e 31 d2  |]..>...H.}.j.^1.|
00000020  0f 05 8a 45 f0 6a 03 59  48 f7 f1 8a 8a 58 00 00  |...E.j.YH....X..|
00000030  00 88 4d f0 28 cb 80 c3  03 8a 8b 5b 00 00 00 88  |..M.(......[....|
00000040  4d f1 6a 01 58 6a 01 5f  48 8d 75 f0 6a 02 5a 0f  |M.j.Xj._H.u.j.Z.|
00000050  05 6a 3c 58 31 ff 0f 05  72 70 73 6c 77 77 64 6c  |.j<X1...rpslwwdl|
00000060  6c 77                                             |lw|

```

Disassembly:

```
   0:   54                      push   rsp
   1:   5d                      pop    rbp ; Setup basic frame pointer
   2:   31 c0                   xor    eax,eax
   4:   31 ff                   xor    edi,edi
   6:   48 8d 75 f0             lea    rsi,[rbp-0x10]
   a:   6a 02                   push   0x2
   c:   5a                      pop    rdx
   d:   0f 05                   syscall ; Read 2 bytes from STDIN into RBP-0x10 (input char + newline)
   f:   8a 5d f0                mov    bl,BYTE PTR [rbp-0x10] ; Move input into BL
  12:   b8 3e 01 00 00          mov    eax,0x13e
  17:   48 8d 7d f0             lea    rdi,[rbp-0x10]
  1b:   6a 01                   push   0x1
  1d:   5e                      pop    rsi
  1e:   31 d2                   xor    edx,edx
  20:   0f 05                   syscall ; Get 1 random byte
  22:   8a 45 f0                mov    al,BYTE PTR [rbp-0x10]
  25:   6a 03                   push   0x3
  27:   59                      pop    rcx
  28:   48 f7 f1                div    rcx
  2b:   8a 8a 58 00 00 00       mov    cl,BYTE PTR [rdx+0x58]
  31:   88 4d f0                mov    BYTE PTR [rbp-0x10],cl ; Get random throw
  34:   28 cb                   sub    bl,cl
  36:   80 c3 03                add    bl,0x3
  39:   8a 8b 5b 00 00 00       mov    cl,BYTE PTR [rbx+0x5b]
  3f:   88 4d f1                mov    BYTE PTR [rbp-0xf],cl ; Decide win/lose/draw
  42:   6a 01                   push   0x1
  44:   58                      pop    rax
  45:   6a 01                   push   0x1
  47:   5f                      pop    rdi
  48:   48 8d 75 f0             lea    rsi,[rbp-0x10]
  4c:   6a 02                   push   0x2
  4e:   5a                      pop    rdx
  4f:   0f 05                   syscall ; Print 2 chars to STDOUT (the computer's throw (r/p/s) and the winner (w/l/d))
  51:   6a 3c                   push   0x3c
  53:   58                      pop    rax
  54:   31 ff                   xor    edi,edi
  56:   0f 05                   syscall ; Exit with return code 0
  58:   727073 6c7777646c6c77 (data)

```

Outputs 'w' for win, 'l' for lose, and 'd' for draw.

Example run:

```
$ ./rps
r
sw

```

User picked rock and computer picked scissors. User wins.

# Answer
> 2 votes
## K, 67

```
{-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}

```

Prints W,L,D for win/lose/draw.

Ungolfed:

```
rps:{[x]
    res:x,*1?"rps";        // join user input to random selection of r,p,s
    -1'f;                  // print the user input and the program selection to stdout
    wins:("pr";"rs";"sp"); // the universe of winning combinations
    losses:|:'wins;        // reverse each win to the get losses

    $[f in wins;
        "win";
    f in losses;
        "lose";
    "draw"]
    }

```

Or in Q, which is more readable:

```
rps:{[x]
    res:x,rand["rps"];        // join user input to random selection of r,p,s
    -1 each f;                // print the user input and the program selection to stdout
    wins:("pr";"rs";"sp");    // the universe of winning combinations
    losses:reverse each wins; // reverse each win to the get losses

    $[f in wins;
        "win";
    f in losses;
        "lose";
    "draw"]
    }

```

Sample Run:

```
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"r"
r
s
"W"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"s"
s
s
"D"
k){-1'f:x,*1?"rps";$[f in b:("pr";"rs";"sp");"W";f in|:'b;"L";"D"]}"p"
p
s
"L"

```

# Answer
> 2 votes
## Javascript, 117 characters

Here's a data-driven approach to the problem. This can probably be optimized by generating the win/lose/draw data instead of mapping it manually, but it's a start :)

Golfed:

```
alert((r=[{v:"r",r:d="D",p:w="W",s:l="L"},{v:"p",r:l,p:d,s:w},{v:"s",r:w,p:l,s:d}][Math.random()*3|0]).v+r[prompt()])

```

Ungolfed:

```
//Output the result to the user
alert(
    (
        //Store the random computer outcome data
        randomRPSData =
            //Create the data for if the computer chooses r, p, or s
            [
                {
                    value: "r",
                    r: (d = "Draw"),
                    p: (w = "Win"),
                    s: (l = "Lose")},
                {
                    value: "p",
                    r: l,
                    p: d,
                    s: w},
                {
                    value: "s",
                    r: w,
                    p: l,
                    s: d}
            ]
            //Have the computer pick a random variable
            [Math.random() * 3 | 0]

    //Output the value the computer chose
    ).value

    //Output whether the user won or not
    + r[prompt()]
);

```

Finally, here's a fiddle with both.

# Answer
> 1 votes
Javascript: **256**

golfed:

```
i=prompt(),a=['p','r','s'];a=a[Math.floor(Math.random()*(3-1+1))+1];if(i==a){alert('d');}else if(i=='p'){if(a=='s'){alert('l');}else{alert('w');}}else if(i=='r'){if(a=='s'){alert('w');}else{alert('l');}}else if(i=='s'){if(a=='r'){alert('l');}else{alert('w')}}

```

ungolfed:

```
i=prompt(),a=['p','r','s'];
a=a[Math.floor(Math.random()*(3-1+1))+1];
if(i==a){
    alert('d');
}
else if(i=='p'){
    if(a=='s'){
        alert('l');
    }else{alert('w');}
}else if(i=='r'){
    if(a=='s'){
        alert('w');
    }else{alert('l');}
}else if(i=='s'){
    if(a=='r'){
        alert('l');
    }else{alert('w')}
}

```

# Answer
> 1 votes
Clojure:

```
(def r 0) (def s 1) (def p 2)
(def object-name #(get {'p "Paper", 's "Scissors", 'r "Rock"} %))
(def result-name #(get {\d "Draw", \w "Win", \l "Lose"} %))
(defn computer-choice [] (nth ['r 's 'p] (int (rand 3))))
(defn game [a b] (get "dwlldwwld" (+ (* 3 a) b) ))
(defn print-game [user comp result] (print (format
  "User: %s\nComputer: %s\nResult: %s\n"
  (object-name user) (object-name comp) (result-name result))))
(println "Enter 'p', 's' or 'r' and press return")
(let [comp (computer-choice),  user (read)]  (print-game user comp (game (eval user) (eval comp))))

```

Mini version (129 code characters):

```
java -jar clojure.jar -e \
"(def r 0)(def s 1)(def p 2)(let[u(read),c(nth['r 's 'p](int(rand 3)))](print c)(print (get \"dwlldwwld\"(+(* 3(eval u))(eval c)))))"

```

# Answer
> 1 votes
**JAVA (387)** first code golf!

```
import java.util.HashMap;public class _ {public static void main(String i[]){HashMap l = new HashMap(){{put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');}};char u =i[0].charAt(0);char c ="rps".charAt((int)(Math.random()*3)%3);int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};System.out.println("U"+u+"C"+c+"R"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));}}

```

---

**Ungolfed**

```
import java.util.HashMap;
public class _ {
    public static void main(String[] input) {
       input = new String[] {"s"};
       HashMap lookup = new HashMap(){{
           put('r', 0);
           put('p', 1);
           put('s', 2);
           put(0, 'T');
           put(1, 'L');
           put(2, 'W');
       }};
       char user = input[0].charAt(0);
       char computer = new char[] {'r', 'p', 's'}[(int)(Math.random()*3)%3];
       int[][] matrix = new int[][] {{0,1,2}, {2,0,1}, {1,2,0}};

       Integer userChoice = (Integer) lookup.get(user);
       Integer computerChoice = (Integer) lookup.get(computer);
       Character result = (Character) lookup.get(matrix[userChoice][computerChoice]);

       System.out.println("u:" + user + ",c:" + computer + ",r:" + result);
    }
    /*
     t = 0, l = 1, w = 2
     *
        +---------------+
        | * | r | p | s |
        +---------------+
        | r | 0 | 1 | 2 |
        +---------------+
        | p | 2 | 0 | 1 |
        +---------------+
        | s | 1 | 2 | 0 |
        +---------------+
     */
}

```

---

**Golfed (Spacing/Indentation)**

```
import java.util.HashMap;
public class _ {
public static void main(String i[]) {
    HashMap l = new HashMap(){{
        put('r',0);put('p',1);put('s',2);put(0,'T');put(1,'L');put(2,'W');
    }};

    char u =i[0].charAt(0);char c = "rps".charAt((int)(Math.random()*3)%3);
    int[][] m =new int[][]{{0,1,2},{2,0,1},{1,2,0}};

    System.out.println("U"+u+"C"+c+"R:"+(Character)l.get(m[(Integer)l.get(u)][(Integer)l.get(c)]));
}}

```

---

<sub>Not the shortest code, but my first try</sub>

# Answer
> 1 votes
**Go (169)**

Golfed :

```
package main
import("fmt";"os")
func main(){v:=map[uint8]int{114:0,112:1,115:2}
u:=os.Args[1][0]
c:="rps"[os.Getpid()%3]
fmt.Printf("%c\n%c\n",c,"TWL"[(3+v[c]-v[u])%3])}

```

Ungolfed (as formatted by `go fmt`):

```
package main

import (
    "fmt"
    "os"
)

func main() {
    v := map[uint8]int{114: 0, 112: 1, 115: 2}
    u := os.Args[1][0]
    c := "rps"[os.Getpid()%3]
    fmt.Printf("%c\n%c\n", c, "TWL"[(3+v[c]-v[u])%3])
}

```

Run :

> go run main.go p
>
> s
>
> W

# Answer
> 1 votes
**Groovy, 89**

```
v='rps'
r=new Random().nextInt(3)
print"${v[r]}${'TLW'[((r-v.indexOf(this.args[0]))%3)]}"

```

Takes user choice as argument. Example:

```
groovy rps.groovy p
sL

```

# Answer
> 1 votes
# Pyth, 23

```
J"rps"K+wOJK%-XJ'KXJtK3

```

Output is in the form:

Tie: 0 Win: 1 Loss: 2

Explanation:

```
J"rps"             J="rps"
K+wOJ              K=input()+random_choice(J)
K                  print K
  XJ'K             index of K[0] in J
      XJtK         index of K[1] in J
 -XJ'KXJtK         difference of above indexes
%-XJ'KXJtK3        above difference mod 3

```

Run as follows:

```
$ cat rps
J"rps"K+wOJK%-XJ'KXJtK3
s
$ cat rps | python3 pyth.py
< Extraneous debug output removed>
sp
1

```

---

For only 4 more characters, we can use T for tie, W for win and L for loss:

```
J"rps"K+wOJKr@"TWL"-XJ'KXJtK

```

Everything is the same up until the difference of indexes, at which point we use the difference as the index into the string`"TWL"`.

---

Note: while I did develop this language after the challenge was posted, I had not seen the challenge until today. The challenge did not influence any aspect of the language.

# Answer
> 1 votes
# Jelly, 15 bytes

```
“rsp”
¢i¢ṙi¢XṄ¤

```

Try it online!

This returns:

* 3 if you tie
* 2 if you lose
* 1 if you win

and expects input as one of `r`, `p` or `s`

## How it works

```
“rsp” - Helper link. Return "rsp"

¢i¢ṙi¢XṄ¤ - Main link. Takes a character C on the left e.g. "r"
¢         - "rsp"
 i        - Get the 1-index of C in "rsp", i           e.g. 1
  ¢       - "rsp"
   ṙ      - Rotate "rsp" i steps to the left           e.g. "spr"
        ¤ - Create a nilad:
     ¢    -   "rsp"
      X   -   Random element, X                        e.g. "r", "s", "p"
       Ṅ  -   Print
    i     - 1-Index of X in the rotated "rsp"          e.g.  3 ,  1 ,  2

```

# Answer
> 1 votes
# Julia 0.7, 35 bytes

```
p->[c=rand("prs");"WLLDWWL"[c-p+4]]

```

ungolfed:

```
function f(p)
    c = rand("prs")
    result = "WLLDWWL"[c-p+4]
    return [c, result]
end

```

characters are converted to integers when subtracted (for example `'r'-'r' == 0` and `'s'-'r' == 1`), good thing `p`, `r` and `s` are close in the alphabet

output: `'L'` you lose, `'W'` you win, `'D'` draw

Julia 0.7 because Julia 1.x would use 3 more characters

Try it online!

# Answer
> 1 votes
## JavaScript, 49 characters

*This an old question but got shorter answer while doing of Advent of Code 2022 day 2*

---

> ***Input:***
>
> ```
> r = rock
> p = paper
> s = scissors
>
> ```

> ***Output:***
>
> ```
> [computers choice][0=Loss, 1=Win, 2=Draw]
>
> ```

> ***Example:***
>
> ```
> User  Computer  Result
> r     r         r2
> r     p         p0
> r     s         s1
>
> ```

---

***Golfed code:***

```
'rps'[c=new Date%3]+(1+c-'ps'.search(prompt()))%3

```

This can be invoked by pasting code in browsers console

***Ungolfed code***

```
function rock_paper_scissors(play) {
    const computer = new Date%3 // pseudo random choice of 0, 1, or 2
    const choices = ['Rock', 'Paper', 'Scissors']
    const playNumber = choices.indexOf(play)
    let answer = `You chose ${play}, `
    answer += `Computer chose ${choices[computer]}, you `
    answer += ['Lose', 'Win', 'Tied'][(2 + computer - playNumber) % 3]
    return answer
}

rock_paper_scissors('Rock')

```

# Answer
> 0 votes
## C# & LinqPad 133

golfed:

```
char i,c,r;i=Console.ReadLine()[0];var a="prsp";c="prs"[new Random().Next(3)];r=i==c?'T':a.Contains(""+i+c)?'W':'L';(c+">"+r).Dump();

```

ungolfed:

```
        char i, c, r; // i for input / c for choosen by computer / r for result
        i = Console.ReadLine()[0]; //getting input in LinqPad
        var a = "prsp";
        c = "prs"[new Random().Next(3)]; // Computer choose a random string
        r = i == c ? 'T' : a.Contains("" + i + c) ? 'W' : 'L'; (c + ">" + r).Dump(); //check for win - dump for output in LinqPad

```

sample output(input was s) : r\>L //Computer chooses rock(r) -\> so we lost

# Answer
> 0 votes
**JavaScript** *(79)*

*Bumping an old one, but here we go ...*

With the added bonus that you can use any rock you like pegnatite, pyroxenite, scoria, sovite, kimberlite, trondjemite, tuff or any other. Only limitation is that you can not use `p` or `s` *;-)*

---

> ***Input:***
>
> ```
> r = rock      (Or , ...)
> p = paper
> s = scissors
>
> ```
>
> ***Output:***
>
> ```
> [computers choice][0=Loss, 1=Win, 2=Draw]
>
> ```
>
> ***Example:***
>
> ```
> User  Computer  Result
> r     r         r2
> r     p         p0
> r     s         s1
>
> ```

---

***Golfed code:***

```
u=~~{p:1,s:2}[prompt()],c=new Date%3;alert('rps'[c]+(u==c?2:!u&c>1|u&!c|u>1&c))

```

The main tricks used are:

`**1.** u = ~~{}[prompt()]`

Using object `{}` and retrieving value by user input from `prompt()`. So far so good. Then instead of having `r : 0` we can force it to be converted to `0` by using the `~~` NOT operator. It is frequently used to floor numbers, but also has the *(advantage)* of not returning `NaN` when other operators would, like for example: `+{a:1, b:2}['c']`.

`**2.** c = new Date%3`

Date is frequently tricked with by e.g. using `+new Date` to convert it to timestamp directly, else one would get a string representation. Here by using *mod* one achieve the same effect.

`**3.** 'rps'[c]`

Indexed access on string giving computers choice `0 = r`, `1 = p` or `2 = s`.

`**4.** (u==c ? 2 : !u&c>1 | u&!c | u>1&c )`

```
   IF  u == c
       Draw                    (aka 2)
   ELSE IF !u&c>1|u&!c|u>1&c
       Win                     (aka 1)
   ELSE
       Loss                    (aka 0)
   ENDIF

...

```

---

The ungolfed code can be something like this:

```
function rock_paper_scissors() {
    var choices = {
            r : 0,
            p : 1,
            s : 2,
        },
        tr_table = ['Rock','Paper','Scissors'],
        user, pc, result
    ;

    function get_input() {
        var input = prompt("Enter your choice `r', `p' or `s':")
                    .toLowerCase();

        if (!/^[rps]/.test(input)) {
            console.warn("Bad input. Please choose `r', `p' or `s'.");
            // return get_input();
            return null;
        }
        return input[0];
    }
    function report(c1, c2) {
        if (c1 === pc) {
            return 'Draw';
        } else if (
            (c1 === 0 && c2  >  1) ||
            (c2 === 0 && c1 === 1) ||
            (c1  >  1 && c2  >  0)
        ) {
            return 'Win';
        } else {
            return 'Loss';
        }
    }

    if ((user = get_input())) {
        user = choices[user];
        pc = Math.floor(Math.random() * 3);
        result  =
            'Computers choice: ' + tr_table[pc] + ', ' +
            'Your choice: ' + tr_table[user] + ', ' +
            'Result=' +  report(user, pc);
        console.log(result);
    }
    return result;
}

rock_paper_scissors();

```

# Answer
> 0 votes
## Golfscript - 29

This is an actual answer this time (looking at you, `n"Draw"` :P ).

```
'rps'.@\?3rand.@- 3%@@[=]''+\

```

Ungolfed:

```
'rps'3rand[=]''+.2$={\;'
T'}{.@'rspr'.@?@@(;\?='
L''
W'if=}if

```

You can run it with `ruby golfscript.rb MyCode.txt`, where `MyCode.txt` is the program code.

Sample runs (all with input "r", but it works with everything) (tie is 0, win is 2, loss is 1):

```
ruby golfscript.rb MyCode.txt
r0
ruby golfscript.rb MyCode.txt
p2
ruby golfscript.rb MyCode.txt
s1

```

If you want an explanation of either version and/or see a potential improvement, tell me.

# Answer
> 0 votes
## Javascript, ~~65~~ ~~71~~ 70

Without computer choise output: **65**

```
alert('-+0+0+0'['rppssrr'.indexOf('rps'[new Date%3]+prompt())+1])

```

Just to test that solution is correct:

```
for(x in {r:0,p:0,s:0})
  for(y in {r:0,p:0,s:0})
    console.log("%s %s %s", x, y, '-+0+0+0'['rppssrr'.indexOf(x+y)+1])

```

With computer choise output: **71**

```
alert((c='rps'[new Date%3])+'-+0+0+0'['rppssrr'.indexOf(c+prompt())+1])

```

**70**

```
alert((g='rps'[new Date%3]+prompt())+-('srps'.match(g)?-1:g[0]!=g[1]))

```

and the test:

```
for(x in {r:0,p:0,s:0})
  for(y in {r:0,p:0,s:0})
    console.log((g=x+y)+-('srps'.match(g)?-1:g[0]!=g[1]))

```

# Answer
> 0 votes
# Python 3, ~~81~~ 76 bytes

```
from random import*
c=randint(0,2)
print('rps'[c],('rps'.find(input())-c)%3)

```

Thought I was being clever and using what I learnt in this challenge. It's not enough unfortunately.

# Answer
> 0 votes
# Befunge93: 85 bytes

```
~v>"R"v    >:2+|>"L",@
@>?"P">:,-:|v  <|-3<
  >"S"^v"T"<   >:1+|
^     ,< "W"<   <  <

```

Same principle as @Fors's answer, with a more compact layout.

Note : I proposed this as an edit to aforementioned answer, but It seems to have been rejected (is there a notification for that ? It's the first time I suggest an edit). If I am mistaken, and the edit gets accepted I'll gladly delete this answer.

# Answer
> 0 votes
# Zsh, ~~83~~ 53 bytes

```
z=rps;g=$z[RANDOM%3+1];<<<$g
c=wlldwwl;<<<$c[#g-#1+4]

```

Try it Online! <sub>~~83 bytes~~</sub> ; hat-tip to @MarcMush

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


title: Where will the ball land?

text:
# Question
Title: Where will the ball land?
Given a string where the first line contains spaces and one period (`.`, the "ball"), followed by lines containing spaces, forward slashes (`/`), and backslashes (`\`), determine what column the ball will land in after falling from its starting position. Each `/` moves it to the left by 1 column and each `\` moves it to the right by 1 column.

### Sample input

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

```

### Sample output

The ball starts in column 5, hits the `/` on line 3, then the three `\`'s on lines 5 through 7 for a final position of:

```
7

```

Note that columns are 1-indexed, mostly for consistency with text editor conventions.

### Edge cases

If the ball hits a `/` in the first column, it's eternally stuck in the nonexistent column 0. Your program should handle this correctly by printing `0`.

If the ball hits either side of a `\/` pattern, the result is undefined. Your program is permitted to terminate with no output, loop infinitely, or print an error message (my solution prints `-1`), but it must not print anything that can be perceived to be valid output.

If the ball hits the left slash in a `\\` pattern, it should end up directly beneath the right slash, not to the right of it. The solution I originally envisioned was prone to getting this wrong, so don't go down that path!

There may or may not be spaces after the `.` or the last `/` or `\` on each line. Your program should not rely on such padding being available. On a similar note, there may or may not be any lines following the first line.

You may assume that the first line will have zero or more spaces and exactly one `.`. Subsequent lines, if any, will have zero or more spaces and zero or more slashes.

### Implementation details

Your program may read from a file (specified as a command-line argument) or read from standard input, at your convenience.

Your program must output a single number to standard output. (Yes, a trailing newline is fine. Yes, the number may have more than one digit.)

### Test cases

> Input:
>
> ```
> .
>
> ```
>
> Output:
>
> ```
> 1
>
> ```
>
> Note that the input here is exactly one byte. This is the smallest case you should be able to handle.

> Input:
>
> ```
>  .
>  \
>   \
>    \
>     \
>
> ```
>
> Output:
>
> ```
>  6
>
> ```
>
> Note that there are no spaces after these slashes.

> Input:
>
> ```
>   .
>   /
>  /\\  /  \
> //\ \/// //
> \\/ \/\ /\/
>
> ```
>
> Output:
>
> ```
> 0
>
> ```

> Input:
>
> ```
>   .
> / / /
>  \\\
>   /\\
>  /   \
>
> ```
>
> Output:
>
> ```
> 1
>
> ```

> Input:
>
> ```
>    .
>
>
>  \
>        /
> /
>
>       \
>
> ```
>
> Output:
>
> ```
> 4
>
> ```

> Input:
>
> ```
>  .
>  \
>
> \/\/\/
>
> ```
>
> Output:
>
> ```
> (anything but a nonnegative number)
>
> ```

### Closing remarks

This question is similar to Simulate a (gravity-based) billiard-ball-type computer, but significantly simpler, so hopefully it will gain more interest.

I have a 169-character solution in Python. I'm sure the talented golfers here can tear that record to pieces, though. :^)

This is , so the shortest answer in characters will be accepted at the end of the month!

# Answer
# Python, 143B

```
import sys
for l in sys.stdin:
 a=l.find('.')
 if a>-1:F=a
 elif F>-1:
    if'\\/'in l[F-1:F+2]:z
    F+={'\\':1,'/':-1}.get((l+' '*F)[F],0)
print F+1

```

Using the space/tab indentation trick. I haven't done anything particularly clever here. `F` is the current index, `l` is the current line; `z` is undefined so it throws an exception, which is definitely not a positive integer, handling the `\/` situation.
> 5 votes

# Answer
# 05AB1E, 37 bytes

```
¶¡ð«ć'.ksvU…/ \yXD>‚èJD„\/Qiõqëнk<X+]>

```

Input as a multi-line string. Outputs `\/` if the ball is stuck.

Try it online or verify all test cases.

**Explanation:**

```
¶¡                       # Split the (implicit) input-string on newlines
                         # (work-around instead of `|`, because it will stop at empty lines)
  ð«                     # Add a trailing space to each line (work-around because indexing
                         # -1 in 05AB1E will wrap around to the other side)
    ć                    # Extract head; pop and push the remainder-lines and first line
                         # separated to the stack
     '.k                '# Get the 0-based index of "." in this first line
s                        # Swap to get the remainder-list of lines
v                        # Loop over each line `y`:
 U                       #  Pop and store the top value (the index) in variable `X`
       X                 #  Push the current index `X`
        D>               #  Duplicate it, and increase the copy by 1
          ‚              #  Pair to [X, X+1]
      y    è             #  Index both of those into the current line `y`
            JD           #  Join the two characters together, and duplicate it
              „\/Qi      #  If it's equal to "\/":
                   q     #   Stop the program
                         #   (after which the string is output implicitly as result)
                  ë      #  Else:
                   н     #   Only leave the first character (at index `X`)
  …/ \              k    #   Get its 0-based index in string "/ \"
                     <   #   Decrease it by 1
                      X+ #   And add it to `X`
]                        # After the loop:
 >                       # Increase the top of the stack (`X`) by 1
                         # (after which it's output implicitly as result)

```
> 2 votes

# Answer
## CJam, 61 bytes

```
qN/('.#)\_:,0+:e>f{' e]" /"f#0\+}{1$1$=\@2$-_@=@[\]$[W1]#/z}/

```

If the rule regarding `\/` is lifted (and we are not required to handle it), this can be shortened to **41** bytes:

```
qN/('.#)\_:,:e>f{' e]" /"f#0\+0+}{1$=-}/

```
> 1 votes

# Answer
# Java 11, ~~213~~ ~~208~~ ~~190~~ ~~175~~ ~~162~~ 160 bytes

```
s->{int r=s.indexOf('.'),c;for(var x:s.split("\n"))if((c=(x+=" ".repeat(r+2)).charAt(r))!=46&&(r+=c<33?0:c<48?-1:x.charAt(r+1)==47?r/0:1)<0)return 0;return++r;}

```

Throws a division by zero error when we are stuck inside a `\/`.

-5 bytes thanks to *@EdgyNerd*
-17 bytes thanks to *@ceilingcat*

Try it online.

**Explanation:**

```
s->{                             // Method with String parameter and integer return-type
  int r=s.indexOf('.'),          //  Get the index of the dot on the first line
      c;                         //  Temp integer
  for(var x:s.split("\n"))       //  Split the input by newlines, and loop over the lines:
    if((c=(x+=" ".repeat(r+2))   //   Append trailing spaces to the line if necessary
          .charAt(r))            //   Get the character at the current index of this line
       !=46                      //   If this is NOT the first line (the char isn't a dot):
       &&(r+=c<33?               //    If the current char is a space:
              0                  //     Index `r` remains the same
             :c<48?              //    Else-if it's a '/':
              -1                 //     Index `r` is decreased by 1
             :x.charAt(r+1)==47? //    Else-if we're stuck in a `\/`:
              r/0                //     Divide by 0 to exit with an error
             :                   //    Else (it's a '\'):
              1)                 //     Index `r` is increased by 1
         <0)                     //    If `r` is now -1:
      return 0;                  //     Return 0
  return++r;}                    //  After the loop: return the index `r` + 1

```
> 1 votes

# Answer
# Python 3, 124 bytes

```
import sys
for l in sys.stdin:i=('.'in l)*l.find('.')or(i<0)*i-2*('\\/'in l[i-1:i+2])or' \\'.find((l+i*' ')[i])+i
print(i+1)

```

Try it online!

Also works in Python 2.

### Explanation

```
for l in sys.stdin:i=          # Change value i for each line in the input
('.'in l)*l.find('.')          # Set i to (0-indexed) dot position if present
or(i<0)*i                      # Keep i fixed if it is below zero
-2*('\\/'in l[i-1:i+2])        # Set i to -2 if \/ trap is encountered
or' \\'.find((l+i*' ')[i])+i   # Else: move position based on character
print(i+1)                     # Print final 1-indexed position

```
> 1 votes

# Answer
# , 95 bytes

```
[:>[:(<"1@|.@}.([:(1&{+_*0>[:*/2-/\])(]+{~ ::])^:(<3))&.>/@,2<@i.~{.)[:(0,'/ \'<:@i.]);._1 LF,]

```

Try it online!

Returns infinity `_` when the ball gets stuck. Lost many bytes handling that special case. Otherwise it's more or less a simple reduction of the rows. Could surely be golfed further.
> 0 votes

# Answer
# JavaScript (Node.js), 123 bytes

```
x=>(g=(i,c)=>y[j++][i]==c?g:y[j]+1?(k=y[j][i])=='/'?g(i-1,'\\'):k=='\\'?g(i+1,'/'):g(i,g):i)(x.indexOf`.`,j=0,y=x.split`
`)

```

Try it online!

0-index, output `g` if stucked
> 0 votes

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