title: Rotate the dots

text:
# Question
Title: Rotate the dots
## Introductions

A 2×n Boolean matrix can be represented as a string of the four characters `. ':`. The string has an "upper row" and a "lower row", with dots representing 1s and empty spaces representing 0s. For example, the 2×6 matrix

```
1 0 1 0 0 1
0 0 0 1 0 1

```

can be represented as `' '. :`. Your task is to take a matrix in this "compressed form", and rotate its entries one step clockwise, like a conveyor belt.

## Input

Your input is a single string over the characters `. ':`. Its length is guaranteed to be at least 2.

## Output

Your output shall be the input string, but with every dot rotated one step in the clockwise direction. More explicitly, the dots on the upper row more one place to the right, except the rightmost one, which moves down. The dots on the lower row move one step to the left, except the leftmost one, which moves up. In particular, the output string must have the same length as the original, and whitespace is significant.

## Example

Consider the input string `:..:'.`, which corresponds to the 2×6 matrix

```
1 0 0 1 1 0
1 1 1 1 0 1

```

The rotated version of this matrix is

```
1 1 0 0 1 1
1 1 1 0 1 0

```

which corresponds to the string `::. :'`.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. You can decide whether the input and output are enclosed in quotes, and one trailing newline is also acceptable in both.

## Test cases

These test cases are enclosed in double quotes.

```
"  " -> "  "
" ." -> ". "
". " -> "' "
"' " -> " '"
" '" -> " ."
": " -> "''"
"''" -> " :"
":." -> ":'"
":.'" -> ":'."
"..." -> ":. "
": :" -> "':."
"':." -> ".:'"
".:'" -> ": :"
"    " -> "    "
"::::" -> "::::"
":..:'." -> "::. :'"
" :  .:'" -> ". '.. :"
": ''. :" -> "'' :'.."
"........" -> ":...... "
"::::    " -> ":::''   "
"    ::::" -> "   ..:::"
" : : : : " -> ". : : : '"
".'.'.'.'.'" -> "'.'.'.'.'."
".. ::  '.' :." -> ": ..'' .' :.'"
".'  '.::  :.'. . ::.'  '. . .::'  :.'." -> "' ' .:.''..'.'. ..:' ' .'. ...'''..'.'"

```

# Answer
> 11 votes
# JavaScript (ES6), ~~100~~ ~~97~~ 93 bytes

*Saved 4 bytes thanks to @edc65*

```
s=>s.replace(/./g,(c,i)=>" '.:"[(i?q>' '&q!=".":c>"'")+(q=c,s[++i]?s[i]>"'":c>' '&c!=".")*2])

```

### How it works

This decides on the character we need to insert by performing some calculations on the chars before and after the current one. We sum:

* If it's the first char, and it has a dot on the bottom, 2;
* Otherwise, if the one before it has a dot on top, 2.
* If it's the last char, and it has a dot on top, 1;
* Otherwise, if the one after it has a dot on the bottom, 1.

This sums nicely to 0 for a space, 1 for `'`, 2 for `.`, and 3 for `:`.

## Test snippet

```
f=s=>s.replace(/./g,(c,i)=>" '.:"[(i?q>' '&q!=".":c>"'")+(q=c,s[++i]?s[i]>"'":c>' '&c!=".")*2])
```

```
Try it out:
<input id=A type="text" value=".'  '.::  :.'. . ::.'  '. . .::'  :.'.">
<button onclick="B.innerHTML=f(A.value)">Run</button>
<pre id=B></pre>
```

# Answer
> 9 votes
# Jelly, ~~32~~ ~~30~~ 29 bytes

```
,Ṛe€"“':“.:”µṪ€;"ṚU1¦ZḄị“'.:

```

Note the trailing space. Try it online! or verify all test cases.

### Background

We begin by considering the input string (e.g., `:..:'.`) and its reverse.

```
:..:'.
.':..:

```

For each character in the top row, we check if it belongs to `':`, and for each character of the bottom row if it belongs to `.:`. This gives the 2D array of Booleans

```
100110
101111

```

which is the matrix from the question, with reversed bottom row.

We remove the last Boolean of each row, reverse the order of the rows, prepend the Booleans in their original order, and finally reverse the top row.

```
100110    10011    10111    010111    111010
101111    10111    10011    110011    110011

```

This yields the rotated matrix from the question.

Finally, we consider each column of Booleans a binary number and index into `'.:`  to obtain the appropriate characters.

```
332031    ::. :'

```

### How it works

```
,Ṛe€"“':“.:”µṪ€;"ṚU1¦ZḄ‘ị“'.:   Main link. Argument: S (string)

 Ṛ                              Reverse S.
,                               Form a pair of S and S reversed.
     “':“.:”                    Yield ["':" ".:"].
  e€"                           For each character in S / S reversed, check if it
                                is an element of "':" / ".:".
                                Yield the corresponding 2D array of Booleans.

            µ                   Begin a new, monadic chain.
                                Argument: A (2D array of Booleans)
             Ṫ€                 Pop the last Boolean of each list.
                 Ṛ              Yield the reversed array of popped list.
               ;"               Prepend the popped items to the popped lists.
                  U1¦           Reverse the first list.
                     Z          Zip to turn top and bottom rows into pairs.
                      Ḅ         Convert each pair from base 2 to integer.
                        “'.:    Yield "'.: ".
                       ị        Retrieve the characters at the corr. indices.

```

# Answer
> 9 votes
# Perl, ~~70~~ ~~69~~ ~~64~~ ~~63~~ ~~61~~ 60 bytes

Includes +2 for `-lp`

Run with the input string on STDIN, e.g.

```
perl -lp rotatedots.pl <<< ":..:'."

```

`rotatedots.pl`:

```
y/'.:/02/r=~/./;y/.':/01/;$_=$'.2*chop|$&/2 .$_;y;0-3; '.:

```

## Explanation

```
y/'.:/02/r                                        Construct bottom row but
                                                  with 2's instead of 1's
                                                  Return constructed value
                                                  (for now assume space
                                                  becomes 0 too)
          =~/./                                   Match first digit on bottom
                                                  row into $&. $' contains
                                                  the rest of the bottom row
                y/.':/01/                         Convert $_ to top row
                                                  (again assume space
                                                  becomes 0 too)
                             $'.2*chop            Remove last digit from
                                                  the top row, multiply by 2
                                                  and append to bottom row
                                       $&/2 .$_   Divide removed digit by
                                                  2 and prepend it to the
                                                  top row
                          $_=         |           "or" the top and bottom
                                                  row together. The ASCII
                                                  values of 0,1,2,3 have
                                                  00,01,10,11 as their last
                                                  two bits.

y;0-3; '.:                  Convert the smashed together top and bottom rows
                            to the corresponding representation characters.
                            Drop the final ; since it is provided by -p
                            (after a newline which doesn't matter here)

```

Space  is not converted in the above code. For the calculations `/2` and `*2` it will behave like and become `0`. In the other positions it will be part of the "or", but the 1 bits of space are a subset of the one bits of `0` and will have the same effect as `0` if or-ed with any of the digits. Only if the character it is or-ed with is a space will it remain a space instead of becoming a `0`. But that's ok since `0` would have been converted back to space anyways.

