# Question
Title: Fill the maze with a wall-following Snake until it gets stuck
Make a snake fill any maze (until it gets stuck).

## The snake

The snake starts at a given starting point, pointing **EAST**. It moves by always having a wall or a part of its body immediately to the **LEFT** of its head ("*left-hand rule wall follower*"), until it gets stuck because all four directions around its head are occupied. (Note: a stuck snake can possibly not fill all the reachable space, but that is not the goal!)

## The challenge

Write a program or function that accepts a maze as input in the form of a 2D text:

* The input can be in any reasonable format: e.g. a list of strings, a single string with newlines, a file.
* The maze has walls ("`#`"), empty spaces ("") and exactly one starting point ("`o`").
* You can choose to

+ either assume that the first and last row and column are entirely walls;
    + or assume that every input is considered to have an *implicit* outer layer of walls
* You can assume that the starting point has a wall (or an implicit wall) directly above it (NORTH) and that the snake can make a valid starting move in the EAST or SOUTH direction.
* You can assume that no other characters are present in the text (except newlines if your input needs them).
* You can assume that all lines are the same length.

and prints / returns a "filled maze" as output, with **a snapshot of the snake at the moment it got stuck**:

* The body of the snake is represented by the characters `>v<^` pointing to where its **next** segment is
* The starting point of the snake is either its direction at the start ("`>`" unless it had to turn immediately) or an `o` character (no need to be consistent)
* The end point of the snake is an `o` character

## Scoring

Usual code golf: the shortest code wins

## Example

```
in:
#################################
#                    o          #
#                               #
#     ##       ###       ##     #
#    ##     ##     ##     ##    #
#    ##     ##     ##     ##    #
#    ##      ##   ##      ##    #
#   ##       ##   ##       ##   #
#   ##         ###         ##   #
#    ##       #####       ##    #
#    ##       #####       ##    #
#    ##        ###        ##    #
#     ##                 ##     #
#                               #
#                               #
#################################

out:
#################################
#>>>>>>>>>>>>>>>>>>>v>>>>>>>>>>v#
#^>>>>>>>>>>>>>>>>>v>>>>>>>>>>vv#
#^^   ##>>>>>>v###o>>>>>v##   vv#
#^^  ##>^   ##>>>>^##   >v##  vv#
#^^  ##^    ##     ##    v##  vv#
#^^  ##^     ##   ##     v##  vv#
#^^ ##>^     ##   ##     >v## vv#
#^^ ##^<       ###       v<## vv#
#^^  ##^      #####      v##  vv#
#^^  ##^      #####      v##  vv#
#^^  ##^<      ###      v<##  vv#
#^^   ##^<<<<<<<<<<<<<<<<##   vv#
#^^<<<<<<<<<<<<<<<<<<<<<<<<<<<<v#
#^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<#
#################################

```

**Animated (for illustration purposes):**

Edit: note that, when in doubt, the snake should "keep its left hand" on the wall it is already on, following corners, not jumping to a wall 1-block away.

Thanks Jonathan Allan for bringing it up, and Draco18s for the explanatory snapshot above.

### Other examples

```
in:
####################
#               o# #
#                ###
#                  #
#      ##          #
#                ###
####################

out:
####################
#>>>>>>>>>>>>>>vv# #
#^>>>>>>>>>>>>vvv###
#^^   v<<<o<<<<v>>v#
#^^<<<<##^<<<<<<v<<#
#^<<<<<<<<<<<<<<<###
####################

```

```
in:
####################
#         o    #####
#              #####
#                  #
#                 ##
####################

out:
####################
#         >>>>v#####
#             v#####
#             >>>>o#
#                 ##
####################

```

```
in:
################
#o             #
#   ########## #
# #          # #
# #          # #
# #          # #
# #  #       # #
# #          # #
# #          # #
# #          # #
# ############ #
#              #
################

out:
################
#>>>>>>>>>>>>>v#
#>>v##########v#
#^#>>>>>>>>>v#v#
#^#>>>>>>>>vv#v#
#^#^>>>>>>vvv#v#
#^#^^#    vvv#v#
#^#^^o<<<<<vv#v#
#^#^^<<<<<<<v#v#
#^#^<<<<<<<<<#v#
#^############v#
#^<<<<<<<<<<<<<#
################

```

# Answer
# Charcoal, ~~94~~ 68 bytes

```
Ｆ²⊞υＳＷ¬⁼§υ⁰§υ±¹⊞υＳ≔⪫υ¶θＰθ…θ⌕θo≔⁰θＷ№ＫＶ «≧⁺⊖⌕Ｅ³§ＫＶ⁺θκ θ✳§rdluθ§>v<^θ»o

```

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

```
Ｆ²⊞υＳＷ¬⁼§υ⁰§υ±¹⊞υＳ≔⪫υ¶θ

```

Slurp the input into a string. This could be avoided by using a less convenient input format.

```
Ｐθ…θ⌕θo

```

Print the input without moving the cursor, and then print up to the `o` again, so that the cursor ends up under it.

```
≔⁰θ

```

Initialise the current direction.

```
Ｗ№ＫＶ «

```

Repeat while there's still a free space in some direction.

```
≧⁺⊖⌕Ｅ³§ＫＶ⁺θκ θ

```

Calculate whether the snake can turn left, or whether it is forced to turn right. The code `≦⊖θＷ¬⁼§ＫＶθ ≦⊕θ` also works for this for the same byte count although it considers `0` as up instead of right so the rest of the code needs to be adapted.

```
✳§rdluθ§>v<^θ

```

Output the appropriate body character in the appropriate direction.

```
»o

```

Restore the head. This can also be written as `Ｐo` which prints the head without moving the cursor each pass through the loop instead (but this allows the loop to be implicitly closed for the same byte count).
> 8 votes

# Answer
# Python 2, ~~273~~ ~~253~~ 242 bytes

<sup>-11 bytes thanks to ArBo</sup>

```
g=input()
d=0
t=lambda g,k=1:'\n'.join(map(''.join,zip(*g.split('\n')[::k])[::-k]))
h='o '
while 1:
 l,r=t(g,-1),t(g)
 if h in l:g=l;d-=1
 elif h in g:g=g.replace(h,'>v<^'[d%4]+'o')
 elif h in r:g=r;d+=1
 else:break
exec-d%4*'g=t(g);'
print g

```

Try it online!

This working by searching the string `'o '`, and replacing it by `'[>v<^]o'`, if it is in the maze.

The same check will also be made on the rotated maze, printing the filled maze when the string isn't there anymore.

The function `t=lambda g,k=1:'\n'.join(map(j,zip(*g.split('\n')[::k])[::-k]))` is used to rotate the grid
> 7 votes

# Answer
# Ruby, ~~126~~ 118 bytes

*-8 bytes saved by abusing `+=` instead of manually searching for `o` again after repositioning it.*

```
->s{d=[q=1,1+l=s=~/$/,-1,~l];i=s=~/o/;(s[i]=">v<^"[q];s[i+=d[q]]=?o)while q=[~-q%4,q,-~q%4].find{|e|s[i+d[e]]==' '};s}

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~72~~ 56 bytes

```
œṣ€⁾o j€ṛị“v<^>”;”oʋ,
UZ$ṛ¡+ƭ€Ɱ3r5¤ç/€ḟ$Ḣß$ṛ¹?
,0ÇZU$ṛ¡/

```

Try it online!

A full program that takes the input as a list of strings and returns a list of strings with the final snake. Note the footer on TIO converts a single newline separated string into the desired input and restores the newlines at the end; this is merely for convenience.

Solution somewhat inspired by the method used by @Rod’s Python 2 answer, though implementation is very different.
> 3 votes

# Answer
# T-SQL 2008 query, ~~373~~ ~~371~~ 366 bytes

I had a priority list, always slither left, straight, right. I changed that priority to always slither back, left, straight, right. Slithering back will always be blocked, so the priority is still the same except the first slither. By turning the snake down initially (C=4), it attempts to slithering up when backslithering. This little stunt saved me 2 bytes. Because I didn't need to add 1 to ~-~-c%4.

I inserted 2 line breaks to make it readable

```
DECLARE @ varchar(8000)=
'################
#o             #
#   ########## #
# #          # #
# #          # #
# #          # #
# #  #       # #
# #          # #
# #          # #
# #          # #
# ############ #
#              #
################';