# Answer
> 8 votes
# Retina, 66

* 2 bytes saved thanks to @daavko
* 4 bytes saved thanks to @randomra

```
:
1e
\.
1f
'
0e

0f
T`h`Rh`^.|.$
(.)(\d)
$2$1
e1
:
e0
'
f0

f1
.

```

### Explanation

Starting with input:

```
: ''. :

```

The first 4 stages construct the matrix, using `1`/`e` for true and `0`/`f` for false for the top/bottom rows, respectively. Top and bottom rows are interlaced together. This would yield a string like:

```
e1f0e0e0f1f0e1

```

However, these 4 stages also effectively move the lower row 1 to the left, simply by reversing the order of the letters and digits:

```
1e0f0e0e1f0f1e

```

The `T`ransliteration stage reverses hex digits for the first and last characters only, i.e. replaces `0-9a-f` with `f-a9-0`. This has the effect of moving the bottom-left character up to the top row and the top-right character down to the bottom row:

```
ee0f0e0e1f0f11

```

The next stage then swaps every letter-digit pair, thereby moving the upper row 1 to the right. Previously this was `(\D)(\d)`, but it turns out that `(.)(\d)` is sufficient because the substitutions always happen left-to-right and so the final two digits won't be erroneously matched by this, because penultimate character will have been already substituted. The matrix has now been fully rotated as required:

```
e0e0f0e1e0f1f1

```

The final 4 stages then translate back to the original format:

```
'' :'..

```

Try it online.

All testcases, one per line, `m` added to `T` line to allow separate treatment of each input line.

# Answer
> 6 votes
# Python 3, ~~145~~ ~~141~~ 130 bytes

```
def f(s):a=[i in"':"for i in s]+[i in".:"for i in s][::-1];return''.join(" '.:"[i+2*j]for i,j in zip([a[-1]]+a,a[-2:len(s)-2:-1]))

```

## Explanation

The golfed solution use the following property of zip : `zip('ABCD', 'xy') --> Ax By`  so `zip(a[:l],a[l:])`  can be replace by `zip(a,a[l:])` and that allow to remove the definition of `l`

```
def f(s):
 l=len(s)-1
 #                ┌───── unfold input string :  123  -> 123456
 #                │                             654
 #  ──────────────┴──────────────────────────────
 a=[i in"':"for i in s]+[i in".:"for i in s][::-1]
 # ─────────┬─────────   ────────────┬───────────
 #          │                        └──── generate the second row and reverse it
 #          └─────────── generate the first row

 return''.join(" '.:"[i+2*j]for i,j in zip([a[-1]]+a[:l],a[l:-1][::-1]))
 #             ──────┬──────           ─┬    ────────────┬───────────
 #                   │                  │                └──── rotate and create first/second new row :  123456  -> 612345  -> 612
 #                   │                  │                                                                                543
 #                   │                  └ group pair of the first and second row : 612 -> (6,5),(1,4),(2,3)
 #                   │                                                             543
 #                   └─────────── replace pair by symbol

```

## Results

```
>>> f(".'  '.::  :.'. . ::.'  '. . .::'  :.'.")
"' ' .:.''..'.'. ..:' ' .'. ...'''..'.'"
>>> f(".....''''''")
":...  '''':"

```

# Answer
> 5 votes
# Pyth, ~~38~~ 36

```
L,hb_ebsXCyc2.>syCXzJ" .':"K.DR2T1KJ

```

2 bytes thanks to Jakube!

Try it here or run the Test Suite.

### Explanation:

```
L,hb_eb         ##  Redefine the function y to take two lists
                ##  and return them but with the second one reversed
                ##  Uses W to apply a function only if it's first argument is truthy
XzJ" .':"K.DR2T ##  Does a translation from the string " .':" to
                ##  .DR2T which is [0,1,2,3...,9] mapped to divmod by 2
                ##  (which is [0,0],[0,1],[1,0],[1,1], then some extra, unused values)
                ##  we also store the string and the list for later use in J and K
.>syC ... 1     ##  zip the lists to get the bits on top and below as two separate lists
                ##  apply the function y from before, flatten and rotate right by 1
Cyc2            ##  split the list into 2 equal parts again, then apply y and zip again
sX ... KJ       ##  apply the list to string transformation from above but in reverse
                ##  then flatten into a string

```

# Answer
> 4 votes
# Pyth, 66 bytes

```
KlQJ.nCm@[,1Z,Z1,ZZ,1 1)%Cd5Qjkm@" .':"id2Ccs[:JKhK<JtK>JhK:JtKK)K

```

Try it here!

## Explanation

This can be broken down in 3 parts:

* Convert the input into a flat array of ones and zeros.
* Do the rotation.
* Convert it back into ASCII.

### Convert input

This is fairly trivial. Each character is mapped in the following way:

```
  -> (0,0)
. -> (0,1)
' -> (1,0)
: -> (1,0)

```

*First one is a whitespace.*
We get a list of 2-tuples which we transpose to get the 2 rows of the matrix which then gets flattened.

**Code**

```
KlQJ.nCm@[,1Z,Z1,ZZ,1 1)%Cd5Q   # Q = input

KlQ                             # save the width of the matrix in K (gets used later)
       m                    Q   # map each character d
                        %Cd5    # ASCII-code of d modulo 5
        @[,1Z,Z1,ZZ,1 1)        # use this as index into a lookup list
   J.nC                         # transpose, flatten and assign to J

```

### Rotate

We have the matrix as flat array in `J` and the width of the matrix in `K`. The rotation can be described as:

```
J[K] + J[:K-1] + J[K+1:] + J[K-1]

```

**Code**

```
s[:JKhKJhK:JtKK)    # J = flat array, K = width of matrix

s[                  )    # Concat all results in this list
  :JKhK                  # J[K]
       JhK          # J[K+1:]
               :JtKK     # J[K-1]

```

## Convert it back

```
jkm@" .':"id2Cc[)K    # [) = resulting list of the step above

              c[)K    # chop into 2 rows
             C        # transpose to get the 2-tuples back
  m                   # map each 2-tuple d
          id2         # interpret d as binary and convert to decimal
   @" .':"            # use that as index into a lookup string to get the correct char
jk                    # join into one string

```

# Answer
> 3 votes
# Python 3, ~~166~~ ~~154~~ ~~153~~ ~~150~~ ~~146~~ ~~138~~ ~~137~~ ~~135~~ ~~132~~ 127 bytes

**Edit:** I've borrowed the use of `zip` from Erwan's Python answer at the end of the function. ~~and their idea to use `[::-1]` reversals, though I put in my own twist.~~ As it turns out, reversals were not a good idea for my function. I have changed my use of `format` for further golfing. Moved `a` and `b` directly into `zip` for further golfing (ungolfing remains unchanged because the separation of `a` and `b` there is useful for in avoiding clutter in my explanation)

**Edit:** Borrowed `(some number)>>(n)&(2**something-1)` from this answer by xnor on the Music Interval Solver challenge. The clutter that is `zip(*[divmod(et cetera, 2) for i in input()])` can probably be golfed better, though I do like the expediency it grants from using two tuples `t` and `v`.

```
t,v=zip(*[divmod(708>>2*(ord(i)%5)&3,2)for i in input()])
print("".join(" '.:"[i+j*2]for i,j in zip((v[0],*t),(*v[1:],t[-1]))))