WITH s as(SELECT 0i,4c,@ m
UNION ALL
SELECT~-i,x,stuff(stuff(m,~-a+x/3*2+(x-3)%2*s,1,'o')
,a,1,char(59+x+~x%2*11*~x))FROM(SELECT
charindex(' ',replicate(stuff(substring(m,~-a,3),2,1,substring(m,a+~s,1))+
substring(m,a-~s,1)+'~',2),-~-~c%4)%5x,*FROM(SELECT*,charindex('o',m)a,charindex('
',M)S FROM S)Q)L
WHERE x>0)SELECT top 1m FROM s
ORDER BY i
OPTION(MAXRECURSION 0)

```

I had to make some minor adjustments to execute this online, the posted version runs in MS-SQL server management studio.

Push Ctrl-T before execute in MS-SQL server management studio, this will show result as text.

**Try it online**
> 3 votes

# Answer
# Python 3, 343 bytes

```
import sys
X=0,1,0,-1
F,*Y=*X,0
L=3
g=[*map(list,sys.stdin.read().split("\n"))]
e=enumerate
r,c=[[r,c]for r,R in e(g)for c,C in e(R)if"o"==C][0]
while 1:
	if" "==g[r+X[L]][c+Y[L]]:F,L=L,~-L%4
	elif" "<g[r+X[F]][c+Y[F]]:
		if" "<g[r-X[L]][c-Y[L]]:g[r][c]="o";break
		L,F=F,-~F%4
	g[r][c]=">v<^"[F];r,c=r+X[F],c+Y[F]
for r in g:print("".join(r))

```

Try it online!

-11 bytes thanks to ArBo
-4 bytes thanks to Jonathan Frech
> 1 votes

# Answer
# 05AB1E, ~~54~~ 52 bytes

```
[S¶¡øí3FDíø})J€»¼D¾èU¼.Δ.¼„o ©å}DÄiXqë®">^<v"¾è'o«.;

```

I/O both as a single multi-line string.

Try it online or verify all test cases.

**Explanation:**

```
[                      # Start an infinite loop:
 S                     #  Split the multi-line string into a list of characters
                       #  (which will use the implicit input in the first iteration)
  ¶¡                   #  Then split by newlines
    øí                 #  Rotate the matrix once clockwise
      3F               #  Loop 3 times:
        D              #   Create a copy of the matrix
         íø            #   And rotate this copy once counterclockwise
       })              #  After the loop: wrap all four matrices into a list
 J                     #  Join each inner-most character-list to string-lines again
  €»                   #  And join each inner list of lines by newlines again
    ¼                  #  Increase variable `c` by 1 (variable `c` is 0 by default)
     D¾<è              #  Index the updated variable `c` in a copy of the list of matrices
                       #  (note that indexing wraps around in 05AB1E)
         U             #  Pop and store it in variable `X`
    ¼                  #  Then increase variable `c` again
    .Δ                 #  Find the first multi-line string in the list which is truthy for:
      .¼               #   Decrease variable `c` by 1 first
        „o             #   Push string "o "
           ©           #   Store this string in variable `®` (without popping)
            å          #   Check if the current multi-line string contains this "o "
    }D                 #  Duplicate the result (results in -1 if none were truthy/found)
      Äi               #  If no result was found:
        X              #   Push variable `X`
         q             #   And stop the program, after which this multi-line string of
                       #   variable `X` is output implicitly as result
       ë               #  Else:
         ">^<v"¾è      #   Get the `c`'th character in string ">^<v"
                       #   (note that indexing wraps around in 05AB1E)
                 'o«  '#   Append a trailing "o" to this character
        ®           .; #   And replace the first variable `®` ("o ") in the
                       #   multi-line string with this

```
> 1 votes

# Answer
# Pyth, 161 bytes

```
J.zK[Z1Z_1)=Y+tKZVlJFTl@JNIq@@JNT\oA[NT;=N3=TZ#Iq@@J+G@KN+H@YNd=TN=N%tN4.?In@@J+G@KT+H@YTdIn@@J-G@KN-H@YNd XJGX@JGH\oB=NT=T%hT4)) XJGX@JGH@">v<^"TA(+G@KT+H@YT;jJ

```

Try it online!

Port of HyperNeutrino's Python 3 solution. Now that I'm done with it, I'm thinking maybe I should have ported Rod's Python 2 solution instead, but I already spent way too much time on this.
> 0 votes

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


title: Golfing with Python Import

text:
# Question
Title: Golfing with Python Import
When is it beneficial to use inline, single use importing in Python?

For example:

```
__import__("x").doSomething()

```

Is the above ever shorter than the below?

```
import x
x.doSomething()

```

Or

```
from x import*
doSomething()

```

# Answer
> 12 votes
This can be useful if you want to use a module just once in an anonymous lambda function, as it allows you to avoid writing a separate statement:

```
lambda x:__import__('SomeModule').foo(x,123)

```

is one byte shorter than

```
from SomeModule import*;f=lambda x:foo(x,123)

```

If the code is a named function or program, then `__import__` is unlikely to help except in the most extreme or contrived circumstances.

# Answer
> 6 votes
When importing multiple modules with sufficiently long names, it can be helpful to assign the `__import__` function to a shorter variable and use it for imports

### Example:

Regular import statements - 97 bytes

```
from itertools import*
from datetime import*
print list(permutations("abc"))
print datetime.now()

```

Assigning `__import__` to `i` \- 94 bytes:

```
i=__import__
print list(i("itertools").permutations("abc"))
print i("datetime").datetime.now()

```

# Answer
> 1 votes
### Almost never.

`__import__("x").doSomething()` needs 15+*x* characters to refer to a module with a name of length *x*.

`import x\nx.doSomething()` needs 9+2\**x* characters. These functions overlap at *x*=6, so compared to this way any module with a longer name is better off using `__import__`, anything shorter benefits from normal imports:

However, `from x import*\ndoSomething()` needs only 14+*x* characters, so compared to the normal import it is not worth it unless the module name is longer than 5 characters:

This all assumes that you are referring to a function/class/whatever only once. If you refer to it more than once, the formulas change, and the latter version might become the winner. In case you use something long from an imported module several times, yet another version wins:

`from x import y as z` nets you 18+*x*+*y*+*z*\*(*n*+1) characters for *n* uses of *z*, which is a large improvement if *y* is big, because *z* can be made 1.

---
Tags: code-golf, tips, python
---


title: Subtract the Folded Matrix

text:
# Question
Title: Subtract the Folded Matrix
## Challenge:

Given an NxN matrix where \\$N\geq2\\$ and one of eight distinct 'folding options', output a 2D array/list with the subtracted values.

The eight folding options are: left-to-right; right-to-left; top-to-bottom; bottom-to-top; topleft-to-bottomright; topright-to-bottomleft; bottomleft-to-topright; bottomright-to-topleft.

**Step by step examples:**

Input matrix:

```
[[ 1, 3, 5, 7],
 [ 0, 8, 6, 4],
 [ 1, 1, 1, 1],  (a'th row in the explanation below)
 [ 1,25, 0,75]]

```

With folding option top-to-bottom we output the following as result:

```
[[ 1,-7,-5,-3],
 [ 0,22,-5,68]]

```

Why? We fold from the top to the bottom. Since the matrix dimensions are even, we don't have a middle layer to preserve as is. The \\$a\\$'th row `[1, 1, 1, 1]` will be subtracted by the \\$(a-1)\\$'th row (would have been \\$(a-2)\\$'th row for odd dimension matrices); so `[1-0, 1-8, 1-6, 1-4]` becomes `[1, -7, -5, -3]`. The \\$(a+1)\\$'th row `[1, 25, 0, 75]` will then be subtracted by the \\$(a-2)\\$'th row (would have been \\$(a-3)\\$'th row for odd dimension matrices); so `[1-1, 25-3, 0-5, 75-7]` becomes `[0, 22, -5, 68]`.

With folding option bottomright-to-topleft instead (with the same input-matrix above) we output the following as result:

```
[[-74,  2,  1,  7],
 [  0,  7,  6],
 [-24,  1],
 [  1]]

```

With the following folding subtractions:

```
[[1-75,  3-1,  5-4,    7],
 [ 0-0,  8-1,    6],
 [1-25,    1],
 [   1]]

```

## Challenge rules:

* You can use any eight distinct letters `[A-Za-z]` or distinct numbers in the range \\$\[-99,99\]\\$ for the folding options. Numbers \\$\[1..8\]\\$ or \\$\[0..7\]\\$ are probably the most common options, but if you want to use different numbers within the range for some smart calculations, feel free to do so. **Please state which folding options you've used in your answer.**
* The input-matrix will always be a square NxN matrix, so you don't have to handle any rectangular NxM matrices. \\$N\\$ will also always be at least 2, since an empty or 1x1 matrix cannot be folded.
* The input of the matrix will always contain non-negative numbers in the range \\$\[0, 999\]\\$ (the numbers in the output will therefore be in the range \\$\[-999, 999\]\\$).
* With the (anti-)diagonal folding or odd-dimension vertical/horizontal folding, the middle 'layer' will remain unchanged.
* I/O is flexible. Can be a 2D array/list of integers; can be returned or printed as a space-and-newline delimited string; you can modify the input-matrix and replace the numbers that should be gone with `null` or a number outside of the `[-999, 999]` range to indicate they're gone; etc. etc.

## 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-matrix 1:

```
Input-matrix (for the following eight test cases):
[[ 1, 3, 5, 7],
 [ 0, 8, 6, 4],
 [ 1, 1, 1, 1],
 [ 1,25, 0,75]]

Input-folding option: left-to-right
Output: [[2,6],[-2,4],[0,0],[-25,74]]

Input-folding option: right-to-left
Output: [[-6,-2],[-4,2],[0,0],[-74,25]]

Input-folding option: top-to-bottom
Output: [[1,-7,-5,-3],[0,22,-5,68]]

Input-folding option: bottom-to-top
Output: [[0,-22,5,-68],[-1,7,5,3]]

Input-folding option: topleft-to-bottomright
Output: [[7],[6,-1],[1,-7,-2],[1,24,0,74]]

Input-folding option: topright-to-bottomleft
Output: [[1],[-3,8],[-4,-5,1],[-6,21,-1,75]]

Input-folding option: bottomleft-to-topright
Output: [[1,3,4,6],[8,5,-21],[1,1],[75]]

Input-folding option: bottomright-to-topleft
Output: [[-74,2,1,7],[0,7,6],[-24,1],[1]]

```

Input-matrix 2:

```
Input-matrix (for the following eight test cases):
[[17, 4, 3],
 [ 8, 1,11],
 [11, 9, 7]]

Input-folding option: left-to-right
Output: [[4,-14],[1,3],[9,-4]]

Input-folding option: right-to-left
Output: [[14,4],[-3,1],[4,9]]

Input-folding option: top-to-bottom
Output: [[8,1,11],[-6,5,4]]

Input-folding option: bottom-to-top
Output: [[6,-5,-4],[8,1,11]]

Input-folding option: topleft-to-bottomright
Output: [[3],[1,7],[11,1,-10]]

Input-folding option: topright-to-bottomleft
Output: [[17],[4,1],[8,-2,7]]

Input-folding option: bottomleft-to-topright
Output: [[17,-4,-8],[1,2],[7]]

Input-folding option: bottomright-to-topleft
Output: [[10,-7,3],[-1,1],[11]]

```

# Answer
> 5 votes
# Octave, ~~256~~ ~~248~~ ~~244~~ 248 bytes

```
m=d=x=@(a,b=1)rot90(a,b)
y=@(a,b=2)flip(a,b)
z=@(a,b=1)tril(a+1e3,-1)+a-x(y(tril(a)))+b*diag(diag(a))
f=@(a,b){m=((a-y(a))(:,1:(d=size(a,2)/2))),-y(m),m=y(x((a=x(a))-y(a)))(d+1:end,:),y(m,1),-y(z(a,-1)),x(z(x(a,2)),2),z(a=x(a,3)),x(z(x(a,2)),2)}{b}

```

Try it online!

*-2 bytes (and a bity of tidying up) thanks to Luis Mendo*

*+2 bytes due to the correction for T-B*

1-Indexed operations for values of b from 1-8:

```
R-L
L-R
B-T
T-B
BR-TL
TR-BL
BL-TR
TL-BR

```

This gave me a headache, I'll golf it properly later

# Answer
> 5 votes
# Jelly,  ~~39~~  34 bytes

<sub>*There is possibly further golfing possible by combining some of the two "functions".*</sub>
...yep: **-5** thanks to NickKennedy!

```
ṃ“Z“Ṛ“U“ “ŒDṙL ZZṚ”ŒḄFḲj“ŒH_Ṛ}¥/”v

```

**Try it online!**

A dyadic link accepting an integer (the instruction) and a list of lists of numbers (the matrix).

Uses the option to take the instruction as an integer in \\$\[-99,99\]\\$ to our advantage, and hence has the following seemingly bizarre mapping:

```
           Instruction  |  integer
------------------------+---------
         left-to-right  |     4
         right-to-left  |    14
         top-to-bottom  |     9
         bottom-to-top  |    39
topleft-to-bottomright  |    65
topright-to-bottomleft  |    15
bottomleft-to-topright  |    10
bottomright-to-topleft  |     0

```

### How?

The link creates Jelly code which is then evaluated using M as an input...

```
ṃ“Z“Ṛ“U“ “ŒDṙL ZZṚ”ŒḄFḲj“ŒH_Ṛ}¥/”v - Link: integer, I; matrix, M
 “Z“Ṛ“U“ “ŒDṙL ZZṚ”                - list of lists of characters = ["Z", "Ṛ", "U", " ", "ŒDṙL ZZṚ"]
ṃ                                  - base decompress (I) using those lists as the digits
                                   -  ...i.e. convert to base 5 and then convert the digits:
                                   -          [1,2,3,4,0] -> ["Z", "Ṛ", "U", " ", "ŒDṙL ZZṚ"]
                   ŒḄ              - bounce
                                   -  ...e.g. [a, b, c] -> [a, b, c, b, a]
                     F             - flatten to a list of characters
                      Ḳ            - split at spaces
                       j           - join with:
                        “ŒH_Ṛ}¥/”  -   list of characters = "ŒH_Ṛ}¥/"
                                 v - evaluate as Jelly code with an input of M

```

Each of the eight options are then:

```
left-to-right           (4): ŒH_Ṛ}¥/
right-to-left          (14): ṚŒH_Ṛ}¥/Ṛ
top-to-bottom           (9): ZŒH_Ṛ}¥/Z
bottom-to-top          (39): ZṚŒH_Ṛ}¥/ṚZ
topleft-to-bottomright (65): ṚUŒDṙLŒH_Ṛ}¥/ZZṚUṚ
topright-to-bottomleft (15): UŒDṙLŒH_Ṛ}¥/ZZṚU
bottomleft-to-topright (10): ṚŒDṙLŒH_Ṛ}¥/ZZṚṚ
bottomright-to-topleft  (0): ŒDṙLŒH_Ṛ}¥/ZZṚ

```

These each (except `0` and `4`) apply a transform to `M` using some of `Z` (transpose),  (reverse), and `U` (reverse each); then one of two functions (see below), then the inverse of the setup transformation (if there was one) implemented with the reverse of the code.

The two inner functions are:

```
ŒH_Ṛ}¥/ - Function A: Fold bottom-to-top: matrix, M
ŒH       - split M into two equal lists of rows (first half bigger by 1 if need be)
      / - reduce by:
     ¥  - last two links as a dyad:
    }   -  using the right argument (i.e. second half):
   Ṛ    -    reverse
  _     -  subtract

ŒDṙLŒH_Ṛ}¥/ZZṚ - Function B: Fold topright-to-bottomleft: matrix, M
ŒD             - diagonals of M
  ṙ            - rotate left by:
   L           -   length of M (puts them in order from bottom left most)
    ŒH_Ṛ}¥/    - same action as calling Function A on the diagonals
           Z   - transpose
            Z  - transpose
             Ṛ - reverse

```

# Answer
> 3 votes
# Jelly, ~~71~~ 34 bytes

```
ḃ2ŒḄ,UZṚŒDṙLƊŒH_Ṛ}¥/$ZZṚƊṚZ8ƭ$ị@¥ƒ

```

Try it online!

Test Suite

A full program. Right argument is the matrix. Left argument is the type of fold:

```
44 = L-R
40 = R-L
36 = T-B
32 = B-T
50 = TL-BR
34 = TR-BR
54 = BL-TR
38 = BR-TL

```

Rewritten to use 5-bit bijective binary as input. Note the program given above won’t work repeatedly for multiple folds.

# Answer
> 3 votes
# JavaScript (ES6),  ~~149 ... 133~~  128 bytes

Takes input as `(matrix)(d)` with \\$0\le d\le7\\$. Removed values are replaced with `NaN`.

Folding directions: \\$0 =\\;\rightarrow\\$, \\$1 =\\;\downarrow\\$, \\$2 =\\;\small\searrow\\$, \\$3 =\\;\small\swarrow\\$, \\$4 =\\;\leftarrow\\$, \\$5 =\\;\uparrow\\$, \\$6 =\\;\small\nwarrow\\$, \\$7 =\\;\small\nearrow\\$

```
m=>d=>m.map((r,y)=>r.map((v,x)=>v-=(w=m.length+~y)-(p=[x+x-y,y,x,q=w+y-x][d&3])&&[r[q],m[w][x],m[q][w],m[x][y]][d>3^p>w?d&3:m]))

```

Try it online!

### Commented

```
m => d =>                   // m[] = matrix; d = direction
  m.map((r, y) =>           // for each row r[] at position y in m[]:
    r.map((v, x) =>         //   for each value v at position x in r[]:
      v -=                  //     subtract from v:
        (                   //       define w as:
          w = m.length + ~y //         the width of input matrix - y - 1
        ) - (               //       and compare it with
          p = [             //       p defined as:
            x + x - y,      //         2 * x - y for vertical folding
            y,              //         y for horizontal folding
            x,              //         x for diagonal folding
            q = w + y - x   //         q = w + y - x for anti-diagonal folding
          ][d & 3]          //       using d MOD 4
        ) &&                //       if p is equal to w, leave v unchanged
        [                   //       otherwise, subtract:
          r[q],             //         r[q] for vertical folding
          m[w][x],          //         m[w][x] for horizontal folding
          m[q][w],          //         m[q][w] for diagonal folding
          m[x][y]           //         m[x][y] for anti-diagonal folding
        ][                  //       provided that we're located in the target area:
          d > 3 ^           //         test p < w if d > 3
          p > w ? d & 3     //         or p > w if d <= 3
                : m         //         and yield either d MOD 4 or m[]
        ]                   //       (when using m[], we subtract 'undefined' from v,
                            //       which sets it to NaN instead)
    )                       //   end of inner map()
  )                         // end of outer map()