```

**Ungolfed:**

```
def rotate_dots(s):
    # dots to 2 by len(s) matrix of 0s and 1s (but transposed)
    t = []
    v = []
    for i in s:
        m = divmod(708 >> 2*(ord(i)%5) & 3, 2)
            # ord(i)%5 of each char in . :' is in range(1,5)
            # so 708>>2 * ord & 3 puts all length-2 01-strings as a number in range(0,4)
            # e.g. ord(":") % 5 == 58 % 5 == 3
            # 708 >> 2*3 & 3 == 0b1011000100 >> 6 & 3 == 0b1011 == 11
            # divmod(11 & 3, 2) == divmod(3, 2) == (1, 1)
            # so, ":" -> (1, 1)
        t.append(m[0])
        v.append(m[1])

    # transposing the matrix and doing the rotations
    a = (v[0], *t)          # a tuple of the first char of the second row
                            # and every char of the first row except the last char
    b = (v[1:], t[-1])      # and a tuple of every char of the second row except the first
                            # and the last char of the first row

    # matrix to dots
    z = ""
    for i, j in zip(a, b):
        z += " '.:"[i + j*2]    # since the dots are binary
                                # we take " '.:"[their binary value]
    return z

```

# Answer
> 3 votes
# MATL, ~~40~~ 39 bytes

```
' ''.:'tjw4#mqBGnXKq:QKEh1Kq:K+hv!)XBQ)

```

**Try it online!** *The linked version has `v` repaced by `&v`, because of changes in the language after this answer was posted*.

```
' ''.:'               % pattern string. Will indexed into, twice: first for reading
                      % the input and then for generating the ouput
t                     % duplicate this string
j                     % input string
w                     % swap
4#m                   % index of ocurrences of input chars in the pattern string
qB                    % subtract 1 and convert to binay. Gives 2-row logical array
GnXKq:QKEh1Kq:K+hv!   % (painfully) build two-column index for rotation
)                     % index into logical array to perform the rotation
XBQ                   % transform each row into 1, 2, 3 or 4
)                     % index into patter string. Implicitly display

```

# Answer
> 2 votes
## Ruby, ~~166~~ 163 bytes

```
->s{a=s.tr(f=" .':",t='0-3').chars.map{|x|sprintf('%02b',x).chars}.transpose;a[1]+=[a[0].pop];a[0]=[a[1].shift]+a[0];a.transpose.map{|x|x.join.to_i 2}.join.tr t,f}

```

Yuck... `transpose` is too long.

Tricks used here:

* `sprintf('%02b',x)` to convert `"0"`, `"1"`, `"2"`, `"3"` into `"00"`, `"01"`, `"10"`, and `"11"` respectively. Surprisingly, the second argument does *not* have to be converted into an integer first.
* The rotation is done via `a[1].push a[0].pop;a[0].unshift a[1].shift;`, which I thought was at least a little clever (if not excessively verbose in Ruby). The symmetry is aesthetically nice, anyway :P

# Answer
> 2 votes
# Javascript ES6 125 bytes

```
q=>(n=[...q].map(a=>(S=` .':`).indexOf(a))).map((a,i)=>(i?n[i-1]&2:n[0]&1&&2)|((I=n[i+1])>-1?I&1:n[i]&2&&1)).map(a=>S[a]).join``

```

---

I map each character to a two digit binary equivalent

```
 : becomes 3   11
 ' becomes 2   10
 . becomes 1   01
   becomes 0   00

```

and I'm thinking of them as being one on top of the other

```
3212021 becomes
1101010
1010001

```

I save that to n

For each character (0-3) of n, I check it's neighbors, adding the highest order bit of the left neighbor to the lowest order bit of the right neighbor. if i==0 (first character) I use it's own lower order bit instead of the left neighbor's higher order bit.

if n\[i+1\]\>-1 it means we got 0,1,2,3 so when that's false we hit the last element.

When that happens I use the character's own highest order bit instead of the right neighbor's lower bit

map that back to  `.':` land and join that array back together

# Answer
> 2 votes
# Common Lisp, ~~253~~ 247 bytes

```
(defun R(i &aux(n(length i))(u #1=(make-list n))(b #1#))(dotimes(k n)(setf(elt u k)(find #2=(elt i k)"':")(elt b k)(find #2#".:")))(map'string(lambda(u b)(cond((and u b)#\:)(u #\')(b #\.)(t #\ )))`(,(car b),@(butlast u))`(,@(cdr b),(nth(1- n)u))))

```

Try it online!

Tests included in TIO.

```
(defun R (i &aux (n (length i))  ; take the length of input
                 (u #1=(make-list n))   ; create the top (up) list
                 (b #1#))  ; create the bottom list
  (dotimes (k.. n)
    (setf (elt u k) (find #2=(elt i k) "':")
; set the k'th element of the top list to a non-falsey value if k'th element of input is #\' or #\:
          (elt b k) (find #2# ".:")
; set the k'th element of the bottom list to a non-falsey value if k'th element of input is #\. or #\:
(map 'string  ; collect the results into a string
     (lambda (u b) ; for each element of the rotated up and bottom lists
       (cond
        ((and u b) #\:) ; if both top and bottom are non-falsey add #\:
        (u #\')         ; if only top is non-falsey add #\'
        (b #\.)         ; if only bottom is non-falsey add #\.
        (t #\ )))       ; if both are falsey add '#\ ' (#\Space)
     `(,(car b),@(butlast u))   ; first element of the bottom and the all but last element of the top
     `(,(cdr b),(nth(1- n)u)))) ; all but first element of the bottom and the last element of the top

```

*Saved 6 bytes using* `#=` *notation for* `(make-list n)` *and* `(elt i k)`

# Answer
> 1 votes
# JavaScript, 311 bytes

Can probably be improved alot:

```
a=(s=prompt()).length-1;o=s[0]==":"||s[0]=="."?s[1]==":"||s[1]=="."?":":"'":s[1]==":"||s[1]=="."?".":" ";for(i=1;i<a;i++)o+=s[i-1]=="'"||s[i-1]==":"?s[i+1]=="."||s[i+1]==":"?":":"'":s[i+1]=="."||s[i+1]==":"?".":" ";alert(o+=s[a]==":"||s[a]=="'"?s[a-1]==":"||s[a-1]=="'"?":":"'":s[a-1]==":"||s[a-1]=="'"?".":" ")

```

# Answer
> 1 votes
## Perl, ~~144~~ ~~142~~ ~~137~~ 131 bytes

```
y/.':/1-3/;s/./sprintf'%02b ',$&/ge;@a=/\b\d/g;@b=(/\d\b/g,pop@a);@a=(shift@b,@a);say map{substr" .':",oct"0b$a[$_]$b[$_]",1}0..@a

```

Byte added for the `-n` flag.

Pretty much the same algorithm as my Ruby answer, just shorter, because... Perl.

```
y/.':/1-3/;                         # transliterate [ .':] to [0123]
s/./sprintf'%02b ',$&/ge;           # convert each digit to 2-digit binary
@a=/\b\d/g;                         # grab the 1st digit of each pair
@b=(/\d\b/g,                        # 2nd digit of each pair
pop@a);                             # push the last element of a to b
@a=(shift@b,@a);                    # unshift the first element of b to a
say                                 # output...
map{                                # map over indices of a/b
substr" .':",oct"0b$a[$_]$b[$_]",1  # convert back from binary, find right char
}0..@a                              # @a is length of a

```

Obnoxiously, `@a=(shift@b,@a)` is shorter than `unshift@a,shift@b`.

Alas, these are the same length:

```
y/ .':/0-3/;s/./sprintf'%02b ',$&/ge;
s/./sprintf'%02b ',index" .':",$&/ge;

```

Thanks to Ton Hospel for 5 bytes and msh210 for a byte!

# Answer
> 1 votes
## JavaScript (ES6), 237 210 204 188 182 178 bytes

*Credit to @Downgoat for saving 16 bytes in the 188-byte revision*

*Update: I had a brainwave and reduced the first operation on `s` to a single `map` call instead of two separate ones*

```
s=>(r=" .':",a=[],s=[...s].map(c=>(t=('00'+r.indexOf(c).toString(2)).slice(-2),a.push(t[0]),t[1])),a.splice(0,0,s.shift()),s.push(a.pop()),a.map((v,i)=>r[+('0b'+v+s[i])]).join``)

```

### Pretty Print & Explanation

```
s => (
  r = " .':", // Map of characters to their (numerical) binary representations (e.g. r[0b10] = "'")
  a = [],     // extra array needed
  // Spread `s` into an array
  s = [...s].map(c => (
    // Map each character to a `0`-padded string representation of a binary number, storing in `t`
    t = ('00' + r.indexOf(c).toString(2)).slice(-2)),
    // Put the first character of `t` into `a`
    a.push(t[0]),
    // Keep the second character for `s`
    t[1]
  )),
  // Put the first character of `s` in the first index of `a`
  a.splice(0,0,s.shift()),
  // Append the last character of `a` to `s`
  s.push(a.pop(),
  // Rejoin the characters, alternating from `a` to `s`, representing the rotated matrix, and map them back to their string representation
  // Use implicit conversion of a binary number string using +'0b<num>'
  a.map((v,i) => r[+('0b' + v + s[i])]).join``
)

```

# Answer
> 1 votes
# Vyxal, 44 bytes

```
f`:'. `f⁺↑b2ẇĿ2ẇÞT÷ḣ„ṫ$„p‟JWÞT⁺↑b2ẇ`:'. `fĿ∑

```

Try it Online!

Yuck.

# Answer
> 1 votes
# Python 3, 124 bytes

```
def f(a,s=" .':",j="".join):q=j(bin(4+s.find(i))for i in a);return j(s[int(j(x),2)]for x in zip(q[4]+q[3::5],q[9::5]+q[-2]))

```

Try it online!

## How it works :

* `q="".join(bin(4+s.find(i))for i in a)` store an unpacked version of our starting string `a` by using binary conversion

If `a` is equal to

```
ABCD
EFGH

```

then `q` is equal to `---ae---bf---cg---dh` with a to h equal to `"1"` if there is a dot in the corresponding emplacement and `"0"` otherwise (and `---` equal to `0b1`)

* `zip(q[4]+q[3::5],q[9::5]+q[-2])` reshapes `q` to have : `(eabcd),(fghd)` (the last `d` in the first part is ignored since the second part is shorter)
* `s[int("".join(x),2)]` reverse the process converting back the binary number into their dot version. Result :

```
EABC
FGHD

```

# Answer
> 1 votes
# 05AB1E, 41 bytes

```
Â)εS„':„.:‚Nèså¤ˆ¨}R¯øí˜2äćR¸ìζJC" '.:"sè

```

Try it online! Outputs as a list of characters. Link includes a footer to format the output.

```
Â)εS„':„.:‚Nèså¤ˆ¨}R¯øí˜2äćR¸ìζJC"..."sè  # trimmed program
                                       è  # push character...
                                          # (implicit) s...
                                       è  # in...
                                 "..."s   # literal...
                                       è  # at...
                                      s   # (implicit) indices in...
                              ζ           # list of elements with same indices in each element of...
                            ¸             # list of...
                          ć               # first element of...
 )                                        # list of...
Â                                         # implicit input...
 )                                        # and...
                                          # implicit input...
Â                                         # reversed...
  ε                                       # with each element replaced by...
              å¤                          # is...
             s                            # (implicit) each element of...
   S                                      # list of characters of...
                                          # (implicit) current element in map...
              å                           # in...
            ès                            # element in...
          ‚                               # list of...
    „':                                   # literal...
          ‚                               # and...
       „.:                                # literal...
            è                             # at index...
           N                              # current index in map...
                 ¨                        # excluding the last element...
                ˆ                         # and append...
               ¤                          # last element of...
              å¤                          # is...
             s                            # (implicit) each element of...
   S                                      # list of characters of...
                                          # (implicit) current element in map...
              å                           # in...
            ès                            # element in...
          ‚                               # list of...
    „':                                   # literal...
          ‚                               # and...
       „.:                                # literal...
            è                             # at index...
           N                              # current index in map...
                ˆ                         # to global array...
                   R                      # reversed...
                      í                   # with...
                    ¯                     # global array...
                     ø                    # with each element paired with corresponding element in...
                    ¯                     # global array...
                      í                   # prepended...
                       ˜                  # flattened...
                         ä                # split into...
                        2                 # literal...
                         ä                # equal pieces...
                           R              # reversed...
                             ì            # with...
 )                                        # list of...
Â                                         # implicit input...
 )                                        # and...
                                          # implicit input...
Â                                         # reversed...
  ε                                       # with each element replaced by...
              å¤                          # is...
             s                            # (implicit) each element of...
   S                                      # list of characters of...
                                          # (implicit) current element in map...
              å                           # in...
            ès                            # element in...
          ‚                               # list of...
    „':                                   # literal...
          ‚                               # and...
       „.:                                # literal...
            è                             # at index...
           N                              # current index in map...
                 ¨                        # excluding the last element...
                ˆ                         # and append...
               ¤                          # last element of...
              å¤                          # is...
             s                            # (implicit) each element of...
   S                                      # list of characters of...
                                          # (implicit) current element in map...
              å                           # in...
            ès                            # element in...
          ‚                               # list of...
    „':                                   # literal...
          ‚                               # and...
       „.:                                # literal...
            è                             # at index...
           N                              # current index in map...
                ˆ                         # to global array...
                   R                      # reversed...
                      í                   # with...
                    ¯                     # global array...
                     ø                    # with each element paired with corresponding element in...
                    ¯                     # global array...
                      í                   # prepended...
                       ˜                  # flattened...
                         ä                # split into...
                        2                 # literal...
                         ä                # equal pieces...
                          ć               # excluding the first element...
                             ì            # prepended...
                                          # (implicit) with each element...
                               J          # joined...
                                          # (implicit) with each element...
                                C         # converted from binary to decimal

```

# Answer
> 1 votes
# Python 3, ~~105~~ 104 bytes