```

# Answer
> 1 votes
# Octave, ~~482 bytes~~, 459 Bytes

The inputs for deciding folding directions are:
1)left to right
2)bottom to top
3)right to left
4)top to bottom
5)tr to bl
6)br to tl
7)bl to tr
8)tl to br
Each call only generates the specified fold, rather than all of them (which would probably would take less bytes). Biggest problem is that for this case I can't figure out how to put folds 1-4 and 5-8 in the same loop. But at least octave has nice looking matrices.

```
    function[m]=f(n,o)
    k=length(n);m=NaN(k);if(o<5)
    if(mod(o,2)>0)n=n'end
    q=[0,0,k+1,k+1](o)
    for x=1:ceil(k/2)if(x*2>k)m(x,:)=n(x,:)else
    for a=1:k
    m(abs(q-x),a)=n(abs(q-x),a)-n(abs(q-(k+1-x)),a)end
    end
    end
    if(mod(o,2)>0)m=flipud(m')end
    else
    if(mod(o,2)>0)n=flip(n)end
    q=[0,0,k+1,k+1](o-4)
    for x=1:k
    for a=1:k+1-x
    if(a==k+1-x)m(x,a)=n(x,a)else
    m(abs(q-x),abs(q-a))=n(abs(q-x),abs(q-a))-n(abs(q-(k+1-a)),abs(q-(k+1-x)))end
    end
    end
    end
    if(mod(o,2)>0)m=flip(m)end
    end

```

Try it online!

Output suppression costs bytes, so ignore everything that isn't the return statement(ans = ).

# Answer
> 1 votes
# Charcoal, ~~78~~ 77 bytes

```
Ｆ⁴«ＵＭηＥ⮌η§μλ¿⁼ιθＵＭηＥκ⎇‹⊕⊗νＬη⁻μ§⮌κν⎇›⊕⊗νＬηωμ¿⁼ι﹪θ⁴ＵＭηＥκ⎇‹λν⁻μ§§ηνλ⎇›λνωμ»Ｅη⪫ι,

```

Try it online! Link is to verbose version of code. Uses the following folding options:

```
0   top-to-bottom
1   left-to-right
2   bottom-to-top
3   right-to-left
4   bottomright-to-topleft
5   topright-to-bottomleft
6   topleft-to-bottomright
7   bottomleft-to-topright

```

Folded values are replaced by empty strings. Explanation:

```
Ｆ⁴«≔ＵＭηＥ⮌η§μλ

```

Rotate the array four times.

```
¿⁼ιθＵＭηＥκ⎇‹⊕⊗νＬη⁻μ§⮌κν⎇›⊕⊗νＬηωμ

```

Fold the array horizontally when appropriate.

```
¿⁼ι﹪θ⁴ＵＭηＥκ⎇‹λν⁻μ§§ηνλ⎇›λνωμ

```

Fold the array diagonally when appropriate.

```
»Ｅη⪫ι,

```

Output the array once it is rotated back to its original orientation.

---
Tags: code-golf, number, arithmetic, integer, matrix
---


title: How many lights are on?

text:
# Question
Title: How many lights are on?
You are little speck on a Cartesian plane. Pondering your existence, you decide to roam around your plane and touch things. You notice that every coordinate pair you visit has a light switch. To entertain yourself, you decide to toggle every switch that you come across.

**The Challenge**: Create a program that will take an input of random length, using only the characters `v`,`^`,`<`, and `>`. These characters correspond to movements.

* `<` moves you one unit to the left
* `^` moves you one unit up
* `>` moves you one unit to the right
* `v` moves you one unit down

Using this randomly generated input, calculate how many switches will be left in the `ON` position, assuming you start at (0,0), all lights begin in the `OFF` state, and you don't turn on any lights until you make your first move. (Meaning, if you start at (0,0), and move up 1 unit to (0,1), there will now be **1** light on). If you come across a switch that is on the `ON` position, it will be turned `OFF`.

Test cases:

```
v>v<^^<v<<^<^><<>^^>>><v>vv^v>v^><><<^>><<<vvv^vvv>v>>v><vv^^<<>vv^^>v^<>>^^<^^>^^v<^>^<vvv^v^v><^<<v<<>><<>v>>^><^>^^<>>>>vv>^<<^<<><vvv<v^>>vvv>v^>>><<v^>^^^^v>>^>^v>v<vv^<>^<<v>vv>><^^<^><vv^^v<v<v^^^>v<^vv^v<><vv^^^>v^>v>vv<<^><v<^v><<v^^v>>v<vv<><^^^v<^v><><<^^<>^>><^^^>vv^<>>>>^<^<<<<>>>v<<v<v<vv><<vv<vv<^v^^^>>vv<>v>><<<v^>vv><v<<<v<<>^vvv^<v^v>^^v^v><<v^>>>v<v<v^>>>v><>>>^<><<<<>vv>v><v>v><^v<>v>>>vv<<>^>^>v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>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^

```

yields 1408 lights on.

To generate input, you may use the following Python script:

```
import random
length = random.randint(15, 10000)
walk = ''
chars = ['v', '<', '>', '^']
for i in range(length):
    walk += random.choice(chars)
print(walk)

```

Standard scoring, winner is the smallest number of bytes.

# Answer
> 28 votes
# MATL, ~~19~~ ~~18~~ ~~17~~ 13 bytes

*5 bytes off thanks to @LeakyNun's idea (see his answer) of using the imaginary unit as a base for exponentiation.*

```
Jj11\^Ys8#uos

```

Try it online! Test cases: **1**, **2**.

### Explanation

The code traces the path using unit steps in the complex plane. Then it counts how many times each position was visited, and outputs how many positions were visited an odd number of times.

```
J         % Push the imaginary unit, 1j
j         % Input string
11\       % Modulo 11. This gives 7 6 5 8 for > ^ < v
^         % 1j raised to those numbers, element-wise. This gives -1j for >, -1 for ^,
          % 1j for < and 1 for v. So it gives the displacements in a "transposed"
          % complex plane
Ys        % Cumulative sum. This transforms displacements into positions
8#u       % Count of occurrences of each unique position
o         % 1 if odd, 0 if even
s         % Sum. Implicitly display

```

# Answer
> 19 votes
# Python, 68 bytes

**25 bytes thanks to Sp3000.**

**2 bytes thanks to Luis Mendo's idea of taking modulus with 11.**

**17 bytes thanks to xnor.**

```
d=set()
p=0
for c in input():p+=1j**(ord(c)%11);d^={p}
print(len(d))

```

Ideone it!

# Answer
> 8 votes
# Java 8, ~~169~~ ~~130~~ 127 bytes

Thanks to Leaky Nun for saving ~~29~~ 32 bytes.

```
s->{int l=s.length,d=2*l+1,p=l*d+d,r=0,m[]=new int[d*d];for(char c:s){p+=c<61?-1:c<63?1:c<95?-l:l;m[p]^=2;r+=m[p]-1;}return r;}

```

Ungolfed (sorta):

```
public static int f(char[] s) {
    int l = s.length, d = 2*l+1, p=l*d+d, r = 0;
    int[] m = new int[d*d];
    for(char c : s) {
        p += c<61 ? -1 : c<63 ? 1 : c<95 ? -l : l;
        m[p] ^= 2;
        r += m[p] - 1;
    }
    return r;
}

```

# Answer
> 7 votes
# Jelly, 13 bytes

A port of Luis Mendo's answer in MATL

```
O%11*@ı+\œ^/L

```

Try it online!

```
O%11*@ı+\œ^/L
O             convert to codepoint
 %11          modulo 11
    *@ı       power of i (imaginary unit)
       +\     cumulative sum
         œ^/  reduce by multiset symmetric difference
            L length

```

Credits of the `œ^/` trick to Dennis

# Answer
> 7 votes
# Perl, 49 bytes

Includes +1 for `-p` Run with the control string on STDIN

```
./lights.pl <<< "<<>"

```

`lights.pl`:

```
#!/usr/bin/perl -p
$\-=1-($a{$x+=/</-/>/,$y+=/\^/-/v/}^=2)for/./g}{

```

If input is restricted to 10000 bytes this reduces to `44+1`:

```
$\+=$#{$x+=/</-/>/.e5+/\^/-/v/}*=-1for/./g}{

```

# Answer
> 6 votes
# TSQL, ~~238~~ ~~235~~ ~~203~~ 191 bytes

Creating a table in memory using recursive SQL. Selecting and calculating from that table(one line code).

Golfed:

```
DECLARE @ varchar(max)= 'v>v<';

WITH C as(SELECT 0 a,b=1UNION ALL SELECT
a+POWER(CHARINDEX(SUBSTRING(@,b,1),'> <v')-2,15),b+1FROM
C WHERE b<=LEN(@))SELECT top
1sum(sum(1-1/b)%2)over()FROM c
GROUP BY a OPTION(MAXRECURSION 0)

```

Ungolfed:

```
DECLARE @ varchar(max)= '>>>><^v^v';

WITH C as
(
  SELECT 0 a,b=1
  UNION ALL
  SELECT a+POWER(CHARINDEX(SUBSTRING(@,b,1),'> <v')-2,15),b+1
  FROM C
  WHERE b<=LEN(@)
)
SELECT top 1sum(sum(1-1/b)%2)over()
FROM c
GROUP BY a
OPTION(MAXRECURSION 0)

```

**Fiddle**

# Answer
> 4 votes
# Mathematica, 64 bytes

A port of Luis Mendo's MATL answer.

```
Count[{_,_?OddQ}]@Tally@Accumulate[I^Mod[ToCharacterCode@#,11]]&

```

# Answer
> 3 votes
# SQF, 160 bytes

Using the function-as-a-file format:

```
x=0;y=0;a=[];{switch(_x){case"v":{y=y-1};case"^":{y=y+1};case"<":{x=x-1};case">":{x=x+1};};if([x,y]in a)then{a=a-[[x,y]]}else{a=a+[[x,y]]}}forEach _this;count a

```

Call as: `"STRING" call NAME_OF_COMPILED_FUNCTION`

Ungolfed:

```
//position tracker variables
x = 0; y = 0;
//`a` keeps track of which coords are switched on
a = [];
{
    //switch based on the magic variable `_x`
    //which is the current element of the forEach
    //and adjust coord tracker variables
    switch(_x) {
        case "v": {
            y = y - 1
        };
        case "^": {
            y = y + 1
        };
        case "<": {
            x = x - 1
        };
        case ">": {
            x = x + 1
        };
    };
    //check if the coord is already turned on
    if ([x, y] in a) then {
        //remove it from `a` using array exclusion
        a = a - [[x, y]]
    } else {
        //append it to `a`
        a = a + [[x, y]]
    }
//do this for each character in _this (the argument)
} forEach _this;
//return the length of `a`
count a

```

# Answer
> 3 votes
## Python: ~~207~~ ~~189~~ 181 Bytes

```
a = input()
l=[]
for i in range(0,len(a)):
 if a[i]=='v':y-=1
 if a[i]=='^':y+=1
 if a[i]=='<':x-=1
 if a[i]=='>':x+=1
 if [x,y] in l:l.remove([x,y])
 else:l.append([x,y])
print(l)

```

Input is a string.

Thanks to @LuisMendo for pointing out that I can actually only indent by 1 space. Darn my Python teachers for telling me to ***always*** do it increments of four.

Fixing it so that input was obtained rather than assumed stored actually saved me 8 bytes.

# Answer
> 3 votes
# Ruby, 64 + 6 = 70 bytes

+6 bytes for `-rset` flag.

A straight port of Leaky Nun's Python answer.

```
->s{d=Set.new
q=0
s.each_char{|c|d^=[q+=1i**(c.ord%11)]}
d.size}

```

See it on repl.it: https://repl.it/Cnjy

# Answer
> 3 votes
## Javascript (ES6), ~~97~~ ~~93~~ 85 bytes

```
i=>[...i].reduce((c,d)=>c-1+(v[p+=v['^<>v'.search(d)]]^=2),0,p=1E6,v=[-1E3,-1,1,1E3])

```

EDIT: -8 bytes, thanks to Neil

Test:

```
var test0 = 'v>v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<>^>v>v^<>v<^<<v>>>^<>v^>v>>vv^^<>>v<v<<^<>v>v^<^^^>v^^>v>v>vv<^<v>v^^><<<v<><>^^<>v>v>^^v>v>v^v>>^<v^v>><>^^>^<>>>^vv^><v^<^>v^>^v><^>^^^vv^^v<>vv<>>^><<^v>^v^>>v>^v^<<^^^vv<<vvv>^vv^v<<<v^^<<><vv<>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^';

S=i=>[...i].reduce((c,d)=>c-1+(v[p+=v['^<>v'.search(d)]]^=2),0,p=1E6,v=[-1E3,-1,1,1E3])

console.log(S(test0))
console.log(S(test1))
```

# Answer
> 2 votes
# R, 172 156  137 101 96 bytes

```
n=function(a)sum(table(cumsum(sapply(strsplit(a,"")[[1]],switch,v=-1,"^"=1,">"=1i,"<"=-1i)))%%2)

```

Using @LeakyNun's complex plane idea.

ungolfed

```
n=function(a){
    b=strsplit(a,"")[[1]]                        #Splits String up
    p=sapply(b,switch,v=-1,"^"=1,">"=1i,"<"=-1i) #Replaces characters with directions
    q=cumsum(p)                                  #Finds each location visitied
    t=table(q)%%2                                #Determines if spots were visited an odd # of times
    sum(t)                                       #counts odd visited spots
}

```

# Answer
> 2 votes
# Actually, ~~24~~ 23 bytes

This is a port of Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

**Edit:** One byte thanks to Leaky Nun.

```
O⌠4P@%ïⁿ⌡Mσ;╗╔⌠╜c2@%⌡MΣ

```

**Ungolfing:**

```
O        ord(c) of the input string (implicit input)
⌠...⌡M   Start a function, and map over the list of ord(). Call the variable i.
  4P@%     i mod 11 (the 4-th prime).
  ïⁿ       1i to the power of (i%11).

σ        Push a list of cumulative sums of the new list of complex numbers.
           This is a list of the coordinate visited.
;╗       Duplicate coord_list, and push to register 0.
╔        uniquify(coord_list)

⌠...⌡M   Map over the uniquified list. Call the variable j.
  ╜c       Push coord_list.count(j)
  2@%      Push count mod 2

Σ        Return the sum of this last list.

```

# Answer
> 2 votes
# PowerShell, 136 bytes

```
$a=@();switch -w($args|% t*y){'^'{$y++}'>'{$x++}'v'{$y--}'<'{$x--}*{if("$x,$y"-in$a){$a=$a|?{$_-ne"$x,$y"}}else{$a+="$x,$y"}}};$a.length

```

Try it online!

I think there's more to optimize here, but this is the lowest I got for now.

Easier to read:

```
$a=@();switch -w($args|% t*y){
    '^'{$y++}
    '>'{$x++}
    'v'{$y--}
    '<'{$x--}
    *{if("$x,$y"-in$a){$a=$a|?{$_-ne"$x,$y"}}else{$a+="$x,$y"}}
};$a.length

```

**Explanation:** The input is changed to a character array and each piece is matched to one of the first 4 switch cases to increment the x or y coord. Everything matches the 5th case where we decide if a light is turned on or off. Length at the end determines total number of switches turned on.

Note: The comma in the coordinates is necessary so we don't get collisions like (10,10) and (101,0)

# Answer
> 2 votes
# PowerShell, ~~96~~ 95 bytes

```
$(switch -w($args|% t*y){^{$y++}'>'{$x++}v{$y--}'<'{$x--}*{"$x,$y"}})|group|% c*|%{$r+=$_%2}
$r

```

Try it online!

Unrolled:

```
$plane=$(switch -w($args|% toCharArray){
    ^  {$y++}
    '>'{$x++}
    v  {$y--}
    '<'{$x--}
    *  {"$x,$y"}
})
$plane|group|% count|{$result+=$_%2}
$result

```

---

# PowerShell, ~~112~~ 109 bytes

A port of Luis Mendo's MATL answer.

```
$args|% t*y|%{($p+=($c=[numerics.complex])::Pow($c::new(0,1),$_%11))}|group{'{0:N2}'-f$_}|% c*|?{$r+=$_%2};$r

```

Try it online!

# Answer
> 1 votes
## Perl, ~~102 98 91~~ 90 (89 + -n) bytes

```
perl -nE '$i=ord()%5,$x+=(-1..1)[$i],$y+=((0)x3,1,-1)[$i],$p{$x,$y}^=1 for/./g;say~~grep$_,values%p'

```

**Readable:**

```
$_ = <>; # -n
for (/./g) {
    $i = ord() % 5;
    $x += (-1 .. 1)[$i];
    $y += ((0) x 3, 1, -1)[$i];
    $p{$x, $y} ^= 1;
}

say 0 + grep $_, values %p;

```
* thanks Dada for -4 and -7

# Answer
> 1 votes
# C, 203 190 189 bytes

```
#define S(s)1-(*s%11<7)*2<<*s%11%2*16
char*t,*u;P,p,r,L,e;
f(char*s){for(P=L=0,t=s;*t;++t){P+=S(t);e=r=1;for(p=0,u=s;u<t;u++)e*=(p+=S(u))!=P;for(p=P;*++u;r^=p==P)p+=S(u);L+=e*r;}return L;}

```

O(n^2) with O(1) memory algorithm.

It loops over every position, checks if this position occurs earlier, and if not checks if this position occurs an even/odd amount of time afterwards, adding it to the total.

# Answer
> 1 votes
# C# ~~210~~ ~~205~~ ~~139~~ ~~138~~ ~~135~~ ~~128~~ 113 Bytes

```
using System.Linq;int f(string s,int x=0,int y=0)=>s.GroupBy(c=>(x+=c%6%3-1)+s+(y-=c/3%6-2)).Sum(g=>g.Count()%2);

```

## Explanation

```
//Have X and Y as default params allows us to use a expression bodied member
//and then remove the return statement
int f(string s, int x = 0, int y = 0) =>

    //treat the string as a char array
    s.GroupBy(c =>

            //Using the unerlying int of the char this math reduces down to either x - 1, x + 1, x + 0, y - 1 or y + 1, or y + 0
            //Concat the resulting values with the original string to ensure uniqueness ie x=1 and y=11 vs x=11 and y=1 for the grouping
            (x += c % 6 % 3 - 1) + s + (y -= c / 3 % 6 - 2))

     //Mod 2 will return either 1 or 0 so we can use sum to count the groups with odd counts
     .Sum(g => g.Count() % 2);

```
* Thanks to VisualMelon for 5 bytes switching `Count` to `Sum`
* Thanks again to VisualMelon, this time for 66 bytes by suggesting some fancy math to get the translations.
* VisualMelon to the rescue again with combining the select and group by for 13 bytes and just using the input string for the x/y separator for another 2

# Answer
> 1 votes
# K (oK), ~~37~~ ~~29~~ 27 bytes

**Solution:**

```
+/2!.#:'=+\-99 0 99 -1 1@5!

```

Try it online!

**Explanation:**

Create list of steps, create path, group, count each repeat, if mod 2 is 0 then off, else on. Felt very AdventOfCode-ish.

```
+/2!.#:'=+\-99 0 99 -1 1@5! / the solution
                        5!  / input mod 5, "^v<>" yields 4 3 0 2
           -99 0 99 -1 1    / left, null, right, down, up
         +\                 / sum along
        =                   / group into key=>value
     #:'                    / count each value
    .                       / take the value
  2!                        / modulo 2
+/                          / sum up

```

**Notes:**

* **-8 bytes** by stealing David Horák's method of squashing x-y into x (I know it has limitations, but it works for the examples)
* **-2 bytes** thanks to ngn

# Answer
> 1 votes
# Perl 6, 47 bytes

```
{sum bag([\+] (-i,*i...*)[.ords X%11]){*}X%2}

```

Try it online!

* `(-i, *i, ... *)` is the infinite repeating sequence `-i`, `1`, `i`, `-1`, ...
* `[.ords X% 11]` slices into that sequence with the ordinal values of the characters in the input string, modulo 11.
* `[\+]` performs a triangular reduction (or "scan") on those values, producing a list of the coordinates visited on the complex plane.
* `bag()` creates a `Bag` containing those coordinates, each of which has an associated multiplicity (the number of times it appeared in the list).
* `{*}` fetches all of the multiplicities from the bag.
* `X% 2` crosses those multiplicities with the number `2` using the modulus operator `%`. Odd multiplicities result in a `1`, even multiplicities result in a `0`.
* `sum` sums those remainders.

# Answer
> 1 votes
# Common Lisp, 198 bytes 186 bytes

**Solution:**

```
(let((p 0)(c 0)(h(make-hash-table)))(progn(loop for s across i do(incf(gethash(incf p(nth(position s "^>v<")'(1e3 1 -1e3 -1)))h 0)))(maphash #'(lambda(k v)(incf c(mod v 2)))h)(write c)))

```

Run it!

**Explanation:**

```
(let ((p 0)(c 0)(h (make-hash-table)))
  (progn
    (loop for s across i
      do(incf (gethash (incf p (nth (position s "^>v<")'(1e3 1 -1e3 -1))) h 0)))
    (maphash #'(lambda (k v) (incf c (mod v 2))) h)
    (write c)))

```
* **p** is a hashtable map key, generated as an index of the character within the string "^\>v\<", remapped to values 1000, -1000, 1 -1 representing the x,y. (x axis is +-1, y axis is +-1000)
* the hash value at that index is incremented by 1 (switch counter)
* the hashtable is than looped trough, and the map function increment the final count as modulo 2 of the value on a given key

Note: i (input) is defined it test as:

```
(defparameter i ">>><^>>>^vv><^^v^<<<>>^<>>^<^>^<<^^v^<v^>>^<<><<>^v<^^^vv>v><^>>^<^<v><^v<^<<^^v><>>^v<^>^v<vvv<<<v^vv>>^vv>^^<>>vv>^<^>vv<>v^<^v<^^<v^^^<<^><><>^v>vvv<^vvv<vv><vv<^^v^^<^^>>><<<>^<>>><^<<<>><>^v><^^vv<>>><^^^<^>>>>v<v^><<>v<v<v^<<^><v^^><>v>^<>^^^vvv<v^>^^^^v>v<v>>>v^^<v<vv>><<>^vv><<vv<<>^^v>>v<^^v>><v<v<<>^^vv>>^v>v>v<>^>^v<>>><>v>v<<v<^<>>>vv>>v>^<>vv^v><><^v^>v<^^>v<^v>>v^>^>>v>v>^>^<^^>vv>>^vv<^><>^><<v^<><<^<^>^^vv^<<^^<^^v<v<>^>v>>>>>>vv<<v>^>vv^>^><^<^^><<vvvv>vvv<><<><v^vv><v^^<>^>><^vv<><>^>vv>>>vv^vv<<^v^^<<v^^>^>vvv<><<v>^>^>v<v>^<^^^^<^>^>><>>^^vv<>v<^>v><v<v^>>v<^v<vv>v^>v<v^<^^^^v<^<^<<v<<<v<v^^>vv^>><<<v>>^^^>^<^>>>v^v><^^vv^>><^^vv<vv<v^><>>^><<<>>^^v^v<<v^<vv^^^>><>>^v^^^>>^>^<<^>v>^^v>><>v>^>vv^^<vvvv<><^v>^><<>>><^<^v^<<vvv^v<<<<<><><<><><<v>v<v>v><^v^^vvv>><>^>^>^v<<vv^^^v^vv><v><><v<v<<>>>v<^<^v<<>^v<<^v<><>v>>^^>^<v^<<^v^^^vv>><v^<v>^v><^<>>>>^^<vv<>^^>^>v^v^^>><>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v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^")

```

# Answer
> 0 votes
# APL (Dyalog Unicode), ~~21~~ 20 bytes<sup>SBCS</sup>

```
+/≠/×⊢⌸+\0j1*'^<v'⍳⎕

```

Try it online!

uses `⎕io←1`

input

`'^<v'⍳` find the index of each input char among `'^<v'`, i.e. `^` becomes 1, `<` 2, `v` 3, and anything else 4

`0j1*` *i* to the power (the imaginary constant)

`+\` partials sums

`⊢⌸` matrix in which each row is the list of occurrences (indices) of a unique partial sum; padded with 0s to make it rectangular

`×` signum - all indices become 1s, the padding remains 0s

`≠/` sum mod 2 for each row

`+/` sum

# Answer
> 0 votes
# krrp, 137 bytes

```
^>:\L\T[length],^v>xy:!tTxy!V?[elem]tv[without]vLtELtv?#?E>V!c#!f>?=c$62.@V#!r>+x1y?=c$60.@V#!r>-x1y?=c$94.@V#!r>x-y1@V#!r>x+y1.LT00E>00.

```

Try it online!

---

# Explanation

```
^>:\L\T                ~ lambda expression, import list and tuple module
 [length],^v>xy:       ~  the answer is the number of lattice points
                       ~  which were visited an odd number of times
  !tTxy                ~   current lattice point
  !V ?[elem]tv         ~   if the lattice point is already present,
      [without]vLtE    ~    remove it, else
      Ltv              ~    add it
  ?#?E> V              ~   no further moves
  !c#!f>               ~   move character
  ?=c$62. @V#!r>+x1y   ~   move right
   ?=c$60. @V#!r>-x1y  ~    move left
    ?=c$94. @V#!r>x-y1 ~     move up
     @V#!r>x+y1        ~      move down
 .LT00E>00.            ~ initialize at point (0, 0)

```

Try it online!

Unfortunately, *krrp* only has one rather slow implementation, making the long test cases difficult to verify.
*krrp* String conversion.

# Answer
> 0 votes
# Ruby, 67 bytes

Inspired by orlp's C solution. Assembles a list of all visited positions, and then for each unique one (using setwise intersection `(d&d)` since it saves a byte over `d.uniq`), count the ones with an odd number of occurrences (technically, map it to the occurances%2, and sum them together, since that does the same thing)

```
->s,q=0{d=s.bytes.map{|c|q+=1i**(c%11)}
(d&d).sum{|c|d.count(c)%2}}

```

Try it online!

---
Tags: code-golf, counting
---


title: Parsing text written the millitext font

text:
# Question
Title: Parsing text written the millitext font
# Reading the text of the millitext font

There is a font here that fits each character into a single, 1x5 pixel block. It does this (assuming you're using an LCD screen) by using the RGB channels of each pixel to expand the one pixel into three subcolumns, one for each channel. Your task is to take in a string of text encoded in this font and 'decode' it.

# Millitext Alphabet

```
CHARACTER: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
ENCODING:  WYWBMRRMMMWYWYWWWMWBMRMYGYGYCWMMMMMW
           MGBWMRRMMMMMRMRRRMGBMRWMMMMMRGMMMMMB
           MGWWWWWBWWWYRMWWMWGBYRWMMYMYGGMMWGGG
           MGRBBBMBMBMMRMRRMMGBMRMMMRWMBGMCWMGR
           WWWWBWWBWWMYWYWRWMWWMWMMGRCMYGWBMMGW

```

I've abbreviated each color to a one character symbol (R=red, G=green, B=blue, C=cyan, Y=yellow, M=magenta, W=white).

# Input Format

The input format for this is pretty open. You can have the input be an array containing each column, an array containing each row, a `char[][]`, or anything like that. You can also choose to use the full words "red", "green", "blue", with uppercase/lowercase of your choice (but it must be consistent for each word! You cannot use "RED" and also do "green" or "Blue").

If your language happens to support it, you can also have input be colors (however that might work, I don't know off-hand).

You can assume that the input will ONLY contain encoded characters in the alphabet above (in particular, there will be no spaces or punctuation in your output).

# Output Format

You can either output a string or some sort of character array. You can chose whether the letters are uppercase or lowercase, but they must all have the same case.

# Example

```
MWRRGMGYRY
MRRRMMMMRM
WWRRMWMYRM -> HELLOWORLD
MRRRMWMMRM
MWWWGMGMWY

```

# Rules

This is , so shortest answer wins!

# Test set

```
WMWGMWWMYYGMYWGMBMMYWYGMWYWMWRWWMYGW
GMRMMGRMMMMMMRMMBMWMRMMMRMGMRRMBMMMR
GWWMMGRYYYMWMWMGBMWYWMMMWYGWWRWGGMMM -> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG
GMRWMGRMMMMWMRMMBMMRRMMCRMGMRRMRGMMM
GMWCWWWMYMGMMRGMWWMRWYGBWMGMWWMWGYGW

```

# Answer
# JavaScript (ES6),  ~~103 100 93 92~~  90 bytes

*Saved 9 bytes thanks to @ShieruAsakoto*

Takes input as an array of columns. Returns an array of characters.

```
a=>a.map(s=>"H-L-D--VGQ87MR6TZ-KJ9WC05BUXF1YI2EON3S-A-P4"[parseInt(s,35)%1161%219%152%43])

```

Try it online!
> 16 votes

# Answer
# Jelly, 50 bytes

```
Oḅ⁹%211“ẎP\7ßɱðvs*Ḋ⁹UfRMJiẒVƑ).Z½Ƈ"}~ḌyH⁵Ŀ⁶Ṿ‘iⱮịØB

```

Try it online!

A monadic link accepting the input as a list of columns and outputting a Jelly string of the translation. Full explanation to follow, but relies on the fact that each possible set of 5 letters is unique when converted to code points, converted back from base-256 to decimal and then mod 211.

Alternative using Arnauld’s fixed font (49 bytes and using same principle.)

### Explanation

```
O                   | Convert to code points
 ḅ⁹                 | Convert from base 256 to decimal
   %211             | Mod 211
       “Ẏ...Ṿ‘iⱮ    | Find indices in [209,80,92,55,21,162,24,118,115,42,193,137,85,102,82,77,74,105,189,86,146,41,46,90,10,144,34,125,126,173,121,72,133,199,134,186]
                ịØB | Index into 01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ

```
> 9 votes

# Answer
# dzaima/APL, ~~80~~ ~~79~~ ~~73~~ ~~72~~ 71 bytes

```
' P  FL6BDEZQA SY574H TVOK J 08  M  U IC92XW 3G1RN'⊇⍨52|8965|2411⊥¨⎕ucs

```

Try it online!
> 7 votes

# Answer
# 05AB1E, ~~45~~ 44 bytes

```
40ö98%•Wþ@»Ý¢a:µ@,–çòßuÒ¹₃©6µć‚FVÝ∊J?•2ôžLR‡

```

Try it online!

Takes input as array of columns, and outputs an array of characters.

Explanation:

```
40ö                       # convert each column from base 40
   98%                    # modulo 98
      •...•2ô             # compressed array: [20, 32, 82, 30, 27, 28, 76, 89, 46, 96, 36, 4, 18, 12, 80, 75, 50, 86, 42, 2, 52, 92, 48, 0, 84, 1, 88, 90, 10, 26, 70, 41, 94, 64, 14, 60]
             žLR          # built-in array 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
                ‡         # transliterate

```
> 6 votes

# Answer
# , ~~143~~ 128 bytes

```
function(v)c(0:9,LETTERS)[match(colSums((sapply(v,U<-utf8ToInt)*194:198)%%45:41),U("#</Eb=,n9J.M4Z+%*V N[Hd\\B?1Oj>KgRYT2")+34)]

```

Try it online!

Function taking a vector of strings (corresponding to the columns) as input e.g. :

```
MWRRG
MRRRM
WWRRM -> c('MMWMM','WRWRW','RRRRW','RRRRW','GMMMG') -> HELLO
MRRRM
MWWWG

```

Explanation :

Performing the following operation for each encoded string (e.g 'CRGBY' = 'S') :

```
        TO ASCII      MULTIPLICATION             MODULO              SUM &              TO
        CODEPOINT                                                    OFFSET             ASCII
---------------------------------------------------------------------------------------------

'C'        67        67 * 194 = 12998       12998 %% 45 = 38  \
'R'        82        82 * 195 = 15990       15990 %% 44 = 18  |
'G'  --->  71  --->  71 * 196 = 13916  ---> 13916 %% 43 = 27  |---> (140 - 34) = 106 ---> 'j'
'B'        66        66 * 197 = 13002       13002 %% 42 = 24  |
'Y'        89        89 * 198 = 17622       17622 %% 41 = 33  /

```

we obtain the following string `'#</Eb=,n9J.M4Z+%*V N[Hd\B?1Oj>KgRYT2'` where each character corresponds to `'0123456789ABCDEFGHIJKLMNOPQR'`.

So, the code performs the described operations on the input strings, then searches their correspondences inside `'#</Eb=,n9J.M4Z+%*V N[Hd\B?1Oj>KgRYT2'` obtaining the positions in string `'0123456789ABCDEFGHIJKLMNOPQR'`.
> 6 votes

# Answer
# Charcoal, 66 bytes

```
ＷＳ§”*&_⟲⎇4>υ≧Y⪪ml^π≕t.A；p↶⧴q⊗Ｈε‖r¡¡ºÞd⸿σＣ⁺⮌”﹪﹪﹪⍘ιWMYCBGR³⁶⁰¦¹¹³¦⁷¹

```

Try it online! Link is to verbose version of code. Takes input as a list of columns terminated with a blank line. Explanation:

```
ＷＳ

```

Input strings until one is blank.

```
§”*&_⟲⎇4>υ≧Y⪪ml^π≕t.A；p↶⧴q⊗Ｈε‖r¡¡ºÞd⸿σＣ⁺⮌”

```

Cyclically index into the string `OV EX8HSCF5IA L TG 17 M P9RB 4 K ZY2 0JW 63Q ND U` which (with trailing space) is 56 characters long.

```
﹪﹪﹪⍘ιWMYCBGR³⁶⁰¦¹¹³¦⁷¹

```

Perform base-7 conversion using the alphabet `WMYCBGR` and then reduce successively modulo 360, 113, 71, and 56 implicitly via the cyclic indexing.

My base 7 approach fared really badly with @Arnauld's fixed font; after some searching I was still at 73 bytes. Using @Grimy's approach cut this down to 67 bytes. However I eventually tracked down a 66 byte solution:

```
ＷＳ§”*&″ÀＭ↔↓<Ｊ;×⊟ςF,Ｇηe↖ητγ´ＷＩＹ³﹪▶⟧9?δc⁶ＡxDê↷hＰiψ”﹪﹪﹪⍘ι⁴⁷¦²³⁷¦⁷³¦⁶⁷

```

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

```
ＷＳ

```

Input strings until one is blank.

```
§”*&″ÀＭ↔↓<Ｊ;×⊟ςF,Ｇηe↖ητγ´ＷＩＹ³﹪▶⟧9?δc⁶ＡxDê↷hＰiψ”

```

Cyclically index into the string `ID HAM178 VS4F 3R EP6CQ Z UB O 0 X 9 G 5TNJKL2Y W` which is 63 characters long.

```
﹪﹪﹪⍘ι⁴⁷¦²³⁷¦⁷³¦⁶⁷

```

Perform base-47 conversion using the alphabet `0-9A-Za-k` and then reduce successively modulo 237, 73, 67, and 63 implicitly via the cyclic indexing.
> 3 votes

# Answer
### CJam (63 bytes)

```
{{Gb"õáÖÅ{a("{i%}/"@/Ö´çýß}yùÜÅ©GôÉç¢"256b43b'0f+=}%}

```

or in xxd format

```
0000000: 7b7b 4762 22f5 e1d6 c59f 7b61 2822 7b69  {{Gb".....{a("{i
0000010: 257d 2f22 0b8a 8340 982f d6b4 e793 fddf  %}/"...@./......
0000020: 7d79 f9dc c519 17a9 0e47 0ef4 c9e7 a222  }y.......G....."
0000030: 3235 3662 3433 6227 3066 2b3d 7d25 7d    256b43b'0f+=}%}

```

This is an anonymous block (function) which expects input as a list of columns. Online demo.

As many of the other answers, this does a base conversion followed by a chain of % to get a short lookup table. In this case I use base 16 and % chain `[245 225 214 197 159 123 97 40]`.
> 2 votes

# Answer
# Jelly, 48 bytes

```
OḌ%⁽qƥ%⁹%53“ð×⁼ẎėWWæ¤jḌṛ>÷ƭÑṙsṛḌz0Ġọµḷ’b51¤iⱮịØB

```

A monadic Link accepting a list of lists of uppercase characters (each being a column) which yields a list of characters.

**Try it online!**

### How?

```
OḌ%⁽qƥ%⁹%53“...’b51¤iⱮịØB - Link: columns
O                         - ordinals
 Ḍ                        - convert from base ten
  %⁽qƥ                    - modulo 29415
      %⁹                  - modulo 256
        %53               - modulo 53
                    iⱮ    - map with first index of x in:
                   ¤      -   nilad followed by link(s) as a nilad:
           “...’          -     22270425059867513817410846141176204460122938458128124185752719
                b         -     convert to base
                 51       -       51
                          -     ... = [38,13,19,27,10,16,20,11,35,31,4,17,9,0,50,45,24,25,34,39,22,29,41,32,3,7,46,5,48,18,6,44,28,14,1,8]
                      ị   - index into
                       ØB -   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

```
> 2 votes

# Answer
# Ruby, 109 bytes

```
->n{n.map{|i|"6&\278$Cc\17Y9\23T\r]{v^Ox\16_+!Qj\fbH
hraD*Ap".index((i.to_i(36)%245%119+8).chr).to_s(36)}*""}

```

Try it online!
> 1 votes

# Answer
# Stax, 46 bytes

```
é►^njÖ_╪»Θîq╪↨δXû=▀úæ5?ªoéV╫╫╩ßH‼╒C═e┼$⌠°JqUu⌡

```

Run and debug it

Each column is decoded as base-36. Successive modulus of 8273, then 95 are applied. This yields a unique number, looked up in a fixed string.

It takes input exactly in the format specified in the examples, and has to transpose them to get columns. I will be able to save some bytes by using some different input format, which I may do at some point.
> 1 votes

---
Tags: code-golf
---


title: Cut the gold chain

text:
# Question
Title: Cut the gold chain
A traveler needs to stay for *n* days in a hotel outside town. He is out of cash and his credit card is expired. But he has a gold chain with *n* links.

The rule in this hotel is that residents should pay their rent every morning. The traveler comes to an agreement with the manager to pay one link of the golden chain for each day. But the manager also demands that the traveler should make the least possible damage to the chain while paying every day. In other words, he has to come up with a solution to cut as few links as possible.

Cutting a link creates three subchains: one containing only the cut link, and one on each side. For example, cutting the third link of a chain of length 8 creates subchains of length \[2, 1, 5\]. The manager is happy to make change, so the traveller can pay the first day with the chain of length 1, then the second day with the chain of length 2, getting the first chain back.

Your code should input the length *n*, and output a list of links to cut of minimum length.

**Rules**:

* *n* is an integer \> 0.
* You can use either 0-based or 1-based indexing for the links.
* For some numbers, the solution is not unique. For example, if `n = 15` both `[3, 8]` and `[4, 8]` are valid outputs.
* You can either return the list, or print it with any reasonable separator.
* This is , so the shortest code in bytes wins.

**Test cases**:

```
Input          Output (1-indexed)
1              []
3              [1]
7              [3]
15             [3, 8]
149            [6, 17, 38, 79]

```

**Detailed example**

For *n* = 15, cutting the links 3 and 8 results in subchains of length `[2, 1, 4, 1, 7]`. This is a valid solution because:

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

```

No solution with only one cut exists, so this is an optimal solution.

**Addendum**

Note that this problem is related to integer partitioning. We're looking for a partition *P* of *n* such that all integers from 1 to *n* have at least one patition that is a subset of *P*.

Here's a YouTube video about one possible algorithm for this problem.

# Answer
> 16 votes
# 05AB1E, ~~23~~ ~~11~~ 8 bytes

```
ΔÍN-;иg=

```

Try it online!

Uses 0-based indexing.

### Explanation:

```
             # start from the implicit input
Δ            # loop forever
 Í           # subtract 2
  N-         # subtract the current iteration number
    ;        # divide by 2
     и       # create a list of length x
      g      # get the length of the list
       =     # print

```

`иg` looks like a noop, but it actually does two useful things: it truncates to an integer (`;` returns a float), and it crashes the interpreter if x is negative (this is the only exit condition).

---

The 23 byte solution used a very different approach, so here it is for posterity: `ÅœʒR2äθP}ʒæOê¥P}θ2äθη€O` (TIO, explanation).

# Answer
> 9 votes
# Python 2, 75 bytes

```
f=lambda n,i=0:n>=i<<i and f(n,i+1)or[min(n,2**j*i-i+j)for j in range(1,i)]

```

Try it online!

---

### Explanation:

Builds a sequence of 'binary' chunks, with a base number matching the number of cuts.

Eg:

`63` can be done in 3 cuts, which means a partition in base-4 (as we have 3 single rings):

Cuts: `5, 14, 31`, which gives chains of `4 1 8 1 16 1 32` (sorted: `1 1 1 4 8 16 32`).

All numbers can be made:

```
1       1
2       1 1
3       1 1 1
4       4
...
42      1 1 8 32
...
62      1 1 4 8 16 32
63      1 1 1 4 8 16 32

```

Other examples:

```
18: 4,11        ->  3 1 6 1 7
27: 5,14,27     ->  4 1 8 1 13 1
36: 5,14,31     ->  4 1 8 1 16 1 5
86: 6,17,38,79  ->  5 1 10 1 20 1 40 1 7

```

# Answer
> 8 votes
# , ~~77~~ 69 bytes

-8 bytes thanks to Aaron Hayman

```
pmin(n<-scan(),0:(k=sum((a=2:n)*2^a<=n))+cumsum((k+2)*2^(0:k))+1)[-n]

```

Try it online!

Let \\$k\\$ be the number of cuts needed; \\$k\\$ is the smallest integer such that \\$(k+1)\cdot2^k\geq n\\$. Indeed, a possible solution is then to have subchains of lengths \\$1,1,\ldots,1\\$ (\\$k\\$ times) and \\$(k+1), 2(k+1), 4(k+1), 8(k+1), \ldots, (k+1)\cdot 2^{k-1}\\$. It is easy to check that this is sufficient and optimal.

(The last subchain might need to be made shorter if we exceed the total length of the chain.)

Ungolfed (based on previous, similar version):

```
n = scan()                            # read input
if(n - 1){                            # If n==1, return NULL
  k = match(F, (a = 2:n) * 2 ^ a > n) # compute k
  b = (k + 1) * 2 ^ (1:k - 1)         # lengths of subchains
  c = 1:k + cumsum(b)                 # positions of cuts
  pmin(c, n )                         # if last value is >n, coerce it to n
}

```

(Proof that the value of \\$k\\$ is as I state: suppose we have \\$k\\$ cuts. We then have \\$k\\$ unit subchains, so we need the first subchain to be of length \\$k+1\\$. We can now handle all lengths up to \\$2k+1\\$, so we need the next one to be of length \\$2k+2\\$, then \\$4k+4\\$... Thus the maximum we can get out of \\$k\\$ cuts is obtained by summing all those lengths, which gives \\$(k+1)\cdot 2^k-1\\$.)

If \\$a(k)\\$ is the smallest integer \\$n\\$ requiring \\$k\\$ cuts, then \\$a(k)\\$ is OEIS A134401.

# Answer
> 3 votes
# Jelly, 12 bytes

```
’_‘ɼ:2»-µƬṖḊ

```

Try it online!

Translation of Grimy's 05AB1E answer so be sure to upvote that one too! Slightly disappointed this comes in a byte longer, but does at least have something a bit like an emoticon as the first three bytes!

# Answer
> 2 votes
# JavaScript (ES6), 66 bytes

This is a port of TFeld's answer.

```
n=>(g=a=>n<++i<<i?a.map(j=>(j+=(i<<j)-i)>n?n:j):g([...a,i]))(i=[])

```

Try it online!

# Answer
> 2 votes
# C++, ~~109~~,107 bytes

-2 bytes thanks to Kevin

```
#include<iostream>
main(){int n,k=0;for(std::cin>>n;++k<<k<n;);for(n-=k;n>0;k*=2,n-=k+1)std::cout<<n<<',';}

```

The algorithm is similar to the Robin Ryder's answer. The code is written in a compilable, whole form. Try it!

Details:

```
std::cin>>n;               // get the value of n as input
while(++k<<k<n);           // determine k
for(n-=k;n>0;k*=2,n-=k+1)  // we don't need n, so the lengths...
    std::cout<<n<<' ';     // of links are subtracted repeatedly

```

This has a **C** variation with the same byte length (doesn't seem to need a separate answer):

```
#include<stdio.h>
main(){int n,k=0;for(scanf("%d",&n);++k<<k<n;);for(n-=k;n>0;k*=2,n-=k+1)printf("%d,",n);}

```

# Answer
> 1 votes
# Retina 0.8.2, 61 bytes

```
.+
11,$&$*
+`\b(1+),(\1(1*)1?\3)$
1$2¶1$1,$3
1+,
1
1A`
1+
$.&

```

Try it online! 1-indexed port of @Grimy's answer. Explanation:

```
.+
11,$&$*

```

Start with `N=2` and the input converted to unary.

```
+`\b(1+),(\1(1*)1?\3)$

```

Repeatedly try to subtract `N` from the input and then divide by 2.

```
1$2¶1$1,$3

```

If successful, remember 1 more than the input on the previous line, increment `N` on the current line, and update the input to the new value.

```
1+,
1

```

Remove `N` and increment the last value so that it's also 1-indexed.

```
1A`

```

Remove the incremented original input.

```
1+
$.&

```

Convert the results to decimal.

# Answer
> 1 votes
# Ruby, 62 bytes

```
->n{(1...c=(0..n).find{|r|n<r<<r}).map{|b|[n,b-c+(c<<b)].min}}

```

Try it online!

Mostly stolen from TFeld's Python answer.

---
Tags: code-golf, puzzle-solver
---


# Question
Title: Convert a string containing integers to list of integers
What is the shortest way to convert a string containing integers separated by spaces to a list of integers?

* input : "-3 1 5 8 10"
* output : \[-3, 1, 5, 8, 10\]

I regularly face this situation and I wanted to know if there is a better way than (24 bytes):

```
list(map(int,s.split()))

```

# Answer
> 14 votes
Using *map* is way shorter than any of the ways I mentioned. You should do that.

Instead of calling `list(...)`, you should use `[*...]` (21 bytes):

```
[*map(int,s.split())]

```

Or even better, if you switch to python 2, `map` will always return a list. (18 bytes):

```
map(int,s.split())

```

Try it online!

Original Post:

---

The straightforward way is going to be 26 bytes

```
[int(n)for n in s.split()]

```

Try it online!

However, if a tuple is acceptable instead of a list, we could use a trick to shave one byte off leaving us with 25 bytes

```
eval(",".join(s.split()))

```

Try it online!

This can be shortened even more with the **replace** function (24):

```
eval(s.replace(' ',','))

```

Try it online!

and even more with iterable unpacking (22):

```
eval(s.replace(*" ,"))

```

Try it online!

If you truly need a list, you can wrap it in `[*...]`. This is still shorter than the straightforward way by 1 byte:

```
[*eval(s.replace(*" ,"))]

```

---
Tags: code-golf, tips, python
---