```
s=" .':"
a=[*map(s.find,input())]
b=a[0]*2,*a,a[-1]//2
print(*map(lambda x,y:s[x&2|y&1],b,b[2:]),sep='')

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~294~~ ~~287~~ 283 bytes

Waaayyyyyy too long, but I will try to golf of some bytes:

```
z=input()
x=len(z)
M=[0,1,2,3]
for Q in M:z=z.replace(":'. "[Q],"11100100"[Q*2:Q*2+2])
a=[]
b=[]
for X in range(x):a+=[z[X*2]];b+=[z[X*2+1]]
b=b[1:]+[a.pop()]
c=[b[0]]+a
z=""
for X in range(len(c)):
 y=c[X]+b[X]
 for Q in M:y=y.replace("11100100"[Q*2:Q*2+2],":'. "[Q])
 z+=y
print(z)

```

# Answer
> 0 votes
## Lua, 139 bytes

```
print(((...):gsub(".",{[" "]="NN@",["."]="YN@",["'"]="NY@",[":"]="YY@"}):gsub("(.)@(.?)","%2%1"):gsub("..",{NN=" ",NY=".",YN="'",YY=":"})))

```

Usage:

```
$ lua conveyor.lua ".'  '.::  :.'. . ::.'  '. . .::'  :.'."
' ' .:.''..'.'. ..:' ' .'. ...'''..'.'

```

# Answer
> 0 votes
# Excel, 139 bytes

```
=LET(e,LEN(A1),q,SEQUENCE(e),x,CODE(MID(A1,q,1))-32,l,x>7,u,x>l*14,CONCAT(MID(" '.:",IF(q=1,l,INDEX(u,q-1))+IF(q=e,u,INDEX(l,q+1))*2+1,1)))

```

Link to Spreadsheet

## How it works

```
=LET(
*Assignments*
e,LEN(A1),              'e = length of A1
q,SEQUENCE(e),          'q = (1 .. e)
x,CODE(MID(A1,q,1))-32, 'x = list of ASCII codes of each character - 32
l,x>7,                  'l = array of lower numbers = 1 if x>7 (.:)
u,x>l*14,               'u = array of upper numbers = 1 if x>l*14 (':)

*Result*
IF(q=1,l,INDEX(u,q-1)) +   'String indices = if q = 1 then l[1] else u[q-1]
IF(q=e,u,INDEX(l,q+1))*2+1 '               + (if q=e then u[e] else l[q+1]) * 2 + 1
CONCAT(MID(" '.:",~,1)))   'Concatenate all the results

```

# Answer
> 0 votes
# , 55 bytes

```
' .'':'&([{~([:g@($$_1|.,)g=.|.@{:1}_2{.])&.(|:@#:)@i.)

```

Try it online!

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


title: Will the Hydra finally die?

text:
# Question
Title: Will the Hydra finally die?
### Background

A Medusa have released a dangerous Hydra which is revived unless the exact number of heads it have is removed. The knights can remove a certain number of heads with each type of attack, and each attack causes a specific amount of heads to regrow. **The knights have hired you to write a program or function that returns a truthy/falsey depending on whether the Hydra can be left with *exactly* zero heads *after* the next hit.**

Note that this is fundamentally different from Become the Hydra Slayer. You are not supposed to figure out which attacks to use.

*For example:*

```
input: head = 2,
       attacks = [1, 25, 62, 67],
       growths = [15, 15, 34, 25],
       hits = [5, 1, 0, 0]
output: TRUE

```

*Explanation:* The Hydra has 10 heads to start with, we have 4 different `attacks` and for each attack, `growth` gives us the number of heads that grows back. `hits` gives us the number of times each attack is applied. So the number of heads the Hydra has after each attack is

```
2 -> 16 -> 30 -> 44 -> 58 -> 72 -> 62

```

Since `62` is a valid attack value (It lies in the attack list), we return `True` since the Hydra will die on the next attack (be left with 0 heads). Note that the order for when the attacks are done is irrelevant.

```
2 -> 16 -> 6 -> 20 -> 34 -> 48 -> 62

```

---

### Input

Any sort of logical way of feeding your program the attack, regrowth and hit values are acceptable. This includes, but is not limited to

* A list of tuples `(1, 15, 5), (25, 15, 1) (62, 34, 0) (67, 25, 0)`
* Lists `2, [1, 25, 62, 67], [15, 15, 34, 25], [5, 1, 0, 0]`
* Reading values from STDIN `1 15 1 15 1 15 1 15 1 15 25 15`
* A file of values

---

### Output

* Some form of truthy/falsey value in your language: 0/1, true/false, etc.

---

### Assumption

* You may assume that any input is valid. E.g every input will not overkill the Hydra and either result in a number of heads that is an attack value, or not.
* Every list (if used) is to be assumed to be of equal lengths
* Every attack value will always correspond to one regrowth value which never changes. these are not required to be unique
* Every input will be a positive integer

---

### Test Cases

The following 10 examples are all `True`, and uses `attacks=[1, 25, 62, 67]`, `growths=[15, 15, 34, 25]` these are simply left out to be brief

```
1, [0, 0, 0, 0], -> True
2, [5, 1, 0, 0], -> True
3, [2, 3, 0, 0], -> True
4, [7, 4, 0, 0], -> True
5, [4, 6, 0, 0], -> True
6, [4, 0, 0, 0], -> True
7, [1, 2, 0, 0], -> True
8, [6, 3, 0, 0], -> True
9, [3, 5, 0, 0], -> True
10, [8, 6, 0, 0] -> True
25, [0, 0, 0, 0], -> True
67, [0, 0, 0, 0], -> True
62, [0, 0, 0, 0], -> True
98767893, [0, 1, 1, 2351614] -> True

```

The following examples are all `False`, and uses `attack=[1, 25, 62, 67]`, `growth=[15, 15, 34, 25]` these are simply left out to be brief

```
65, [0, 3, 0, 0], -> False
66, [4, 5, 0, 0], -> False
68, [0, 2, 0, 0], -> False
69, [0, 1, 1, 0], -> False
70, [2, 5, 0, 0], -> False
71, [0, 0, 0, 1], -> False
72, [0, 0, 0, 0], -> False
73, [1, 2, 1, 0], -> False
74, [2, 3, 0, 0], -> False
75, [1, 5, 0, 0], -> False
98767893, [1, 1, 1, 2351614] -> False

```

This is a question so answers will be scored in bytes, with fewer bytes being better.

# Answer
# Vyxal, 5 bytes

```
-*∑+c

```

Try it Online!

Inputs: attacks, growths, hits, heads

## Explanation

`-` subtract: growths - attacks
`*` multiply: that * hits
sum
`+` add: that + heads
`c` contains: is it in attacks?
> 3 votes

# Answer
# Haskell, 44 bytes

```
w=zipWith
(u#z)y=elem=<<sum.(u:).w(*)z.w(-)y

```

Try it online!

Pretty simple. We get the differences of the attacks and the regrows with `zipWith(-)`, then we multiply these by the attacks taken `zipWith(*)z`. Then we sum that with the starting head count, and check if that is in the attack list.
> 6 votes

# Answer
# Python 3, 56 bytes

Try it online!

```
lambda h,a,g,t:h+sum(z*(x-y)for x,y,z in zip(g,a,t))in a

```
> 3 votes

# Answer
# , 36 bytes

```
function(H,a,g,h)sum(H,g*h-a*h)%in%a

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~7~~ 6 bytes

```
_ḋ⁵⁶+e

```

Try it online!

Takes four arguments: growths, attacks, hits, heads.

## Explanation

```
_ḋ⁵⁶+e Main dyadic link
_      Subtract: growths - attacks
 ḋ     Dot product with
  ⁵      third argument: hits
    +  Add
   ⁶     fourth argument: heads
     e Is it an element of the second argument: attacks?

```
> 3 votes

# Answer
# JavaScript (ES6), 54 bytes

Returns a Boolean value.

```
(a,g,n,h)=>a.includes(h.map((v,i)=>n+=v*=g[i]-a[i])|n)

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 22 bytes

```
FreeQ[#,#3-#4.(#-#2)]&

```

Try it online!

Input `[attacks, growths, hits, head]`. Returns `True` if the hydra cannot be slain on the next hit.
> 2 votes

# Answer
# Charcoal, 16 bytes

```
№η⁺θΣＥε×ι⁻§ζκ§ηκ

```

Try it online! Link is to verbose version of code. Outputs one `-` for each matching attack, so if there are two attacks that deal the same amount of damage then `--` will be output. Explanation:

```
      ε             Array of hits
     Ｅ              Map over elements
          §ζκ       Relevant growth
         ⁻          Subtract
             §ηκ    Relevant attack
       ×            Multiplied by
        ι           Current element
    Σ               Take the sum
  ⁺θ                Add the starting number of heads
№η                  Output the number of matching attacks

```
> 1 votes

# Answer
# , 15 bytes

Just to remind myself that `/` supports cycling gerunds. Takes health on the left, (hits, regrow, attack) on the right.

```
(+1#.*`-/)e.2{]

```

Try it online!

* `*`-/` Does hits * regrow - attack
* `1#.` summed
* `+` plus health
* `e.2{]` exists in the attacks?
> 1 votes

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


title: Rotated Position of Integers

text:
# Question
Title: Rotated Position of Integers
## Challenge:

### Input:

A sorted list of positive integers.

### Output:

The amount of integers which are still at the exact same index, after rotating the digits in each integer its index amount of times towards the left and sorting the modified list again.

**Example:**

Input: `[8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]`
Output (0-based indexing): `6`
Output (1-based indexing): `5`

*Why?*

0-based indexing:

```
After rotating each: [8,94,73,102,592,276,8227,3338,9217,63784,89487,7887471]
Sorted again:        [8,73,94,102,276,592,3338,8227,9217,63784,89487,7887471]

Input indices:        0  1  2   3   4   5    6    7    8     9    10      11
Original input-list: [8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]
Modified list:       [8,73,94,102,276,592,3338,8227,9217,63784,89487,7887471]
Modified indices:     0  2  1   3   5   4    7    6    8     9    10      11
Equal indices:        ^         ^                      ^     ^     ^       ^

So the output is: 6

```

1-based indexing:

```
After rotating each: [8,49,37,021,925,762,2278,3383,2179,37846,94878,8874717]
Sorted again:        [8,(0)21,37,49,762,925,2179,2278,3383,37846,94878,8874717]

Input indices:        1  2  3   4   5   6    7    8    9    10    11      12
Original input-list: [8,49,73,102,259,762,2782,3383,9217,37846,89487,7471788]
Modified list:       [8,21,37,49,762,925,2179,2278,3383,37846,94878,8874717]
Modified indices:     1  4  3  2   6   5    9    7    8    10    11      12
Equal indices:        ^     ^                               ^     ^       ^

So the output is: 5

```

## Challenge rules:

* The input-list is guaranteed to only contain positive integers.
* The input-list is guaranteed to be sorted from lowest to highest.
* The input-list is guaranteed to contain at least two items.
* As you can see above, both 0-based and 1-based indexing is allowed. **Please state in your answer which of the two you've used, since outputs can differ accordingly!**
* Leading `0`s after rotating are ignored, which can be seen with the 1-based example above, where the integer `102` becomes `021` after rotating, and is then treated as `21`.
* Integers are guaranteed unique in the input-list, and are guaranteed to remain unique after the rotations are completed.
* Note that we only look at the positions of the rotated integers in correlation with the positions of the input, not with the values of the input-list. To clarify what I mean by this: with the input-list `[1234,3412]` and 1-based indexing, the list becomes `[2341,1234]` after rotating each integer it's index amount of times, and then when sorted becomes `[1234,2341]`. Although both the original input-list and the rotated list contains the integer `1234` at the leading position, they aren't the same! The rotated `1234` was `3412` before. The 1-indexed output for this input-list is therefore `0`, since the two integers have swapped their positions.
* Input is flexible. Can be a list/stream/array of integers/strings/digit-arrays, etc. Please state what you've used if you don't take the inputs as integers.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input: [8, 49, 73, 102, 259, 762, 2782, 3383, 9217, 37846, 89487, 7471788]
0-based output: 6
1-based output: 5

Input: [1234, 3412]
0-based output: 2
1-based output: 0

Input: [2349, 2820, 17499, 21244, 29842, 31857, 46645, 56675, 61643, 61787]
0-based output: 3
1-based output: 0

Input: [4976, 11087, 18732, 22643, 52735]
0-based output: 2
1-based output: 3

Input: [4414, 5866, 7175, 8929, 14048, 16228, 16809, 19166, 24408, 25220, 29333, 44274, 47275, 47518, 53355]
0-based output: 4
1-based output: 4

Input: [11205, 16820, 63494]
0-based output: 1
1-based output: 3

```

Feel free to generate more random test cases with (or draw inspiration from) this ungolfed 05AB1E program, where the input is the size of the random list (NOTE: the output of this generator might not comply with the rule "*Integers are guaranteed unique in the input-list, and are guaranteed to remain unique after the rotations are completed*", so keep that in mind when using it.)

# Answer
> 11 votes
# , ~~114~~ 107 bytes

-5 bytes thanks to Giuseppe.

Outgolfed by digEmAll.

```
function(l){for(j in seq(l))l[j]=rep(l[j]%/%(e=10^(b=nchar(l[j]):1-1))%%10,j+1)[j+0:b]%*%e
sum(sort(l)==l)}

```

Try it online!

0-indexed.

Ungolfed version:

```
function(l) {
  n = length(l)                         # size of input
  for (j in 1:n) {
    b = nchar(l[j]) -1                  # number of digits in l[j] -1
    e = 10 ^ (b:0)
    d = l[j] %/% e %% 10                # convert to vector of digits
    l[j] = rep(d, j + 1)[j + 0:b] %*% e # rotate digits and convert back to an integer
  }
  sum(sort(l) == l)                     # number of integers which are in the same position
}

```

To rotate the `b` digits of an integer by `j` positions, the code repeats the digits many times, then takes the digits in positions `j+1` to `j+b`. For instance, to rotate `102` 4 times, keep the values marked with an `x` (positions 5 to 7):

```
102102102102
    xxx

```

so the result is `021`.

# Answer
> 6 votes
# 05AB1E, 9 bytes

```
ΣN._ï}-_O

```

Try it online!

Uses 0-based indexing.

Explanation:

```
Σ    }       # sort the input by
 N._         # each number rotated its index to the left
    ï        # then cast to int (otherwise the sort is alphabetic)
      -      # subtract the input from the result
       _O    # then count the 0s

```

# Answer
> 6 votes
# Japt `-x`, ~~10~~ 9 bytes

0-based

```
í¶UñÈséYn

```

Try it

```
í¶UñÈséYn     :Implicit input of integer array U
í             :Interleave with
  Uñ          :U sorted by
    È         :Passing each integer at 0-based index Y through the following function
     s        :  Convert to string
      é       :  Rotate right by
       Yn     :    Y negated
 ¶            :Reduce each pair by testing for equality
              :Implicit output of sum of resulting array

```

# Answer
> 4 votes
# Python 2, ~~104~~ ~~100~~ ~~97~~ 93 bytes

```
b=[int((s*-~i)[i:i+len(s)])for i,s in enumerate(input())]
print map(cmp,b,sorted(b)).count(0)

```

Try it online!

0-based indexing.

First rotates each number, and then compares the result with result, but sorted.

---

Saved:

* -3 bytes, thanks to Erik the Outgolfer
* -4 bytes, thanks to Kevin Cruijssen (and his rule-change)

# Answer
> 4 votes
# Jelly, 9 bytes

```
Dṙ"JḌỤ=JS

```

Try it online!

Monadic link that takes a list of integers and returns an integer indicating the number of integers that remain in place after performing the rotation using 1-indexing.

### Explanation

```
D         | Convert to decimal digits
 ṙ"J      | Rotate left by index
    Ḍ     | Convert back to integer
     Ụ    | Index in sorted list
      =J  | Check if equal to index in original list
        S | Sum

```

# Answer
> 4 votes
# , ~~90~~ ~~88~~ 85 bytes

```
function(x)sum(rank(as.double(substr(strrep(x,L<-sum(x|1)),y<-1:L,y+nchar(x)-1)))==y)

```

Try it online!

* 0-indexed rotation
* rotation strategy inspired by @RobinRyder's answer
* -5 bytes thanks to @Giuseppe

### Unrolled code with explanation :

```
function(x){
    L=sum(x|1)                         # store the length of x

    R=strrep(x,L)                      # repeat each string of vector x L times

    S=substring(R,1:L,1:L+nchar(x)-1)) # for each string of R, extract a substring of the same
                                       # length of the original number starting from index 1
                                       # for the 1st element, index 2 for the 2nd and so on
                                       # (this basically rotates the strings )

    Y=as.double(S)                     # convert the strings to numbers

    sum(rank(Y)==1:L)                  # return the number of times the ranks of Y
                                       # match with their original positions
}

```

# Answer
> 3 votes
# , ~~28~~ 26 bytes

-2 bytes thanks to Jonah

```
1#.i.@#=[:/:#\".@|.&>":&.>

```

Try it online!

# Answer
> 2 votes
# Pyth, 15 bytes

```
sqVSJ.ev.<`bkQJ

```

Try it online! Uses 0-based indexing.

```
sqVSJ.ev.<`bkQJ   Implicit: Q=eval(input())
     .e      Q    Map elements of Q, as b and with index k, using:
          `b        Convert b to string
        .<  k       Rotate the above left k places
       v            Convert back to integer
    J             Store the above as J
   S              Sort the above
 qV           J   Vectorised equality check with the unsorted list
s                 Sum, implicit output

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~107~~ ~~99~~ 95 bytes

-8 bytes Thanks @Shaggy for accepting array of strings instead. Further golfed 4 bytes from this. Will not trigger memory error this time.

```
a=>[...b=a.map(F=(x,i)=>i--?F(x.slice(1)+x[c=0],i):x)].sort((p,q)=>q-p).map(x=>c+=x==b.pop())|c

```

Try it online!

# JavaScript (Node.js), ~~111~~ 107 bytes

-4 bytes Thanks @Arnauld!

```
a=>[...b=a.map((x,i)=>"".padEnd(x+i,x+=c='').substr(i,x.length))].sort((p,q)=>q-p).map(x=>c-=x==b.pop())|-c

```

Try it online!

# JavaScript (Node.js), ~~113~~ 111 bytes

```
a=>[...b=a.map((x,i)=>"".padEnd(x+i,x).substr(i,`${x}`.length))].sort((p,q)=>p-q).map((x,i)=>x-b[i]||c++,c=0)|c

```

Try it online!

0-indexed. May trigger memory error for very large entries.

# Answer
> 2 votes
# APL+WIN, ~~23, 21~~ 19 bytes

2 bytes saved by inputting the integers as a nested vector of characters

```
+/i=⍋⍎¨(i←⍳⍴v)⌽¨v←⎕

```

1 indexed.

```
v←⎕ prompt for input.

(i←⍳⍴v)⌽¨ rotate each set of characters by input indices.

⍋⍎¨ convert characters to integers and get sorted indices.

+/i= sum where original and sorted indices are the same.

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# PHP, ~~159~~ ~~141~~ ~~134~~ 130 bytes

```
function($a){foreach($a as$x){for($j=$i;$j--;$x=substr($x,1).$x[0]);$b[$x]=$i++;}ksort($b);foreach($b as$z)$y+=++$j==$z;return$y;}

```

Try it online!

Zero-based indexing.

***Ungolfed:***

```
function( $a ) {
    // iterate through digits
    foreach( $a as $x ) {
        // rotate the digits the number of times based on their index
        for( $j = $i; $j--; ) {
            // move first digit to last digit
            $x = substr( $x, 1 ) . $x[0];
        }
        // the new number is used as key for sort, value is the original index
        $b[ $x ] = $i++;
    }
    // sort by the new numbers
    ksort( $b );
    // iterate sorted array
    foreach( $b as $z ) {
        // if new index matches original index, increment count ($y)
        if ( ++$j == $z ) {
            $y++;
        }
    }
    return $y;
}

```
* -4 bytes taking input as array of strings, thx to @KevinCruijssen for pointing that out.

# Answer
> 2 votes
# Stax, ~~11~~ 10 bytes

```
ìát'óJ♣á◄·

```

Run and debug it

This program uses 0-based indexing and takes input as an array of strings. I saved a byte by taking opportunity of the new input clarificatinos.

# Answer
> 2 votes
# Perl 5 `-pa`, 80 bytes

```
map$d{$_.substr$_,0,$b%y///c,''}=$b++,@F;$\+=$d{$_}==$r++for sort{$a-$b}keys%d}{

```

Try it online!

Takes input as space separated numbers on STDIN; gives 1-based result.

# Answer
> 2 votes
# K (Kona), ~~25~~ 21bytes

-4 bytes thanks to ngn!

```
{+/t=<.:'(t:!#x)!'$x}

```

Try it online!

# Answer
> 2 votes
# T-SQL query, 99 bytes

Sql has no rotating method, so I had to implement my own syntax, since this is a query, it had to be done without looping.

0-based indexing.

Using a table variable as input.

```
SELECT-sum(1/~(z*3))FROM(SELECT~i+rank()over(order by
substring(n+n,i%len(n)+1,len(n))*1)z FROM @)c

```

**Try it online**

# Answer
> 2 votes
# Perl 6, 50 bytes

```
{sum ^$_ Z==sort {+[~] rotate .[$^i].comb,$i},^$_}

```

Try it online!

0-based indexing. Also exposed a Rakudo bug.

### Explanation

```
{                                                }  # Anonymous block
            sort                              ^$_   # Sort indices 0..n
                 {                          },  # by
                              .[$^i]            # element at index i
                                    .comb       # split into chars
                       rotate            ,$i    # rotated i times
                   [~]  # joined
                  +     # converted to number
     ^$_ Z==  # Pairwise equal to original indices 0..n
 sum   # Sum of equal indices

```

# Answer
> 1 votes
# Icon, 141 bytes

```
procedure f(l)
n:=0
b:=[]
t:=l[k:=1to*l]&m:=k%*t&t:=t[m+1:0]||t[1:m+1]&put(b,[+t,l[k]])&\x
l[i:=1to*l]=sortf(b,1)[i,2]&n+:=1&\x
return n
end

```

Try it online!

1-based indexing

# Answer
> 1 votes
# Perl 5, 104 bytes

```
sub f{my$i;grep/\d+$/&&$i++==$&,sort{$a<=>$b}map{my$n=shift;map$n=~s/(.)(.+)/$2$1/,1..$_;"$n.$_"}0..$#_}

```

Try it online!

0-based indexing in Perl. Ungolfed and commented:

```
sub f {
  my $i;                            #index counter
  grep /\d+$/ && $i++==$&,          #keep/return elems where $i matches original index stored as decimals
  sort { $a<=>$b }                  #sort rotated elems numerically (<=> is the numerical comparison op
  map {                             #loop through input
    my $n = shift;                  #shift(@_) got elem from input array @_
    map $n=~s/(.)(.+)/$2$1/, 1..$_; #rotate left times current index
    "$n.$_"                         #use rotated number with original index number as decimals (to dont affect sort)
  }
  0..$#_
}

```

# Answer
> 1 votes
# Ruby `-ap`, 77 bytes

1-indexed. Was temp deleted earlier because I missed part of the spec.

`-p` reads a line of STDIN, and outputs `$_` at the end. `-a` splits that read line by spaces and saves it as `$F`.

```
i=0
$_=$F.zip($F.sort_by{|s|s.chars.rotate(i+=1).join.to_i}).count{|a,b|a==b}

```

Try it online!

# Answer
> 1 votes
# Scala, ~~200~~ 160 bytes

```
def f(a:Seq[String])=
  a.zipWithIndex
   .map(x=>{val r=x._2%x._1.size;x._1.drop(r)+x._1.take(r)->x._2})
   .sortBy(_._1.toInt)
   .zipWithIndex
   .filter(x=>x._1._2==x._2)
   .size

```

Try it online!

0-indexed. 160 chars after removing indentation and newlines. This prints 6:

```
println( f(Seq("8","49","73","102","259","762","2782","3383","9217","37846","89487","7471788")) )

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 65 bytes

```
o=Ordering
g=Count[o@MapIndexed[FromDigits@*RotateLeft,#]-o@#,0]&

```

Try it online!

1-based. We take the input as a list of digit lists, which works because Mathematica orders lists by length, then lexicographically, i.e. just like the original numbers.

# Answer
> 1 votes
# Bash, 204 201 bytes

The only interesting thing here (possibly) is the use of `eval`. The algorithm is also clunky in that it creates a sorted list then reads it in order to determine changed index/indices.

1-based solution. My thanks to @RobinRyder for the helpful rotation algorithm.

```
for((i=1;i<$#+1;i++));do eval s=\${$i};for((j=0;j<i;j++));do eval s=${s}\${$i};done;eval n=\${s:$i:\${#$i}};echo $n $i;done|sort -nk1,1|{ i=1;c=0;while read d j;do((i==j))&&((c++));((i++));done;echo $c; }

```

Try it online!

Revised code following Kevin's comments; Try it online!

# Answer
> 1 votes
# Vyxal, 12 bytes

```
µ¥Ǔ&›₀β;=';L

```

Try it Online!

```
µ      ;     # Sort by...
 ¥           # Register
  Ǔ          # Shift right by
   &›        # Increment register
     ₀β      # Cast to int
        =';L # Find those where they're equal

```

---
Tags: code-golf, number, integer, sorting
---


title: Chasing the car

text:
# Question
Title: Chasing the car
Imagine you are sitting at a park. Suddenly your car gets hijacked and being driven in different directions. Here are the directions, arrows show which direction goes towards where:

```
     South
       |
       V
East->   <-West
       ^
       |
     North

```

After being driven, the car stops. Now you have to find out how far the car is away from you and angle of you and your car in degrees. It will be given how many units have been driven and in which direction. Input/Output format is flexible, you can take a 2D list/1D list/string etc and return the displacement and angle.

**Test Cases**

```
[[40,East],[40,North],[30,West],[30,South]] -> 14.1421356237 45.0
[[45,North],[200,East]] -> 205.0 75.9637565321

```

No need to output exact angle and distance, just 2 digits after decimal is fine, but more than 2 is fine too.

Only given directions are North, east, south, west.

The value of movement in a direction is always positive integer.

Trailing Whitespace allowed. Code golf, so shortest code wins.

*My English is bad, sorry. Please ask for clarification if you have trouble understand ing*

# Answer
> 3 votes
# Ruby, 44 bytes

```
->l{z=l.sum{|a,b|a*b};[z.abs,z.arg*57.2958]}

```

Try it online!

Input direction as:

* 1i East
* 1 North
* -1i West
* -1 South

# Answer
> 3 votes
# Python 3, 77 bytes

```
lambda a:(abs(v:=(sum(x*d for x,d in a))),phase(v)*180/pi)
from cmath import*
```

Attempt This Online!

Takes the direction as a complex number: `1`, `-1`, `1j`, or `-1j` for east, west, north, and south respectively.

---

# Python 2, 74 bytes

Thanks to @xnor

```
from cmath import*
m,t=polar(sum(x*d for x,d in input()))
print m,t*180/pi
```

Attempt This Online!

Full program taking input as a list from STDIN with directions as above.

# Answer
> 3 votes
# APL (Dyalog Unicode), 18 bytes

Anonymous tacit infix function, taking a list of complex units as one argument and the magnitudes as another argument.

```
(|,{180÷○÷12○⍵})+.×

```

Try it online!

`+.×` dot product, i.e. sum of products of directions and magnitudes

`(``)` apply the following tacit function to that:

`{``}` apply the following lambda to that;  is the argument:

`12○⍵` the phase (i.e. angle)

`÷` reciprocal of that

*π* times that

`180÷` 180 divided by that

`|,` prepend the absolute value

---

If we were allowed to answer in radians, the solution would be just:

```
10 12○+.×

```

Try it online!

`+.×` dot product, i.e. sum of products of directions and magnitudes

`10 12○` magnitude and phase of that

# Answer
> 2 votes
# Python 2, 115 bytes

```
x=y=0;from math import*
for u,d in input():exec('x+=u y+=u x-=u y-=u'.split()[d])
print hypot(x,y),atan(x/y)*180/pi

```

Try it online!

Straightforward approach. Full program. Takes input as a 2D list, 0 for East, 1 for North, 2 for West, 3 for South.

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