title: Cut resistance of a list

text:
# Question
Title: Cut resistance of a list
## Background

Define a **run** in a list as a maximal contiguous subsequence of identical values. For example, the list

```
0 0 0 1 1 0 3 3 3 2 2

```

has five runs of lengths 3, 2, 1, 3, 2 respectively. (Think of run-length encoding.)

Then define a **cut operation** as removing one item from each run of a list. Applied to the list above, the result will be `0 0 1 3 3 2`.

Finally, the **cut resistance** of a list is the number of cut operations needed to reduce it to an empty list. The cut resistance of the list above is 3:

```
0 0 0 1 1 0 3 3 3 2 2
0 0 1 3 3 2
0 3
(empty)

```

Note that the cut resistance can be higher than the maximal run length, since multiple runs may fuse in the way:

```
1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0
0 1 0 0 0
0 0
0
(empty)

```

Related OEIS sequence: A319416 (cut resistance of n written in binary)

## Task

Given a (possibly empty) list of nonnegative integers, compute its cut resistance.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
0 0 0 1 1 0 3 3 3 2 2 => 3
1 0 0 1 1 0 0 1 0 0 1 0 0 1 0 1 0 => 4
1 2 3 4 5 99 100 101 => 1
4 4 4 4 4 4 3 3 3 3 2 2 1 2 2 3 3 3 3 4 4 4 4 4 4 => 7
(empty) => 0

```

# Answer
> 7 votes
# , 20 bytes

```
1-~&#(#~2=/\_&,)^:a:

```

Try it online!

Using the `0 0 0 1 1 0 3 3 3 2 2` example:

1. `(......_&,)` Prepend infinity `_`:

```
_ 0 0 0 1 1 0 3 3 3 2 2

```
2. `(..2=/....)` Are consecutive pairs equal? Returns 0-1 list of same length as input:

```
_ 0 0 0 1 1 0 3 3 3 2 2  <-- Before
 0 1 1 0 1 0 0 1 1 0 1   <-- After

```
3. `(#~.......)` Apply the above mask as a filter to the input. This drops the first member of every group:

```
0 0 1 3 3 2

```
4. `^:a:` Repeat until we reach a fixed point, returning all intermediate results (0-padded on the right):

```
0 0 0 1 1 0 3 3 3 2 2
0 0 1 3 3 2 0 0 0 0 0
0 3 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

```
5. `1-~&#` Subtract 1 from `1-~` the above result, after applying the "length of" verb to both lists `&#`. Since the length of 1 is 1, it remains unchanged, while the result above becomes 4:

```
4 - 1
3

```

# Answer
> 6 votes
# Python 2, 55 bytes

```
f=lambda l:l>[]and-~f([x for x in l[1:]if x==l.pop(0)])

```

Try it online!

False for 0.

**57 bytes**

```
f=lambda l:l>[]and-~f([a for a,b in zip(l,l[1:])if a==b])

```

Try it online!

# Answer
> 6 votes
# K (ngn/k), 13 bytes

Same as Jonah's, scan of x at where equal each-prior.

```
#1_{x@&=':x}\

```

Using `0 0 0 1 1 0 3 3 3 2 2` as example:

`=':` means equal each prior

```
  =': 0 0 0 1 1 0 3 3 3 2 2
      0 1 1 0 1 0 0 1 1 0 1  / zeros in the result correspond to the first item of the run

```

then indexing into the argument with this mask effectively drops the first item of each run. the indices are:

```
 &=': 0 0 0 1 1 0 3 3 3 2 2 / where equal each-prior?
1 2 4 7 8 10

 0 0 0 1 1 0 3 3 3 2 2@1 2 4 7 8 10 / indexing
0 0 1 3 3 2

```

we can turn this into a function and repeat until the result stops changing

```
 {x@&=':x}\0 0 0 1 1 0 3 3 3 2 2
(0 0 0 1 1 0 3 3 3 2 2
 0 0 1 3 3 2
 0 3
 !0)

```

drop 1 and take the length

```
 #1_{x@&=':x}\0 0 0 1 1 0 3 3 3 2 2
3

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 8 bytes

```
.Γγ€¨˜}g

```

Try it online or verify all test cases.

**Explanation:**

```
.Γ        # Continue until the result no longer changes,
          # collecting all intermediate results in a list
  γ       #  Split the list into chunks of equal adjacent elements
   €¨     #  Remove the last value of each chunk
     ˜    #  Flatten the list of lists
      }g  # After the cumulative fixed-point loop, pop and push the length
          # (which is output implicitly as result)

```

# Answer
> 4 votes
# Pyth, 10 bytes

```
tl.uqF#C,t

```

Try it online!

There's a bug in the parser related to this use of `qF#`, because if I append three variables at the end (e.g. `NNQ`), it crashes the parser. This is because `qF` should be treated as having arity 1, but it's being treated as having arity 2. However, it works fine as is, because the rest of the program is implicit, so the parser completes before anything goes wrong.

Explanation:

```
tl.uqF#C,t
  .u          Repeatedly apply the following function until the result stops changing:
         t    Remove the first element of the input (tail)
        ,     Pair with the input
       C      Transpose, resulting in all 2 element sublists.
      #       Filter on
    qF        the two elements being equal.
 l            Length
t             Subtract 1 for the empty list.

```

Note that the intermediate lists look like:

```
[1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0]
[[0, 0], [1, 1], [0, 0], [0, 0], [0, 0]]
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
[]

```

Try it online!

This occurs because the program doesn't both to select one element from each pair of numbers. Instead, the pair itself is used as the element of the list in the next iteration. This saves 2 bytes.

# Answer
> 4 votes
# JavaScript (Node.js), 38 bytes

```
f=s=>s+s?f(s.filter(t=>s===(s=t)))+1:0

```

Try it online!

# JavaScript (Node.js), 42 bytes

```
f=s=>s+s?f(s.filter(t=>s[++i]==t,i=0))+1:0

```

Try it online!

# Answer
> 4 votes
# Haskell, 41 bytes

```
f[]=0
f(h:t)=1+f[x|(x,y)<-zip(h:t)t,x==y]

```

Try it online!

`f a=1+f[x|(x,y)<-zip a$tail a,x==y]` is the same length.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 38 bytes

```
If[#!={},#0[Join@@Rest/@Split@#]+1,0]&

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-p`, 32 bytes

```
$\++while s/\b(\d+ )(\1*)/$2/g}{

```

Try it online!

Requires a trailing space on the input. (Though I did put some code in the header to add it if it isn't already there so that testing is easier.)

# Answer
> 3 votes
# Prolog, 115 bytes

```
a([_],[]).
b(_,[],E,E).
b(A,[B|C],D,E):-A=B,b(A,C,[B|D],E);b(B,C,D,E).
c(A,B):-A=[],B=0;A=[P|L],b(P,L,[],C),!,c(C,D),B is D+1.

```

Clear version:

```
% Cut operation.
% Cut operation.
% Previous A, Head B, Tail C, List D, List E.
b(_, [], E, E).
b(A, [B|C], D, E) :-
    A = B,
    b(A, C, [B|D], E)
;   b(B, C, D, E).

% Count cut.
% List A, Number of cut B.
c(A, B) :-
    A = [],
    B = 0
;   A = [P|L],
    b(P, L, [], C),!,
    c(C, D),
    B is D + 1.

```

# Answer
> 3 votes
# APL (dzaima/APL), 18 bytes

```
≢1↓{⍵⊇⍨⍸2=/¯1,⍵}⍡≡

```

`{⍵⊇⍨⍸2=/¯1,⍵}` \- dfn that finds the next stage

`⍡≡` iterate until reaching a fixpoint

`≢2↓` drop the first two elements, then take the length

-2 bytes thanks to Marshall

-1 byte thanks to Bubbler

Try it online!

# Answer
> 3 votes
# Husk, 7 bytes

```
←V¬¡Ψf=

```

Try it online!

## Explanation

It's not often that I get to use the higher order modifier function `Ψ`, but here it's very convenient.

```
←V¬¡Ψf=   Implicit input: a list.
   ¡      Iterate (producing an infinite list)
     f    filtering by condition:
    Ψ     the next element
      =   is equal to this one.
          The last element is always discarded.
 V        1-based index of first result that is
  ¬       falsy (for lists, this means empty).
←         Decrement.

```

# Answer
> 2 votes
# C (gcc), ~~108~~ ~~104~~ 101 bytes

```
*o,*O,r;e(int*s){for(r=1;~*s;r++)for(o=s;~*o;*O=-1){for(;*o==*++o;);for(O=--o;~*O;)*O++=O[1];}s=~-r;}

```

Try it online!

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

```
f=function(x)`if`(sum(x|1),1+f(x[-cumsum(rle(x)$l)]),0)

```

Try it online!

*Edit: recursive function is 1 byte shorter, and returns `0` for empty input*

(original, non-recursive version returned FALSE for empty input)

# Answer
> 2 votes
# T-SQL, 125 bytes

I am using table as input

```
DECLARE @ INT=1u:SET
@-=1DELETE x FROM(SELECT*,lag(a,1,-1)over(order by i)b
FROM t)x
WHERE a<>b
IF @@rowcount>0GOTO u
PRINT-@

```

The posted code is using a permanent table as input. **Try it online** is using a table variable spending 1 additional byte

# Answer
> 2 votes
# Brain-Flak, 68 bytes

```
([]){{}({}()<>)<>([])}<>({()<{(({}<>)<>[({})]){{}<>{}(<>)}{}}<>>}{})

```

Try it online!

```
([]){{}({}()<>)<>([])}<>  # add 1 to everything so I don't have to handle 0

({()<                     # until stack is "empty", counting iterations:
  {                       # for each number
    (
      ({}<>)              # copy to other stack
    <>[({})])             # and compare to next number (or zero if at end)
    {{}<>{}(<>)}{}        # if not equal, remove newly added number
  }<>                     # switch stacks for next iteration
>}{})                     # output number of iterations

```

# Answer
> 2 votes
# Factor \+ `grouping.extras`, 78 bytes

```
[ 0 swap [ [ ] group-by values [ rest ] map-concat [ 1 + ] dip ] until-empty ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves an integer on the data stack as output.

* `0 swap` Tuck away our cut resistance value for safe keeping.
* `[ ... ] until-empty` Keep doing something to a sequence until it's empty. This is shorter than having to call `dup`, `empty?`, `drop`, and the like.
* `[ ] group-by values` Group the runs of a sequence. This is shorter than `[ = ] monotonic-split`.
* `[ rest ] map-concat` Cut the runs and glue 'em back together.
* `[ 1 + ] dip` Increment the cut resistance value.

# Answer
> 2 votes
# Vyxal, 7 bytes

```
≬ĠvṪfİL

```

Try it Online!

```
     İL # Count number of times until the result repeats
≬----   # By applying the following
 Ġ      # Group consecutive elements
  vṪ    # Remove the last item from each group
    f   # Flatten

```

# Answer
> 1 votes
# Python 2, 63 bytes

Takes in a string \\$ s \\$, a space-separated string of the numbers. It returns `False` for the *empty* case.

```
f=lambda s:s>''and-~f(re.sub(r'(\d+ )(\1*)',r'\2',s))
import re

```

Try it online!

---

## Python 2, 65 bytes

Same as above, but returns `0` for the *empty* case, in case returning false is disallowed.

```
f=lambda s:len(s)and-~f(re.sub(r'(\d+ )(\1*)',r'\2',s))
import re

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, ~~27~~ 25 bytes

*-2 bytes thanks to @Neil*

```
1`\b
=
}`(\d+ )(\1*)
$2
=

```

Try it online!

Similar to @Xcali's Perl solution, and similarly requires a trailing space in the input.

```
1`\b
=

```

Replace the first word-boundary with a `=` character. The first time this is executed, it will match the start of the input. On subsequent runs, it will match the empty space between a `=` and the first number in the list

```
(\d+ )(\1*)
$2

```

Replace sequences of repeated integers with everything but the first integer.

```
}`

```

Execute the preceding two stages in a loop until the input stops changing

```
=

```

Count the number of `=`'s

# Answer
> 1 votes
# Factor, 109 bytes

```
: f ( s -- n ) 0 swap [ dup empty? ]
[ [ = ] monotonic-split [ 1 tail ] map concat
[ 1 + ] dip ] until drop ;

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~9~~  8 bytes

-1 by golfing a 9-byter suggested by clapp

```
EƝTịµƬL’

```

**Try it online!**

# Answer
> 1 votes
# C (gcc), ~~118~~ \\$\cdots\\$ ~~94~~ 92 bytes

Saved ~~2~~ ~~5~~ 7 bytes thanks to ceilingcat!!!

```
*t;k;c;f(l,n)int*l;{for(k=0;n;++k)for(t=l,c=-1;t-l<n;)c-*t?c=*t,wmemcpy(t,t+1,n--):++t;c=k;}

```

Try it online!

**Commented code**

```
*t;k;c;f(l,n)int*l;{
  for(k=0;                  /* initialise cut operation counter */
    n;                      /* loop until there're no numbers left
                                     in array */
    ++k)                    /* increment cut operation counter after
                                     every loop */
     for(t=l,               /* save the pointer to the start of
                                     the array */
       c=-1;                /* initialise c to something that won't
                                     match first number */
       t-l<n;)              /* loop until our temp pointer is past
                                     the end of the array */
        c-*t?               /* should we do a cut operation? */
         c=*t,              /* save our cuurent number so we do a cut
                                     operation at next different number */
         wmemcpy(t,t+1,n--) /* shift array down one element
                                     and reduce number of elements by 1 */
         :++t;              /* if we're not doing a cut operation
                                     bump pointer */
  c=k;                      /* return k */
}

```

# Answer
> 1 votes
## Clojure, 72 bytes

```
#(count(take-while seq(iterate(fn[c](mapcat rest(partition-by + c)))%)))

```

Damn these function names are long :D

# Answer
> 0 votes
# Charcoal, 22 bytes

```
Ｗθ«≔Φθ∧λ⁻κ§θ⊖λθ⊞υω»ＩＬυ

```

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

```
Ｗθ«

```

Repeat until the input list is empty.

```
≔Φθ∧λ⁻κ§θ⊖λθ

```

Filter out the first term and any terms equal to their predecessor, i.e. the first of every run.

```
⊞υω

```

Keep track of the number of iterations.

```
»ＩＬυ

```

Output the number of iterations.

# Answer
> 0 votes
# Japt, 9 bytes

```
Ê©ÒßUòÎcÅ

```

Try it

```
Ê©ÒßUòÎcÅ     :Implicit input of array U
Ê             :Length
 ©            :Logical AND with
  Ò           :Negate the bitwise NOT of
   ß          :Recursive call with argument
    Uò        :  Partition U between elements where
      Î       :    The sign of their difference is truthy (not 0)
       c      :  Flatten after
        Å     :    Slicing off the first element of each partition

```

# Answer
> 0 votes
# Husk, ~~8~~ 7 bytes

```
←LU¡mhg

```

Try it online!

A different method, which is ~~slightly longer~~ now the same length.

## Explanation

```
←LU¡mhg
      g group runs of consecutive equal elements
   ¡    apply function infinitely, collecting it's results
    mh  drop the last element from each run
  U     cut at fixed point
←L      Get length, decrement.

```

# Answer
> 0 votes
# Ruby `-nl`, 43 bytes

Similar to the other regex-based answers.

```
$.+=1while gsub(/(\d+ )(\1*)/,'\2')!=""
p$.

```

Attempt This Online!

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


title: 1D monochrome Link-a-Pix solvability

text:
# Question
Title: 1D monochrome Link-a-Pix solvability
## Background

Link-a-Pix is a puzzle on a rectangular grid, where the objective is to reveal the hidden pixel art by the following rules:

* Connect two cells with number N with a line spanning N cells, so that the two cells are at the two ends of the line.
* The number 1 is considered connected to itself (which makes it an exception to the rule of "connect *two* cells").
* Two different lines are not allowed to overlap.
* The puzzle is solved when all the given numbers on the grid are connected by the above rules. There may be some unused cells after the puzzle is solved.

The following is an example puzzle and its unique solution.

(Source: The NP completeness of some lesser known logic puzzles, 2019)

A Link-a-Pix puzzle often involves colors and reveals a colorful picture when solved, but we will ignore them for simplicity, and focus on "monochrome" puzzles.

## Task

In this challenge, the puzzle is limited to one dimension, or equivalently, a grid of height 1.

Given a 1D Link-a-Pix puzzle instance, check if it has a solution or not. A puzzle instance is given as a sequence of non-negative integers, where each cell with a given number contains that number and the others contain 0.

For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

## Test cases

```
Truthy
[0, 1, 0, 4, 0, 0, 4, 2, 2, 0, 1]
[0, 0, 0, 0] (the puzzle is solved vacuously)
[12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12] (multi-digit numbers must be supported)
[2, 2, 0, 2, 2, 2, 2, 1, 2, 2] (suggested by tsh)

Falsy
[0, 4, 0, 3, 4, 3, 0] (two lines cannot overlap)
[3, 0, 3, 0, 3, 1, 3, 0, 3, 0, 3]
[1, 0, 2, 2, 2, 2, 2, 0, 1] (one of 2s have nowhere to connect)
[3, 3, 3, 3] (suggested by tsh)
[3, 3, 3]
[0, 0, 4, 4] (the 4s must begin and end the 4-cell line)
[12, 2] (multi-digit numbers must not be treated as multiple single-digit numbers)

```

# Answer
> 10 votes
# JavaScript (ES6), 41 bytes

Returns *false* for valid or *true* for invalid.

```
a=>a.some(p=(x,i)=>--p>0?x:a[i+x-1]^=p=x)

```

Try it online!

### Commented

```
a =>            // a[] = input
a.some(p =      // start with p NaN'ish
  (x, i) =>     // for each value x at position i in a[]:
  --p > 0 ?     //   decrement p; if it's positive:
    x           //     make sure that we have x = 0
                //     (because we're currently over a connection 'line')
  :             //   else:
    a[          //     XOR the entry at ...
      i + x - 1 //     ... i + x - 1 ...
    ]           //
    ^= p = x    //     ... with x; and set p = x
                //     this must give 0 if the puzzle is valid
)               // end of some()

```

The trickiest case is when a \\$0\\$ is reached at position \\$i\\$ and we're currently outside a connection (i.e. \\$p\le0\\$), which causes the entry at \\$i-1\\$ to be XOR'ed with \\$0\\$. If the puzzle is valid, this will always result in \\$0\\$ as expected because:

* if \\$i=0\\$, we do `undefined ^ 0`
* if \\$i\>0\\$, the entry at \\$i-1\\$ either was already set to \\$0\\$ or was cleared by the previous XOR

# Answer
> 7 votes
# Jelly, 15 bytes

```
Ṁ1;Ṭ×Ʋ€ṚœṣF¥ƒ⁸Ẹ

```

Try it online!

A monadic link taking a list of integers and returning `0` for those that have a solution and `1` for those that don’t.

## Explanation

```
Ṁ               | Max
     Ʋ€         | For each integer z from 1 to this:
 1;             | - Prepend 1
   Ṭ            | - Untruthy (so [1, 4] becomes [1, 0, 0, 1]
    ×           | - Multiply by z
       Ṛ        | Reverse (so that the largest lists come first)
           ¥ƒ⁸  | Reduce using the original list as the starting point and the following two links as a dyad:
        œṣ      | - Split at matching substrings
          F     | - Flatten
              Ẹ | Finally check if any non-zero values remain

```

---

# Second approach

# Jelly, 19 bytes

```
Ị¬Ts2r/€ịµF^Ø.¦L)FẸ

```

Try it online!

## Explanation

```
Ị                    | Insignificant (<= 1)
 ¬                   | Not
  T                  | Truthy indices
   s2                | Split into pairs
     r/€             | For each, make a range between the two values (returns asingle value if there isn’t a pair, which will knly be seen if no solution
        ị            | Index into original input
         µ           | Start a new monadic chain
                )    | For each:
          F          | - Flatten (handles situation with single value)
           ^Ø.¦      | - Xor the first and last values with:
               L     | The length of that set
                 F   | Flatten
                  Ẹ  | Any

```

---

# Original approach

# Jelly, 23 bytes

```
ṣḊLḂȯm2;Ẉ+2nʋ¥ɗʋɗⱮỊÐḟFẸ

```

Try it online!

In brief, tries splitting the list at every occurrence of each integer \>=2 and then tests the following for each of those splits:

* The length is odd (I.e. there was an even number of that value originally)
* There are no non-zero integers in between the pairs of that integer
* The lengths of each run of zeros is equal to the integer minus 2

If any test fails for any split then the puzzle is not-solvable.

## Explanation

```
                ɗⱮỊÐḟ   | Use each of the input except 0s and 1s as the right argument y of the following (with the original argument x as the left argument):
ṣ                       | - Split x at y (-> z)
               ʋ        | - Following as a dyad using arguments z and y:
 Ḋ                      |   - Remove first element
  L                     |   - Length
   Ḃ                    |   - Odd
    ȯ         ɗ         |   - Or the following as a dyad with arguments z and y:
     m2                 |      - Take every other sublist starting at the first (-> w)
             ¥          |      - Following as a dyad using arguments (w, y)
       ;    ʋ           |      - Concatenate to the following using arguments (w, y)
        Ẉ               |        - Lengths of w
         +2             |        - Add 2 (vectorises)
           n            |        - Not equal to y
                     F  | Finally, flatten all lists
                      Ẹ | Check whether any are non-zero

```

# Answer
> 6 votes
# , 33 bytes

```
0(-.~-:2#_2-~/\I.@:<)1&(1+=j.<)#]

```

Try it online!

A large part is reused from Jonah's solution, but this solution adds an idea and a J-specific black magic of combining `j.` with `#`.

### A high-level view of the algorithm

```
Example input: 0 1 0 4 0 0 4 2 2 0 1
Insert a 1 after ones, and a 0 after other nonzeros (call it X):
               0 1 1 0 4 0 0 0 4 0 2 0 2 0 0 1 1
1) Nonzero indices of X:
               1 2 4 8 10 12 15 16
   Non-overlapping pairwise difference:
               (2-1),(8-4),(12-10),(16-15) = 1 4 2 1
   Duplicate each number (call it Y):
               1 1 4 4 2 2 1 1
2) Remove zeros from X (call it Z):
               1 1 4 4 2 2 1 1
Do Y and Z agree? Yes.

```

### Why this works

First, note that Z, which is simply X without zeros, should agree with something duplicated. This means the paired non-zero numbers in X should have the same value (and X cannot have any unpaired value at the end). This holds iff the nonzeros in the original input can be paired in the Link-a-Pix way, ignoring the distances.

Then look at Y, which is generated from the paired distances between nonzero numbers. Y = Z means that the numbers forming a pair must be equal to the distance between them. The process of computing X precisely makes the distance between two `n`'s equal to `n` (by duplicating the ones and adding a distance of 1 for the others).

### How the code works

When given a complex number `a+bi` as the left arg of `#`, the corresponding item is replicated `a` times and then `b` fill elements are inserted. It is like APL's `/` and `\` combined, and as far as I'm aware, it is at least not very straightforward to do the same in other languages (APL-like or not).

```
0(-.~-:2#_2-~/\I.@:<)1&(1+=j.<)#]  NB. Input: vector of integers
1&(1+=j.<)#]  NB. Construct X:
1&(  =   )    NB. For each item, 1 if equal to 1, 0 otherwise
1&(     <)    NB. For each item, 1 if greater than 1, 0 otherwise
   1+ j.      NB. Compute complex numbers (a, b) -> (a+1) + bi
          #]  NB. As left arg of #, duplicate 1s and insert a 0 after >1s
0(-.~-:2#_2-~/\I.@:<)  NB. Test if Y = Z:
0(     2#_2-~/\I.@:<)  NB. Construct Y:
0(             I.@:<)  NB. Indices of nonzero items of X
         _2-~/\        NB. Non-overlapping pairwise differences
       2#              NB. Duplicate each number
0(-.~               )  NB. Construct Z: Remove zeros from X
     -:                NB. Do Y and Z agree?

```

# Answer
> 5 votes
# , 53 bytes

```
([:*/2|[:+/@:*;.1,~&1)*[:(-.&0-:1+2#_2-~/\I.@:*)]*1&<

```

Try it online!

This is the idea for the approach Bubbler's answer improves and refines. I consider that answer the "final draft" J answer. Aside from making use of some nice J tricks, it also eliminates the need for doing a separate check for "ones in the middle". Previous versions of this answer had similar ideas, but each of them failed on some test cases, whereas Bubbler's solution irons out all the problems.

Consider `0 1 0 4 0 0 4 2 2 0 1`:

* `]*1&<` Convert ones to zeros:

```
0 0 0 0 4 0 0 4 2 2 0 0 0

```
* `I.@:*` Signum and find indexes (ie, indexes of everything non-zero):

```
3 6 7 8

```
* `_2-~/\` Deltas of consecutive (non-overlapping) pairs:

```
3 1

```
* `1+2#` Duplicate in place and add 1:

```
4 4 2 2

```
* `-.&0` \- Does that equal the original input without zeroes or ones? (yes, in this case)

```
4 4 2 2

```
* `([:*/2|[:+/@:*;.1,~&1)*` Are there also no `1`s between any of the pairs?

```
_1 1 _1 3 _1 _1 3 1 1 _1 1

```

# Answer
> 4 votes
# Haskell, ~~64~~ 61 bytes

```
f[]=1>0
f(h:t)|r<-drop(h-1)t=[a`div`h*h|a<-[2..h]]++r==t&&f r

```

Try it online!

```
f[]=1>0    - if we reach end is solvable: output True
f(h:t)=    - head : tail
[a`div`h*h|a<-[2..h]]
           - we build the tail of h-block we expect
==take(h-1)t
           - and compare with the actual one
&&(f$drop(h-1)t) - then continue

```
* abusing the fact that `drop` and `take` can take negative amount (behaving like 0) on tail to handle both 0 and 1
* edit : concatenaing expected with rest of list and compared to rest of list

# Answer
> 3 votes
# JavaScript (V8), 45 bytes

```
a=>a.some(v=>c?a*!--c-v:(c=a=v)&&0*--c,c=0)|c

```

Try it online!

Output falsy if solutions exist.

```
a=>       // `a` is the given input array
a.some(   // try to find out some value violate spec
v=>       // `v` is current value
c?        // `c` is count down since last non-zero
a*!--c-v: // if c=1, we need to close the segment
          //          with value equals to previous `a`
          // if c>1, we need the value to be 0
          // if `v` is not what we want, `some` returns true
          // also count down `c`
(c=a=v)&& // if c=0 and v=0, ignore current value
          // if c=0 and v>0, assign `v` to `a` and `c`
0*--c,    // count down c
          // also return something falsy
c=0)      // count down is initialized to 0
|c        // test if there is an unmatched number left

```

# Answer
> 3 votes
# Brachylog, ~~19~~ 18 bytes

```
~c{+<2|h.~l?↔?b+}ᵐ

```

Try it online! (Times out for falsey test cases longer than seven elements.)

### Explanation

Checks every possible partition of the list until it finds a valid solution.

```
~c                  Construct a list of lists whose concatenation is the input list
  {             }ᵐ  The following predicate must succeed for each sublist:
                     Either:
   +                  The sum of the sublist
    <2                is less than 2
                      (in which case it's a bunch of 0's and at most one 1)
      |              Or:
       h              The first element of the sublist
        .             (which will be the output of this predicate)
         ~l?          is the length of the sublist
            ↔         and the sublist reversed
             ?        is the same as itself
              b       and the sublist with first element removed
               +      summed
                      equals the output of this predicate (previously declared
                       to be the first element of the sublist)

```

The second branch succeeds iff the sublist is a valid would-be line of the form \\$\[N, 0, \cdots, 0, N\]\\$:

* The head of the sublist is \\$N\\$.
* Its length is also \\$N\\$, so it can be filled in to form a line of \\$N\\$ numbers.
* It is a palindrome, which means its tail is also \\$N\\$.
* The sum of everything but the head is \\$N\\$. Since the tail is \\$N\\$ and all the numbers are nonnegative, all the numbers in the middle must be \\$0\\$.

# Answer
> 2 votes
# Charcoal, 30 bytes

```
¹Ｗθ«≔⊟θι¿›ι¹¿∨Φ⁻ι²∧θ⊟θ¬∧θ⁼ι⊟θ⎚

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for affirmative, nothing for negative. Explanation:

```
¹

```

Assume a solution exists.

```
Ｗθ«≔⊟θι

```

Loop over the cells (in reverse order, not that it matters here).

```
¿›ι¹

```

If the last cell `n` was greater than `1`, then...

```
¿∨Φ⁻ι²∧θ⊟θ¬∧θ⁼ι⊟θ

```

... if any of the next `n-2` cells is nonzero, or the following cell is not `n` or does not exist, then...

... clear the canvas, because there is no solution.

# Answer
> 1 votes
# Jelly, 37 bytes

```
’ȯ€Ø1F‘µTịĖs2ạ;2ị$$}¥/€‘1¦€2ị$ÐḟUƑƇ$Ƒ

```

Try it online!

Uses Jonah's trick to replace 1 with 2, 2; credit for that to him here.

# Answer
> 1 votes
# Retina 0.8.2, ~~52~~ 45 bytes

```
$
,
\d+
$*
1?,|(1(1)+)(?<-2>,)+\1,(?(2)^)

^$

```

Try it online! Link includes test cases. Edit: Saved 7 bytes thanks to @tsh. Explanation:

```
$
,

```

Add a trailing comma so that all numbers are followed by commas.

```
\d+
$*

```

Convert the numbers to unary.

```
1?,|(1(1)+)(?<-2>,)+\1,(?(2)^)

```

Match all cases of either 0 or 1 followed by a comma, or a number `n+1` repeated twice with `n` commas between (which represents `n-1` empty cells) and one following. A .NET balancing group is used to ensure the relationship between the numbers and the number of commas.

```
^$

```

Check to see whether everything was matched.

# Answer
> 1 votes
# Pip, ~~38~~ 37 bytes

```
!qR` [01]\b|( \d+)( 0)*\1`{(sNa)-b|x}

```

Regex solution. Takes input from stdin as a space-separated list of integers with a single leading space. Try it here! Alternately, here's a 39-byte version in Pip Classic: Try it online!

If the numbers were single-digit only, this could be **25 bytes**:

```
!qR`0|1|(\d)0*\1`{#a-b|x}

```

Try it online!

### Explanation

```
!qR` [01]\b|( \d+)( 0)*\1`{(sNa)-b|x}
 q                                     Read a line of stdin
  R`                     `             Find all non-overlapping matches of this regex:
     [01]\b                             A single 0 or 1
           |                            or
            ( \d+)                      Any other number
                  ( 0)*                 followed by zero or more 0's
                       \1               followed by the same number again
                          {         }  Replace each match with this function:
                            sNa         The number of spaces in the match
                           (   -b)      minus the value of the first capture group
                                        (Either the first branch was taken, in which
                                        case the capture group is unused and the
                                        expression is nil [falsey], or the second
                                        branch was taken and the length is correct,
                                        in which case the expression is 0 [falsey],
                                        or the length is incorrect, in which case
                                        the expression is nonzero [truthy])
                                  |     OR
                                   x    empty string
                                       (The effect is to remove correctly formatted lines
                                       from the input; incorrectly formatted lines are
                                       either left unchanged or replaced with 1's)
!                                      Return 1 if the resulting string is empty, else 0

```

---

Here's a non-regex solution in **40 bytes** that takes the list as command-line arguments and outputs via stderr (error message = falsey, no error = truthy):

```
W#Y@g2>y?POg#g>=y=g@Dy=$+g@\,y?g@>:@g;Vk

```

Try it online!

# Answer
> 1 votes
# SWI-Prolog, 131 bytes

```
t([]). t(L):-append(Q,W,L),g(Q),t(W). g([0]). g([1]). g(W):-append([H|L],Q,W),append(L,[H],Q),sum_list(L,0),length(L,X),X is H/2-1.

```

Prolog is hard to golf but it is ideal for this kind of problem.

Explanation:

```
% recursion stop condition
t([]).
% a testcase succeeds if the first part Q of the list is good
% and the second part W recursively also succeeds
t(L):-append(Q,W,L),g(Q),t(W).
% base cases: 0 and 1 are both good
g([0]).
g([1]).
% a longer list is good if it consists of the pattern HLLH
g(W):-append([H|L],Q,W),
append(L,[H],Q),
% and L consists of zeros
sum_list(L,0),
% and the length of L is half the border value minus 1
length(L,X),
X is H/2-1.

```

# Answer
> 1 votes
# 05AB1E, 21 bytes

```
.œεεćsOyθyg)Ëy2‹P~]Pà

```

Can probably be shorted, but this will do for now.

Try it online or verify all test cases.

**Explanation:**

```
.œ                 # Get all partitions of the (implicit) input-list:
  ε                # Map over each partition:
   ε               #  Map over each inner part-list:
    ć              #   Check if the first item of the list,
     sO            #   the sum of the list minus its first item,
       yθ          #   the last item of the list,
         yg        #   and the length of the list,
           )Ë      #   are all four equal to each other
                 ~ #   Or
             y  P  #   Check if all items in the list
              2‹   #   are either 0 and/or 1
  ]                # Close both maps
   P               # Check if all parts in a partition were truthy (product)
    à              # Check if any partition is truthy (max)
                   # (after which the result is output implicitly)

```

# Answer
> 0 votes
# sed `-E`, 50 bytes

My sed is rusty and I’m not totally happy with this, but *c’est la vie*. Takes input on stdin with a trailing space, prints `T` or `F`.

```
s/\b1 /&&/g
s/([0-9]+ )(0 )*\1//g
/[^0 ]/{cF
n}
cT

```

Attempt This Online!

---
Tags: code-golf, array, decision-problem, puzzle-solver
---


title: Blink the CAPS LOCK

text:
# Question
Title: Blink the CAPS LOCK
Most computer keyboards feature a small integrated LED light, indicating the current input mode, as controlled with the CAPS LOCK button.

Your task is to blink it:

* Turn it on;
* Wait for 0.5 (+/-0.1) seconds;
* Turn it off again.

Video footage of the LED blinking is highly appreciated !

## Rules

* You can blink a different LED (e.g. Scroll Lock, Num Lock, Wi-Fi status etc), if you wish, but it must be physically located on your keyboard;
* If your language is missing a subsecond `sleep` command, your program may use a 1 second delay instead, at a penalty of +2 bytes (that's for `0.`);
* Your program must blink at least once, what happens afterward is up to you, i.e. it can continue to blink (in which case you must wait for the same delay, before turning it on again), or halt e.t.c.;
* If the chosen LED is ON by default, on your system, you can assume that it has been explicitly switched off (e.g. manually), before the program is run;
* This is , the shortest answer in bytes wins.

## Leaderboard

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

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

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 130 votes
# Befunge (BEF32), ~~390~~ ~~334~~ 305 bytes

This is really silly, but as long as this site accepts the notion that the interpreter defines the language, I might as well abuse the rule. This code only works in Kevin Vigor's Win32 Befunge-93 Implementation, version 1.01 (I think the only version available). You can download the binary here.

```
p55p99+5p65*5p")"5p"M"3*"I~q"+\3*3445"|"2*"lm"2v
v"y"*3\*2"e/n"4\5"nnIn"*833*2"mn"4\7"nnIn"*833*<
>2*"yO"4"DJG"3*\2*55*3"T"4"DLG"3*\2*55*3"/~M"+\3*4446"~A"+4v
>+00p9p:v:"l'"*2"^D"4"l3"*2"^D"4"l"*54*2"^D"4"l"*2+94*2"^D"<
^1:g00-4_5"u1"*-:1+:1+"@"\0p"%"5*\0p"P"\0p@
Sleep kernel32.dll keybd_event user32.dll

```

Now normally you wouldn't expect this sort of challenge to be possible in a Befunge, but BEF32 is a Win32 port of a very old version of the reference implementation, and back then there was no bounds checking on the `p` (put) command. This effectively allows us to write to any location in memory, which ultimately lets us force the interpreter to execute arbitrary machine code.

Now we can't actually alter any of the existing code, since the .text section of the executable won't have write permissions. However, we can trick the system into executing an address in the .data section, by writing that address into the the runtime library's `atexit` table (at least I suspect that's what it is). The end result is that our code is automatically executed when the interpreter exits.

This relies on the fact that the executable is loaded at a fixed address, so we know exactly where everything is in memory - it assumedly wouldn't work if you overrode the default ASLR settings. It also relies on the .data section being executable, despite not having the executable attribute set, so again it most likely wouldn't work if you overrode the default DEP settings.

The code itself is essentially a copy of Mego's `keybd_event` technique translated into machine code:

```
6823B84000         push "keybd_event"
682FB84000         push "user32.dll"
6810B84000         push "Sleep"
6816B84000         push "kernel32.dll"
BB02000000         mov  ebx,2
               initloop:
89C7               mov  edi,eax
FF1594D14000       call LoadLibraryA
50                 push eax
FF1590D14000       call GetProcAddressA
4B                 dec  ebx
75EE               jnz  initloop
89C6               mov  esi,eax
               flashloop:
6A00               push 0
6A01               push 1
6A45               push 69
6A14               push 20
FFD6               call esi
6A00               push 0
6A03               push 3
6A45               push 69
6A14               push 20
FFD6               call esi
68F4010000         push 500
FFD7               call edi
EBE3               jmp  flashloop

```

This version of the code continues flashing forever (or at least until you kill the process), since that turned out to be easier to golf than a single flash.

And since everyone is posting animations, this is an approximation of what it looks like on my keyboard.

# Answer
> 73 votes
# AutoHotkey, ~~29~~ 26 bytes

*Thanks to @Dane for saving 3 bytes*

```
Loop{
Send,{VK14}
Sleep,500
}

```

I originally chose `NumLock` because it's one character shorter than `CapsLock`. The GIF below reflects that condition. It's the same effect as the altered code above. I could have gone with `VK90` above to make the GIF still be accurate but aligning with the original challenge felt better.

---

In honor of mbomb007's comment, here's a morse code message in **239 bytes**:

```
s:=000090901009011091100110090111109111901090190110901109091000091001101909101191000911190190109100001090191010919111901091011
Loop,123{
StringMid,c,s,A_Index,1
IfEqual,c,9
{
Sleep,2000
Continue
}
Send,{NumLock}
Sleep,%c%500
Send,{NumLock}
Sleep,500
}

```

Here are the first 30 seconds of that message:

# Answer
> 34 votes
# GFA-Basic 3.51 (Atari ST),  ~~61 56 43~~  35 bytes

This code will make the floppy drive LED blink forever at the required rate (`PAUSE 25` = pause for 25 / 50 second).

This would probably be shorter in assembly, but I don't have the appropriate tools at my fingertips. This is the size of the GFA-Basic listing once saved in .LST format and manually edited to remove useless whitespace, rename instructions to shorter strings and replace each `CR+LF` with a simple `CR`. Note that a final `CR` is required.

```
DO
i=i XOR2
SP &HFF8802,i
PA 25
LO

```

Will automatically expand to:

```
DO
  i=i XOR 2
  SPOKE &HFF8802,i
  PAUSE 25
LOOP

```

`SPOKE` is a supercharged `POKE` that first puts the 68000 in *supervisor* mode, so that it's allowed to access restricted memory areas (here: the *register write* address of the YM2149 soundchip, which is also responsible for some other I/O).

And yes: the LED is physically located on the keyboard ... I suppose.

*I don't have access to a real ST right now, so this is just a mockup.*

# Answer
> 24 votes
# fish \+ ckb, ~~56~~ 54 bytes

```
while cd;echo rgb (random)|tee /d*/*/*/c*;sleep .5;end

```

Blinks my entire keyboard in random colors, though since the number isn't 6 hex digits long it's a bit limited.

And yes, that shell glob is potentially dangerous. Works On My Machine™

Bonus script, 8 months later: This will go through all colors. Not golfed.

```
#!/usr/bin/fish
while true
        echo rgb (printf '%06x' (random 0 16777215)) | tee /dev/input/ckb*/cmd > /dev/null
        sleep 0.5
end

```

# Answer
> 21 votes
# Bash + amixer, 45 Bytes

```
a() { amixer set Master toggle
}
a;sleep .5;a

```

Blinks the mute light on my keyboard.

# Answer
> 19 votes
## C (Windows), 79 bytes

```
#include<windows.h>
k(n){keybd_event(20,69,n,0);}f(){k(1);k(3);Sleep(500);f();}

```

### Explanation

`keybd_event` is a (deprecated) Windows API function to send a keyboard event (keyup or keydown). `20` is the code for the Caps Lock key, `69` is the hardware scan code (I have no idea what that means), and `1` means keydown and `3` means keyup. A keypress is simulated by sending a keydown event immediately followed by a keyup event. One keypress is sent to turn on Caps Lock, then the program sleeps for 500 milliseconds, and then another keypress is sent to turn Caps Lock back off.

Thanks to Steadybox for a bunch of bytes saved

# Answer
> 16 votes
# MATLAB, ~~146~~ ~~136~~ 70

*Thanks to @Poke for removing 66 bytes!*

```
r=java.awt.Robot;while 1
r.keyPress(20)
r.keyRelease(20)
pause(.5);end

```

This uses Matlab's ability to call Java classes. The Caps Lock light is blinked in a loop by programmatically pressing and releasing `Caps Lock`.

Video or it didn't happen.

# Answer
> 16 votes
## x86 machine code for PC (e.g. MS-DOS COM file), 27 bytes

This machine code (displayed here with a Unicode rendering of the usual CP437 of PC BIOS) will blink the CAPS LOCK indicator forever on a PC:

```
j@▼î▐j`Z░φεê╪εÇ≤♦╞♦◙Ç<☺t∩δ∙

```

The code has been made so it contains no NULL bytes, and can thus be typed with the keyboard (using the Alt+XXX trick for extended characters) to create a COM file (e.g., using the `COPY CON blink.com` command under MS-DOS, in which case the output file will have to contain a spurious 28th byte, the `^Z` (EOF) character required to stop the copy operation).

The effect is achieved by directly sending commands to the keyboard controller of the PC (port 60h) to set the LED state (as a side-effect, it might set Num Lock and Scroll Lock LEDs to a random non-blinking state). The timing, to minimize the number of instructions, is achieved by using the countdown timer maintained by the BIOS at address `0040:0040` (it decrements every 54.925 ms, with 9 cycles the blinking cycle is 494.3 ms, which is within the allowed margin) — this counter is normally used by the BIOS to stop the floppy disk motor; as the floppy drive is not used by the program and the code is assumed to run in a single-task environment (e.g. DOS), playing with the floppy motor timer is not an issue.

The code runs fine under MS-DOS (tried with VirtualBox, it should also run fine on real hardware, although I didn't have the time yet to make a bootable MS-DOS USB stick to test). As it doesn't rely on any OS functions, it can even run without the operating system (e.g., by placing it in the boot sector of a disk). It requires at least a 80186 processor to run, because of the "immediate push" instructions used to shorten the code of some bytes.

Assembly source code:

```
  PUSH 0x40               ; pushes 0x0040 (BIOS data segment) on the stack
  POP DS                  ; pops it into DS segment selector
  MOV SI, DS              ; copies DS to SI (timer counter is nicely placed at 40:40)
  PUSH 0x60               ; pushes 0x0060 (kbd controller port) on the stack
  POP DX                  ; pops it to DX
loop:
  MOV AL, 0xED            ; 8042 keyboard controller 'set mode indicators' command
  OUT DX, AL              ; outputs the command to the keyboard contr oller
  MOV AL, BL              ; copy BL register to AL
  OUT DX, AL              ; outputs LED state to keyboard controller
  XOR BL, 4               ; toggles bit 2 (CAPS LOCK) for next iteration
  MOV BYTE PTR[SI], 0x0A  ; sets floppy motor countdown timer to 10
wait:
  CMP BYTE PTR[SI], 0x01  ; checks if timer reached 1
  JE loop                 ; if yes, time for next iteration
  JMP wait                ; if not, checks again

```

Hexadecimal dump of the assembled code:

```
6A 40 1F 8C DE 6A 60 5A B0 ED EE 88 D8 EE 80 F3 04 C6 04 0A 80 3C 01 74 EF EB F9

```

Here is the result running under MS-DOS in VirtualBox (doesn't work with DosBox, presumably because the keyboard controller is not completely emulated):

(sorry for the shaky video).

# Answer
> 13 votes
# SmileBASIC, ~~36~~ 23 bytes

```
XON MIC
WAIT 30XOFF MIC

```

Blinks the microphone status light. (video coming soon)

# Answer
> 13 votes
# Python2 - 108 bytes

Does the capslock key. Interestingly, this actually turns on just the LED itself without affecting the keyboard or pressing the key. You can change the `4` at the end to `2` to do numlock. `6` does both.

```
import fcntl,os,time;exec"fcntl.ioctl(os.open('/dev/console',os.O_NOCTTY),19250,%d);time.sleep(.5);"*2%(4,0)

```

# Answer
> 8 votes
# shell+numlockx, ~~40~~ 35 bytes

\[Saved 5 bytes thanks to Ryan.\]

Continually blinks the NumLock light on unixish systems.

```
numlockx toggle;sleep .5;exec sh $0

```

# Single blink, 33 bytes

```
numlockx on;sleep .5;numlockx off

```

# Answer
> 8 votes
# PowerShell, 71 bytes

```
for(){(New-Object -c WScript.Shell).SendKeys('{NUMLOCK}');sleep -m 500}

```

### Notes

* Blinks forever
* Uses `NUM LOCK` to save a byte.

# Answer
> 7 votes
# VBS, 75 bytes

```
do
wscript.sleep 500
Createobject("wscript.shell").sendkeys"{numlock}"
loop

```

Repeatedly blinks Num Lock key, as `numlock` is 1 byte shorter than `capslock`.

# Answer
> 7 votes
## C#, ~~215~~ ~~202~~ ~~198~~ ~~195~~ 185 bytes

~~Without realising I have done the "same" code as this answer by @Mego, go check it out!.~~

```
[System.Runtime.InteropServices.DllImport("user32")]static extern void keybd_event(int v,int s,int f,int e);n=>{for(n=0;;System.Threading.Thread.Sleep(125))keybd_event(20,69,n++&2,0);};

```

*Saved 13 bytes thanks to @Metoniem*
*Saved 10 bytes thanks to @VisualMelon*

Here's a full formatted version showing it working:

```
class P
{
    [System.Runtime.InteropServices.DllImport("user32")]
    static extern void keybd_event(int v, int s, int f, int e);

    static void Main()
    {
        System.Action<int> a = n =>
        {
            for (n = 0; ; System.Threading.Thread.Sleep(125))
                keybd_event(20, 69, n++ & 2, 0);
        };

        a(0);
    }
}

```

---

For bonus fun change `n++ & 2` to `n+=2 & 2` and watch the num lock and caps lock keys alternate in flashing on and off. I have no idea why that happens because it shouldn't but it looks "cool".

# Answer
> 6 votes
# Java 7, ~~121~~ ~~118~~ 113 bytes

```
void a()throws Exception{java.awt.Robot r=new java.awt.Robot();r.keyPress(20);r.delay(500);r.keyRelease(20);a();}

```

A single press and release just triggers the state; it doesn't blink it. Thus we may as well loop it and it looks like recursion is the cheapest manner of doing that.

# Answer
> 6 votes
# Linux terminal, 8+11 = 19 bytes

File `f` = `1B 5B 33 71 1B 5B 30 71`

`native@shell:~$` `pv f -q -L8`

## WAT?

According to ECMA-48, `1B` starts terminal control escape sequence.

Caps on =`1B 5B 33 71`, then off = `1B 5B 30 71`

`pv` progress view

`f` file

`-q` quiet

`-L8` 8 bytes/s = 0.5 sec delay

## Usage

Prepare

```
#Create file
echo "1B 5B 33 71 1B 5B 30 71"|xxd -r -p > f

#Install progress view utility
sudo apt install pv

```

`Ctrl`+`Alt`+`F6` switch to native console

run `pv f -q -L8`

`Ctrl`+`Alt`+`F7` switch back

# Answer
> 5 votes
**JavaScript, 82 bytes**

**Credit goes to @FinW** actually, I just changed old function to new ES6 arrow function in order to save some bytes. And becuase I don't have enough points to comment I wrote a new reply.

Edit - deleted brackets to save another 2 bytes.

```
o=new ActiveXObject("WScript.Shell");setInterval(()=>o.SendKeys("{NUMLOCK}"),500);

```

His code looked like this

```
o=new ActiveXObject("WScript.Shell");setInterval(function(){o.SendKeys("{NUMLOCK}")},500);

```

# Answer
> 4 votes
# Scala, 84 83 78 bytes

### Edit: Saved 1 byte thanks to @TheLethalCoder,

He suggested using `1>0` in place of `true`.

### Edit 2: Saved 5 bytes thanks to @Corvus\_192,

He suggested using infix notation and dropping the parentheses after the constructor

```
while(1>0){val r=new java.awt.Robot;r keyPress 20;r keyRelease 20;r delay 500}

```

## Ungolfed:

```
while(1>0) {
    val r=new java.awt.Robot()
    r.keyPress(20)
    r.keyRelease(20)
    r.delay(500)
}

```

Standard Scala port of @Poke's Java answer. Type it directly into the Scala interpreter prompt.

A video of it blinking both my Caps Lock LED and my OSD to boot!

# Answer
> 4 votes
**Bash, 31 bytes**

```
xset led 1;sleep .5;xset -led 1

```

Works in X, without root access ! (If it does not work for you, see the init function of the code below to make sure xkbcomp is configured correctly)

And a bonus script to send any morse code through caps lock (not golfed) :

```
unit=0.15
id=1
function init {
        file=/tmp/blink_tmp
        xkbcomp $DISPLAY $file
        sed -i 's/!allowExplicit/allowExplicit/' $file
        xkbcomp $file $DISPLAY &>/dev/null
        rm $file
}
if [[ -z $1 ]]; then
        echo "Usage : blink [message]"
        exit 1
fi
init
function finish {
        off
}

function on {
#su -c 'setleds -L +caps < /dev/console'
xset led $id
}
function off {
#su -c 'setleds -L -caps < /dev/console'
xset -led $id
}
function slp {
        sleep $(echo "$unit*$1" | bc)
}
function dot {
on
slp 1
off
slp 1
}
function dash {
on
slp 3
off
slp 1
}
function gap {
        slp 3
}
function morse {
        msg=$1
        for (( i=0; i<${#msg}; i++ )); do
                char=${msg:$i:1}
                if [[ $char == "-" ]]; then
                dash
                elif [[ $char == "." ]]; then
                dot
                elif [[ $char == "/" ]]; then
                gap
                fi
        done
}
while true; do
        morse $1
done

```

Exemple : `blink "...././.-../.-../---//.--/---/.-./.-../-..///"`

# Answer
> 3 votes
**Bash + Xdotool, 36 bytes**

```
for((;;)){ xdotool key 66;sleep .5;}

```

Just execute it in a bash shell. It needs to be in a graphical environment. Infinite loop from here. Changed Num\_Lock to 66 to save 6 bytes, and thanks to @Michael Kjörling for 2 bytes.

# Answer
> 3 votes
# Python using pyautogui: 126 143 115 103 bytes

*Thanks to @nedla2004 for saving 12 bytes*

```
from pyautogui import*
import time
while 1:keyDown('capslock');time.sleep(.5);keyUp('capslock')pslock')

```

# Answer
> 3 votes
# xdotool, 20 bytes

```
key -delay=500 66 66

```

Presses the key **66** aka *Caps Lock* twice, with a delay of **500 ms** between key presses.

Note that xdotool is a scripting language; it can be run from a file and it even supports shebangs. Since its `exec` command allow running external programs, it is capable of addition and primality testing, so it satisfies our definition of programming language.

### Test run

```
$ cat blink.xdo; echo
key -delay=500 66 66
$ xdotool blink.xdo

```

# Answer
> 2 votes
# Bash + setleds, 43 bytes

```
setleds -D +caps;sleep 0.5;setleds -D -caps

```

Pretty simple. Uses `setleds` to toggle the light.

# Answer
> 2 votes
# Bash, 103 bytes

```
cd /sys/class/leds/asus\:\:kbd_backlight;while true;do echo 3;sleep .5;echo 0;sleep .5;done>brightness

```

Must be run as root.

Does flashing the entire keyboard backlight work? (video to come when I get home)

# Answer
> 2 votes
# JavaScript, 90 bytes

```
o=new ActiveXObject("WScript.Shell");setInterval(function(){o.SendKeys("{NUMLOCK}")},500);

```

It requires `ActiveX` meaning it will only run on IE (Edge *doesn't* support it, though). It flashes the NUMLOCK key because, as with other answers, it is shorter than CAPSLOCK or SCROLLLOCK.

## Ungolfed

```
shell = new ActiveXObject("WScript.Shell");
setInterval(
    function(){
        shell.SendKeys("{NUMLOCK}")
    }
,500);

```

# Answer
> 2 votes
# Batch File (With help of vbs), 74+2=76 bytes

```
echo Createobject("wscript.shell").sendkeys"{numlock}">z.vbs&z&timeout 1&z

```

Partially based on Trelzevir's answer.

`.vbs` is automatically included in `PATHEXT`.

# Answer
> 2 votes
# Bash, 33 Bytes

This assumes Num-Lock to be on before it is run. Switch `off` and `on` otherwise. Requires the `numlockx` package obviously ;)

```
numlockx off;sleep .5;numlockx on

```

**Edit:**

Saw Alex Howansky has already posted this solution, yet not marked it with Bash and I just searched the site for "Bash".

# Answer
> 2 votes
# C (msvc) \+ Win32, 51 bytes

```
main(i){main(i+keybd_event(20,69,i%4,Sleep(125)));}

```

# Answer
> 1 votes
## Kotlin Script, 72 bytes

While not smallest one, still it's pretty good. I'm loving kotlin's *run* for some things, and this is one of them ( smaller than val r = java.awt.Robot() because we don't need both r. and val r =. Still, it's longer than MathLab )

```
java.awt.Robot().run{while(1>0){keyPress(20);keyRelease(20);delay(500)}}

```

## Ungolfed:

```
java.awt.Robot().run {
    while(1>0) {
        keyPress(20)
        keyRelease(20)
        delay(500)
    }
}

```

# Answer
> 1 votes
# Python3 , 55 49 bytes

*Thank you @NoOneIsHere for -4 bytes!*

This includes packages: pyautogui and `time` modules
Code:

```
while(1):pag.press("capslock");time.sleep(0.5)

```

Thank you @NoOneIsHere for -4 bytes!
The key in action:

# Answer
> 1 votes
# VBA, 82 Bytes

Anonymous VBE Immediate window function that takes no input and annoys the user indefinitely. Depedant upon the windows kernel32 function sleep that is declared below.

### Sleep Declaration (Win-32)

```
Declare Sub Sleep Lib "kernel32" (ByVal M&)

```

### Sleep Declaration (Win-64, + 8 Bytes)

```
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal M&)

```

### Anonymous VBE immediate window function

```
Do:SendKeys"{CAPSLOCK}":Sleep 500:DoEvents:Loop

```

# Slightly more fun version, 97 Bytes

A set of mutually recursive subroutines that indefinitely annoys the user

```
Sub A
Application.OnTime Now+5.8E-6,"B"
End Sub

```

```
Sub B
DoEvents
SendKeys"{CAPSLOCK}"
A
End Sub

```

# Questionable version, 66 + 2 Bytes

I'm not sure if having to declare a function from a dll counts as having an inbuilt function so, in the case that it does not, then here is a 66+2 byte version that waits 1 second

```
Do:DoEvents:Application.Wait Now+#0:0:1#:SendKeys"{CAPSLOCK}":Loop

```

# Answer
> 1 votes
# 按键精灵, 41 bytes

```
For 2
KeyPress"Num Lock",1
Delay 500
Next

```

# Answer
> 0 votes
# Clojure, 134 bytes

```
(repeatedly(fn[](Thread/sleep 500)(.setLockingKeyState(java.awt.Toolkit/getDefaultToolkit)java.awt.event.KeyEvent/VK_CAPS_LOCK true)))

```

Loops infinitely, constantly resetting the caps lock's key state. For some reason, setting it to `true` over and over again toggles it, even though that's not supposed to happen.

Those imports are killer. Might try going the route of the Java answer and use `Robot` instead; see if that helps.

Thanks for posting this challenege. I'm currently sitting in a chair at the dentist waiting to get a tooth pulled. The distraction is appreciated!

The GIF ended up being too big to upload.

```
(repeatedly ; Implicit infinite loop
  (fn[]
     (Thread/sleep 500)

     (.setLockingKeyState
       (java.awt.Toolkit/getDefaultToolkit)
       java.awt.event.KeyEvent/VK_CAPS_LOCK
       true)))

```

---
Tags: code-golf, keyboard, hardware
---


title: Multiplying substrings

text:
# Question
Title: Multiplying substrings
Write a program that takes two integers as an input; the first can be any integer and the second is less than or equal to the number of digits in the first number. Let these numbers be `a` and `b` respectively.

The program will do the following

* Concatenate a minimal number of `1`s to the end of `a` so the number of digits in `a` is divisible by `b`.
* Split `a` along every `b` digits.
* Multiply the digits in each section together.
* Concatenate the products together (if one of the numbers is zero, then concatenate `0`).
* Repeat this process until a number with strictly fewer than `b` digits is formed. Print this as the output, as well as the number of the process is repeated. Units are not necessary, but some form of separation between the final number and number of iterations is.

In the following test cases, the individual steps are shown for the purpose of understanding. It is not necessary for your program to display the steps.

**Test case 1**

`1883915502469, 3`

*Steps*

```
1883915502469          //Iteration 1
188391550246911
188 391 550 246 911
64 27 0 48 9
64270489               //Iteration 2
642704891
642 704 891
48 0 72
48072                  //Iteration 3
480721
480 721
0 14
014                    //Iteration 4
0

```

*Sample Output*: `0, 4`

**Test case 2**

`792624998126442, 4`

*Steps*

```
792624998126442        //Iteration 1
7926249981264421
7926 2499 8126 4421
756 648 96 32
7566489632             //Iteration 2
756648963211
7566 4896 3211
1260 1728 6
126017286              //Iteration 3
126017286111
1260 1728 6111
0 112 6
01126                  //Iteration 4
01126111
0112 6111
0 6
06

```

*Sample Output*: `06, 4`

---

The program must return an error (or just not print anything) if `b>len(a)`. Also, `b` cannot equal 1 or the program will result in an infinite loop.

---

This is code golf, so standard rules apply. Shortest code in bytes wins.

# Answer
# Python, 156 bytes

```
g=lambda a,d,c=0,k=-1,j=''.join:d>(l:=len(a))and(a,c/c*c)or g(j([str(-[k:=k*x for x in map(int,j((a+l%d*"1")[i:i+d]))][k:=-1])for i in range(0,l,d)]),d,-~c)

```

Attempt This Online!

Takes in a string and an integer, causes a DivideByZero error if the input is invalid.

---

# Python 3 + `functools` \+ `operator`, 137 bytes

```
g=lambda a,d,c=0,j=''.join:d>(l:=len(a))and(a,c/c*c)or g(j([str(reduce(mul,map(int,j((a+l%d*"1")[i:i+d]))))for i in range(0,l,d)]),d,-~c)

```

Attempt This Online!
> 3 votes

# Answer
## Perl 6, 116 bytes

```
my ($a,$b)=@*ARGS;for 0..* {if $b>$a.chars {$_&&say "$a,$_";last};$a=map({[*] @_},($a~1 x$b-1).comb.rotor($b)).join}

```

```
my ($a,$b)=@*ARGS;
for 0..* {
  if $b>$a.chars {$_&&say "$a,$_";last}; # you need a ｢;｣ if you remove the newline
  $a=map(
    {[*] @_},
    ($a~1 x$b-1).comb.rotor($b)
  ).join
}

```
> 2 votes

# Answer
# Python 3 + `functools` \+ `operator`, ~~242~~ ~~241~~ 205 bytes

Shorter version (thanks 97.100.97.109!)

```
def g(a,b):
 c,d,j=0,int(b),''.join
 while len(a)>=d:a=j(map(str,[reduce(mul,map(int,[*j(u)]))for u in zip(*[iter([a+"1"*n for n in range(d)if not len(a+"1"*n)%d][0//(d<=len(a))])]*d)]));c+=1
 return (a,c)

```

Original explained version:

```
def g(a,b):
 c=0
 while len(a)>=int(b):a="".join(map(str,[reduce(mul,map(int,u))for u in map(list,map(''.join,zip(*[iter([a+"1"*n for n in range(int(b))if not len(a+"1"*n)%int(b)][0])]*int(b))))]));c+=1
 return None if int(b)>len(a)else(a,c)

```

This was a fun one! I wish I could've made it a one-liner but there was no real way to do that without massively increasing the length. Takes input as two strings, returns a 2-tuple of a string and an int (or `None` if `b>len(a)`)

## Explanation

```
def challenge(a,b):
  c=0
  while len(a) >= int(b):
    a="".join(
      map(str,[
        reduce(mul,map(int,u)) # Multiply the digits together. Uses reduce from functools and mul from operator, works similarly to sum() but for multiplication
        for u in map(list,map(''.join,
                              zip(*[iter(
                                [a+"1"*n for n in range(int(b)) if not len(a+"1"*n)%int(b)][0] # Do the 1 concatenation
                              )]*int(b))
                             ) # Split a along every b digits
                    ) # Split those strings into lists
      ]) # Convert to a list of strings
    ) # Concatenate the products together
    c+=1
  return None if int(b)>len(a) else(a,c) # I don't really like the "return None if invalid input" requirement, but ah well

```
> 2 votes

# Answer
# CJam, 42 bytes

```
q~:N;Ab{_N(>}{_N/)N1e]a+::*s:~}w])S@,_])g*

```

Test it here.
> 1 votes

# Answer
# Pyth, 32 bytes

```
IglzQf<l=zjk*MsMMc+z*\1%_lzQQQ)z

```

Demonstration

Takes input on two lines, `a` followed by `b`. Gives output on two lines, operations followed by result.

Pad: `+z*\1%_lzQ`

Chop: `c ... Q`

Convert to list of ints: `sMM`

Take products: `*M`

Convert back to str: `jk`

Assign back: `=z`

Check for termination: `<l ... Q`

Print iterations taken: `f ... )`

Print result: `z`

Initial check of whether to print anything at all: `IglzQ`
> 1 votes

# Answer
# Ruby, 139 bytes

```
f=->n,b,i=1{c=[*n.scan(/.{#{b=b.to_i}}/),*$'[0]&&$'.ljust(b,?1)].map{_1.chars.map(&:to_i).reduce:*}*""
c.size<b ?[c,i]:f[c,b,i+1]}
p f[*$*]

```

Attempt This Online!

## Explanation

```
f = ->n,b,i=1{                    # Recursive lambda definition; n is the number, b is the target length, i is the number of iterations
  c = [                             # Make an array of...
    *n.scan(/.{#{b=b.to_i}}/),        # the whole sections of length b
    *$'[0] && $'.ljust(b, ?1)         # plus, if there’s stray letters, the final section padded to length b
  ].map{
    _1.chars.map(&:to_i).reduce :*    # Multiply each section’s digits
  } * ""                            # Join back together

  c.size < b ?                      # If we’re under the target length...
    [c, i] :                          # return the remaining string and iteration count
    f[c, b, i+1]                      # otherwise call itself recursively, incrementing the iteration count
}

p f[*$*]                          # $* is ARGV; splat it into f's arguments

```
> 1 votes

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


# Question
Title: Write a program for splitting the string with alternative spaces
Write a program in the minimum number of bytes that prints a string split into chunks of every length from 1 to the string's length (ascending and then descending), separated by spaces.

## Example

```
Input : abcdef
Output: a b c d e f
        ab cd ef
        abc def
        abcd ef
        abcde f
        abcdef
        abcde f
        abcd ef
        abc def
        ab cd ef
        a b c d e f

```

# Answer
> 6 votes
# Ruby, ~~84~~ 81 characters

```
i=gets.chop
puts (a=(1..i.size).map{|n|i.scan(/.{0,#{n}}/)*' '})+a.reverse[1..-1]

```

The magic is in the regex: `i.scan(/.{0,#{n}}/)`. Since Ruby does regex interpolation too, it will become

```
i.scan(/.{0,1}/)
i.scan(/.{0,2}/)
...

```

This means it will grab as many characters as it can, limited to `n`. `n` progressively gets bigger, and is used to generate the first half of the output.

Then I just call `reverse` to generate the second half. I had to use `[1..-1]` in order to avoid repeating the middle line (what that does is basically chop off the first element of the array).

Sample run:

```
c:\a\ruby>spacesplitgolf.rb
CodeGolfStackExchange         // (this is the input)
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e

```

# Answer
> 4 votes
### GolfScript, 22 characters

```
:I,,{)I/' '*n+}%.-1%1>

```

Try the example here.

```
> abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

*Code explained:*

```
:I          # Save input to variable I
,,          # Create array [0..n)
{
  )         # Increment loop variable by 1
  I/        # Split input into chunks with as many characters
  ' '*      # Join with spaces
  n+        # Append newline
}%
.-1%1>      # Create reverse copy (minus first element)

```

# Answer
> 4 votes
# Smalltalk (Smalltalk/X) (137 chars)

```
s := Stdin nextLine.
(1 to:s size),(s size-1 downTo:1) do:[:n |
 ((s asCollectionOfSubCollectionsOfSize:n) asStringWith:' ') printNL]

```

### output (first line is input):

```
abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

# Answer
> 3 votes
# J - ~~32~~ 27 char

Thanks to randomra for improvements.

```
(,&' '\(,@)"{~#-~|@i:@<:@#)

```

Explained:

* `<:@#` \- One less than the length of the string.
* `|@i:` \- Count from that number down to 0, then back up to that number. (J has weird primitives!)
* `#-~` \- Subtract from each of those numbers the length. When you do the math, the result is that you count from -1 to the negation of the length and back up.
* `u\(,@)"{~` \- For each negative integer, apply the verb `u` on non-overlapping infixes of the string, with length the negative of the integer, and then run it into a single string. So e.g. for `_2` it will split the string up into non-overlapping pairs of letters, apply `u`, then make a string back of all the new infixes.
* `,&' '` \- Append a space. (This fills in `u` above.)

Usage:

```
   (,&' '\(,@)"{~#-~|@i:@<:@#) 'abcdef'
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

# Answer
> 2 votes
### Delphi XE3 - WayToMany characters (WayToMany==321 261 245)

Im sure I can get this shorter so consider this as Work In Progress ^.^

**Edits:**
*Removed use of array making 2 units redundant saving a total of 61 chars*
*Removed useless begin..end for loop saving 16 chars*

```
{$APPTYPE CONSOLE}uses idglobal;var i,st:int16;s,r:string;p:boolean;begin readln(s);st:=1;p:=true;repeat r:='';for I:=1to Length(s)do r:=r+iif(i mod st=0,s[i]+' ',s[i]);writeln(r);if st=length(s)then p:=false;st:=iif(p,st+1,st-1);until st<1;end.

```

### With indent

```
{$APPTYPE CONSOLE}
uses idglobal;
var
i,st:int16;
s,r:string;
p:boolean;
begin
readln(s);
st:=1;
p:=true;
repeat
  r:='';
  for I:=1to Length(s)do
    r:=r+iif(i mod st=0,s[i]+' ',s[i]);
  writeln(r);
  if st=length(s)then
    p:=false;
  st:=iif(p,st+1,st-1);
until st<1;
end.

```

Result: (first line is input)

# Answer
> 2 votes
## Python 94 (bit verbose, but that;s Python)

```
s=raw_input();print'\n'.join(' '.join(map(''.join,zip(*[iter(s)]*n)))for n in range(1,len(s)))

```

# Answer
> 2 votes
# Rebol (144 chars)

```
s: input o:[]repeat i(length? s) - 1[t: copy s forskip t i + 1[insert t" "]append o next t]append o reverse append copy o s forall o[print o/1]

```

### Un-golfed:

```
s: input
o: []

repeat i (length? s) - 1 [
    t: copy s
    forskip t i + 1 [insert t " "]
    append o next t
]

append o reverse append copy o s

forall o [print o/1]

```

### Usage example:

```
rebol script.reb <<< "abcdef"
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

# Answer
> 2 votes
## R, 95

```
x=scan(,"");z=1:nchar(x);for(i in c(z,rev(z)[-1]))cat(gsub(paste0("(.{",i,"})"),"\\1 ",x),"\n")

```

(based on regular expressions)

Example:

```
> x=scan(,"");z=1:nchar(x);for(i in c(z,rev(z)[-1]))cat(gsub(paste0("(.{",i,"})"),"\\1 ",x),"\n")
1: abcdef
2:
Read 1 item
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

# Answer
> 2 votes
# JavaScript - 242

I'm new to CodeGolf (and JS as well) and this is my first try. Any suggestions are welcome :)

```
function f(s){var i,j,a=s.split(''),t;for(i=1;i<=a.length;i++){t='';for(j=1;j<=a.length;j++){t+=a[j-1];if(j%i==0)t+=' ';}
console.log(t);}
for(i=a.length;i>0;i--){t='';for(j=1;j<=a.length;j++){t+=a[j-1];if(j%i==0)t+=' ';}
console.log(t);}}

```

**Example:**

```
>>> f('CodeGolfIsAwesome');

C o d e G o l f I s A w e s o m e
Co de Go lf Is Aw es om e
Cod eGo lfI sAw eso me
Code Golf IsAw esom e
CodeG olfIs Aweso me
CodeGo lfIsAw esome
CodeGol fIsAwes ome
CodeGolf IsAwesom e
CodeGolfI sAwesome
CodeGolfIs Awesome
CodeGolfIsA wesome
CodeGolfIsAw esome
CodeGolfIsAwe some
CodeGolfIsAwes ome
CodeGolfIsAweso me
CodeGolfIsAwesom e
CodeGolfIsAwesome
CodeGolfIsAwesom e
CodeGolfIsAweso me
CodeGolfIsAwes ome
CodeGolfIsAwe some
CodeGolfIsAw esome
CodeGolfIsA wesome
CodeGolfIs Awesome
CodeGolfI sAwesome
CodeGolf IsAwesom e
CodeGol fIsAwes ome
CodeGo lfIsAw esome
CodeG olfIs Aweso me
Code Golf IsAw esom e
Cod eGo lfI sAw eso me
Co de Go lf Is Aw es om e
C o d e G o l f I s A w e s o m e

```

# Answer
> 2 votes
## Perl, ~~77~~ 71

Better late, than never (and since so far no Perl solution):

```
chomp($s=<>);say$s=~s/.{$_}/$& /gr for@a=1..length$s,reverse@a[-@a..-2]

```

Requires `5.014` because of `r` modifier. Uses 'say' feature. And

```
echo CodeGolfStackExchange| perl -M5.010 spaces.pl
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e

```

# Answer
> 2 votes
# CJam, ~~20 19~~ 18 bytes

Not a valid entry as CJam was created sometime after this question and moreover, this code is using some of the even newer features of the language.

```
q:Q,{)Q/S*N}%_W%3>

```

1 byte saved thanks to Martin.

**Explanation**:

```
q:Q,                   "Read the input, store it in Q and take its length";
    {      }%          "Map over 0 to length - 1";
     )Q/               "Increment iterator and split Q into pieces of length iterator";
        S*N            "Join by space and add new line";
              _W%      "Copy the mapped string array and reverse it";
                 3>    "Remove the first 3 elements, which comprise of 2 new lines and";
                       "the original string which should appear once only";

```

Example input:

```
CodeGolfStackExchange

```

Output:

```
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e

```

Try it online here

# Answer
> 1 votes
## D - ~~178~~ 176

**Golfed**:

```
import std.stdio,std.range;void main(string[]a){int l=a[1].length;for(int i=1;i<=l;++i)a[1].chunks(i).join(" ").writeln;for(int i=l-1;i>0;--i)a[1].chunks(i).join(" ").writeln;}

```

**Un-golfed**:

```
import std.stdio, std.range;

void main( string[] a )
{
    int l = a[1].length;

    for( int i = 1; i <= l; ++i )
        a[1].chunks( i ).join( " " ).writeln;

    for( int i = l - 1; i > 0; --i )
        a[1].chunks( i ).join( " " ).writeln;
}

```

**Example 1**:

```
F:\Code\D\Other>rdmd spaces.d abcdef
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

**Example 2**:

```
F:\Code\D\Other>rdmd spaces.d CodeGolfStackExchange
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e

```

# Answer
> 1 votes
# k \[50 chars\]

```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}

```

### Example

```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}"abcdef"

"a b c d e f"
"ab cd ef"
"abc def"
"abcd ef"
"abcde f"
"abcdef"
"abcde f"
"abcd ef"
"abc def"
"ab cd ef"
"a b c d e f"

```

### Example 2

```
{x c,1_|c:{1_,/-1,/:(y*!-_-(#x)%y)_x}[!c]'1+!c:#x}"CodeGolfStackExchange"

"C o d e G o l f S t a c k E x c h a n g e"
"Co de Go lf St ac kE xc ha ng e"
"Cod eGo lfS tac kEx cha nge"
"Code Golf Stac kExc hang e"
"CodeG olfSt ackEx chang e"
"CodeGo lfStac kExcha nge"
"CodeGol fStackE xchange"
"CodeGolf StackExc hange"
"CodeGolfS tackExcha nge"
"CodeGolfSt ackExchang e"
"CodeGolfSta ckExchange"
"CodeGolfStac kExchange"
"CodeGolfStack Exchange"
"CodeGolfStackE xchange"
"CodeGolfStackEx change"
"CodeGolfStackExc hange"
"CodeGolfStackExch ange"
"CodeGolfStackExcha nge"
"CodeGolfStackExchan ge"
"CodeGolfStackExchang e"
"CodeGolfStackExchange"
"CodeGolfStackExchang e"
"CodeGolfStackExchan ge"
"CodeGolfStackExcha nge"
"CodeGolfStackExch ange"
"CodeGolfStackExc hange"
"CodeGolfStackEx change"
"CodeGolfStackE xchange"
"CodeGolfStack Exchange"
"CodeGolfStac kExchange"
"CodeGolfSta ckExchange"
"CodeGolfSt ackExchang e"
"CodeGolfS tackExcha nge"
"CodeGolf StackExc hange"
"CodeGol fStackE xchange"
"CodeGo lfStac kExcha nge"
"CodeG olfSt ackEx chang e"
"Code Golf Stac kExc hang e"
"Cod eGo lfS tac kEx cha nge"
"Co de Go lf St ac kE xc ha ng e"
"C o d e G o l f S t a c k E x c h a n g e"

```

# Answer
> 1 votes
# C# - ~~182~~ 176

```
using C=System.Console;class P{static void Main(string[]p){int l=p[0].Length,i=-l,j;for(;++i<l;){for(j=0;++j<=l;)C.Write(p[0][j-1]+(j%(i>0?l-i:l+i)>0?"":" "));C.WriteLine();}}}

```

Ungolfed:

```
using C=System.Console;

class P
{
    static void Main(string[] p)
    {
        int l=p[0].Length,i=-l,j;
        for (; ++i < l;)
        {
            for(j=0;++j<=l;)C.Write(p[0][j-1]+(j%(i>0?l-i:l+i)>0?"":" "));
            C.WriteLine();
        }
    }
}

```

Output:

```
D:\>program CodeGolfStackExchange
C o d e G o l f S t a c k E x c h a n g e
Co de Go lf St ac kE xc ha ng e
Cod eGo lfS tac kEx cha nge
Code Golf Stac kExc hang e
CodeG olfSt ackEx chang e
CodeGo lfStac kExcha nge
CodeGol fStackE xchange
CodeGolf StackExc hange
CodeGolfS tackExcha nge
CodeGolfSt ackExchang e
CodeGolfSta ckExchange
CodeGolfStac kExchange
CodeGolfStack Exchange
CodeGolfStackE xchange
CodeGolfStackEx change
CodeGolfStackExc hange
CodeGolfStackExch ange
CodeGolfStackExcha nge
CodeGolfStackExchan ge
CodeGolfStackExchang e
CodeGolfStackExchange
CodeGolfStackExchang e
CodeGolfStackExchan ge
CodeGolfStackExcha nge
CodeGolfStackExch ange
CodeGolfStackExc hange
CodeGolfStackEx change
CodeGolfStackE xchange
CodeGolfStack Exchange
CodeGolfStac kExchange
CodeGolfSta ckExchange
CodeGolfSt ackExchang e
CodeGolfS tackExcha nge
CodeGolf StackExc hange
CodeGol fStackE xchange
CodeGo lfStac kExcha nge
CodeG olfSt ackEx chang e
Code Golf Stac kExc hang e
Cod eGo lfS tac kEx cha nge
Co de Go lf St ac kE xc ha ng e
C o d e G o l f S t a c k E x c h a n g e

```

**Edit**: now using parameters instead of ReadLine().

# Answer
> 1 votes
# JavaScript 127

```
function f(s) {
o=s+'\n'
for(i=s.length;--i;){
l='',j=0
while((p=s.substr(i*j++,i)))l+=p+' '
l+='\n',o=l+o+l
}
console.log(o)
}

```

# Answer
> 1 votes
## **Python - 153**

```
a=raw_input()
k=0
b=len(a)
for i in range(b+1)+range(b-1):
 k+=1
 p=[i,b-2-i][k>b]
 s=a
 if kb+1:
    for j in a[p::p+1]:s=s.replace(j, j+" ",1)
    print s

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
żvẇ∞⁋

```

Try it Online!

```
  ẇ   # Cut into slices of length...
 v    # Each of...
ż     # Range from 1 to length of input
   ∞  # Mirror
    ⁋ # Join by newlines, joining each line with spaces

```

# Answer
> 0 votes
# Q, 34

```
{a,1_(|)a:" "sv'(1+(!)(#)x)cut\:x}

```

# Answer
> 0 votes
# C - ~~134~~ 132

Maximum 8 characters of input, ignoring buffer overflow

```
#define L n){for(i=0;b[i];){if(i%n==0)p(32);p(b[i++]);}p(10);}
main(i){char b[9],n=1,(*p)()=putchar;gets(b);for(;b[n];++L for(;n;--L}

```

# Answer
> 0 votes
# Haskell, 109 bytes

```
p s=putStr$unlines$f s++(reverse$init$f s)
f s=map(unwords.(s#))[1..length s]
[]#i=[]
s#i=take i s:drop i s#i

```

Usage example: `p "abcdef"`. Output:

```
a b c d e f
ab cd ef
abc def
abcd ef
abcde f
abcdef
abcde f
abcd ef
abc def
ab cd ef
a b c d e f

```

# Answer
> 0 votes
# Factor, 78 bytes

```
[ dup length [1,b] dup reverse rest append [ group " "join print ] with each ]

```

Try it online!

# Answer
> 0 votes
# Japt `-R`, 9 bytes

```
Êõ@òX ¸Ãê

```

Try it

```
Êõ@òX ¸Ãê
Ê         # Get the length of the input
 õ@    Ã  # For each X in the range [1...length]:
   òX     #  Split the input into substrings with length X
      ¸   #  Join them with spaces
        ê # Palindromize

-R        # Join with newlines and print

```

# Answer
> 0 votes
# Raku, 44 bytes

```
{.put for map {.comb($^n)},(1...+.comb...1)}

```

Try it online!

Raku conveniently has a `comb` method on strings that can split one into chunks of a given size, so it's just a matter of mapping that method from 1, up to the number of characters in the string, then back down to 1 again.

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


title: Plot a hyperbolic plane tessellation

text:
# Question
Title: Plot a hyperbolic plane tessellation
Make a plot (Poincare disk) of a tessellation on a hyperbolic plane, such as:

The program takes *four* inputs:

1) How many edges/polygon (three in this example).

2) How many intersect at each vertex (seven in this example).

3) How many steps away from the center vertex to render (5 in this example, if you look closely). This means that a vertex is included iff it can be reached in 5 or less steps form the center. Edges are rendered iff both their vertexes are included.

4) The resolution of the image (a single number of pixels, the image is square).

The output must be an image. Edges must be rendered as circle-arcs, not lines (the Poincaré disk projection turns lines into circles). Points do not need to be rendered. When the user puts in something that is *not* hyperbolic (i.e. 5 triangles meeting at each vertex), the program does not have to work properly. This is code-golf, so the shortest answer wins.

# Answer
# Mathematica, 2535 bytes

Taken from **here** (hence why it's community wiki). Not really that golfed. View the provided link for the author's explanation of his code.

Also, I'm no Mathematica expert, but I bet Martin could do wonders on the code length. I don't even understand the math behind it.

I left it readable, but if the question doesn't get closed, I'll golf it past readability and move the 2 other parameters inside the caller function.

**Currently invalid**, feel free to help improve it:

* I think this uses lines rather than arcs.
* Centered on a face, rather than a vertex.

```
HyperbolicLine[{{Px_, Py_}, {Qx_, Qy_}}] :=
 If[N[Chop[Px Qy - Py Qx]] =!= 0.,
  Circle[OrthoCentre[{{Px, Py}, {Qx, Qy}}],
   OrthoRadius[{{Px, Py}, {Qx, Qy}}],
   OrthoAngles[{{Px, Py}, {Qx, Qy}}]], Line[{{Px, Py}, {Qx, Qy}}]]

OrthoCentre[{{Px_, Py_}, {Qx_, Qy_}}] :=
 With[{d = 2 Px Qy - 2 Py Qx, p = 1 + Px^2, q = 1 + Qx^2 + Qy^2},
  If[N[d] =!= 0., {p Qy + Py^2 Qy - Py q, -p Qx - Py^2 Qx + Px q}/d,
   ComplexInfinity]]

OrthoRadius[{{Px_, Py_}, {Qx_, Qy_}}] :=
 If[N[Chop[Px Qy - Py Qx]] =!= 0.,
  Sqrt[Total[OrthoCentre[{{Px, Py}, {Qx, Qy}}]^2] - 1], Infinity]

OrthoAngles[{{Px_, Py_}, {Qx_, Qy_}}] :=
 Block[{a, b, c = OrthoCentre[{{Px, Py}, {Qx, Qy}}]},
  If[(a = N[Apply[ArcTan, {Px, Py} - c]]) < 0., a = a + 2 \[Pi]];
  If[(b = N[Apply[ArcTan, {Qx, Qy} - c]]) < 0.,
   b = b + 2 \[Pi]]; {a, b} = Sort[{a, b}];
  If[b - a > \[Pi], {b, a + 2 \[Pi]}, {a, b}]]

Inversion[Circle[{Cx_, Cy_}, r_], {Px_, Py_}] := {Cx, Cy} +
  r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2)
Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], {Px_, Py_}] := {Cx, Cy} +
  r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2)

Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Line] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}]

Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Polygon] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}]

Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], {Ux_, Uy_}] :=
 With[{u = Px - Qx,
   v = Qy - Py}, {-Ux (v^2 - u^2) - 2 u v Uy,
    Uy (v^2 - u^2) - 2 u v Ux}/(u^2 + v^2)]
Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], p_Polygon] :=
 Map[Inversion[Line[{{Px, Py}, {Qx, Qy}}], #] &, p, {2}]

Inversion[Circle[{Cx_, Cy_}, r_], c_List] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, c]

PolygonInvert[p_Polygon] :=
 Map[Inversion[HyperbolicLine[#], p] &,
  Partition[Join[p[[1]], {p[[1, 1]]}], 2, 1]]
PolygonInvert[p_List] := Flatten[Map[PolygonInvert[#] &, p]]

LineRule = Polygon[x_] :> Line[Join[x, {x[[1]]}]];
HyperbolicLineRule =
  Polygon[x_] :>
   Map[HyperbolicLine, Partition[Join[x, {x[[1]]}], 2, 1]];

CentralPolygon[p_Integer, q_Integer, \[Phi]_: 0] :=
 With[{r = (Cot[\[Pi]/p] Cot[\[Pi]/q] - 1)/
     Sqrt[Cot[\[Pi]/p]^2 Cot[\[Pi]/q]^2 - 1], \[Theta] = \[Pi] Range[
       1, 2 p - 1, 2]/p},
  r Map[{{Cos[\[Phi]], -Sin[\[Phi]]}, {Sin[\[Phi]], Cos[\[Phi]]}}.# &,
     Transpose[{Cos[\[Theta]], Sin[\[Theta]]}]]]

PolygonUnion[p_Polygon, tol_: 10.^-10] := p
PolygonUnion[p_List, tol_: 10.^-10] :=
 With[{q = p /. Polygon[x_] :> N[Polygon[Round[x, 10.^-10]]]},
  DeleteDuplicates[q]]
HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer,
  t_: 10.^-10] :=
 Map[PolygonUnion[#, t] &,
   NestList[PolygonInvert, Polygon[CentralPolygon[p, q, \[Phi]]],
     k][[{-2, -1}]]] /; k > 0

HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer,
  t_: 10.^-10] := Polygon[CentralPolygon[p, q, \[Phi]]] /; k == 0
HyperbolicTessellationGraphics[p_Integer, q_Integer, \[Phi]_,
  k_Integer, rule_RuleDelayed, opts___] :=
 Graphics[{Circle[{0, 0}, 1],
   HyperbolicTessellation[p, q, \[Phi], k, 10.^-10] /. rule}, opts]

```

Called like:

```
HyperbolicTessellationGraphics[7, 3, 0., 5, HyperbolicLineRule, ImageSize -> 100, PlotLabel -> "{7,3}"]
HyperbolicTessellationGraphics[3, 7, 0., 7, HyperbolicLineRule, ImageSize -> 300, PlotLabel -> "{7,7}"]

```
> 3 votes

# Answer
# JavaScript/HTML/SVG, 5086 bytes

Not golfed, but the logic/math is short and hopefully relatively clear; also does the planar and spherical tessellations ((p-2)\*(q-2) \<= 4) without too much extra logic (it was easier to implement those than to leave gaps in the table!).

The calling code in the snippet below calls the function several times: first to display the 512x512 {3,7} picture (not shown here; it looks just like the above), and then to display a 128x128 {p,q} (meaning q p-gons surround each vertex) for each p,q from 3 to 9:

```
<!DOCTYPE html>
<html>
 <!--
 https://codegolf.stackexchange.com/questions/55848/plot-a-hyperbolic-plane-tessellation
 -->
 <style> svg { border: 1px solid black; } </style>
 <body>
  <script>
   "use strict";
   console.log("    in script");
   // Do an immediately invoked async function,
   // so we can sleep in it (to flush drawing).
   (async () => {
 console.log("        in script async function");
 const t0 = performance.now();

 // ==========================
 // IMPLEMENTATION BEGINS HERE

 // some complex math
 const neg = ([x,y]) => [-x,-y];
 const conj = ([x,y]) => [x,-y];
 const plus = (a,b) => [a[0]+b[0],a[1]+b[1]];
 const minus = (a,b) => [a[0]-b[0],a[1]-b[1]];
 const cross = (a,b) => a[0]*b[1]-a[1]*b[0];  // area of spanned parallelogram
 const times = (a,b) => [a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0]];
 const timesreal = ([x,y],r) => [x*r, y*r];
 const abs2 = ([x,y]) => x**2+y**2;
 const abs = z => Math.sqrt(abs2(z));
 const dist = (a,b) => abs(minus(a,b));
 const inverse = z => timesreal(conj(z), 1/abs2(z));
 const dividedby = (a,b) => times(a,inverse(b));

 // Transform z by the translation that takes the origin to t.
 // Works with any curvature; in particular:
 //   -1 = hyperbolic (poincare disk)
 //    0 = planar,
 //    1 = spherical (stereographic projection)
 const Plus = (z,t, curvature) => {
   // (z + t) / (1 - curvature*conj(t)*z)
   return dividedby(plus(z,t),
                    minus([1,0],
                          timesreal(times(conj(t), z), curvature)));
 };
 // Transform z by the translation that takes t to the origin.
 const Minus = (z,t, curvature) => Plus(z, neg(t), curvature);

 // Simple monotonic function of actual distance. Specifically:
 // - hyperbolic distance is 2*atanh(chord distance)
 // - spherical distance is 2*atan(chord distance)
 // - planar distance is chord distance
 // (I might be off by a factor of 2 in some of these claims, doesn't matter)
 const ChordDistance = (a,b, curvature) => abs(Minus(a,b, curvature));

 // signed radius of the circle passing through a,b,c
 const circumradius = (a,b,c) => dist(a,b)*dist(b,c)*dist(c,a) /
                                 (2 * cross(minus(b,a), minus(c,a)));

 // signed radius of circle needed to render segment a,b as circular arc
 // in the picture; may be infinite
 const ArcRadius = (a,b, curvature) => {
   if (curvature === 0) return Infinity;  // planar picture: all straight lines
   if (abs(a) > 1e3 || abs(b) > 1e3) return Infinity;  // one of them is infinite
   if (Math.abs(cross(a,b)) < 1e-3) return Infinity;  // collinear with origin
   // Let c be any third point on the arc
   const c = Plus(timesreal(Minus(b,a, curvature), .5), a, curvature);
   return circumradius(a,b,c);
 };

 const doit = (svgsize,p,q,steps,maxverts) => {
  const curvature = Math.sign(4-(p-2)*(q-2));  // -1:hyperbolic, 0:planar, 1:spherical
  const Dist = (a,b) => ChordDistance(a,b, curvature);

  const euclidean_first_edge_length = curvature===0 ? 1 :
    Math.sqrt(Math.abs((Math.sin(Math.PI/q)/Math.cos(Math.PI/p))**2 - 1))

  // a,b are generators of the symmetry group (not including reflections):
  //  - a is rotation by 2pi/q about origin
  //  - b is rotation by pi about first edge midpoint
  const primitive_qth_root_of_unity = [Math.cos(2*Math.PI/q),
                                       Math.sin(2*Math.PI/q)];
  const a = z => times(z, primitive_qth_root_of_unity);
  const b = ([x,y]) => Plus([-x, -y], [0,-euclidean_first_edge_length], curvature);

  // generate verts
  const vs = [[0,0]];
  for (let i = 0; i < steps; ++i) {
    for (const g of [b,a]) {
      for (let j = 0; j < vs.length; ++j) {  // while vs is growing
        if (vs.length >= maxverts) break;
        const v = g(vs[j]);
        if (vs.findIndex(w=>Dist(v,w)<=1e-6)<0) vs.push(v);
      }
    }
  }

  // generate edges (pairs of points, not pairs of indices)
  const es = [];
  if (vs.length >= 2) {
    const d = Dist(vs[0], vs[1]);
    for (let i = 0; i < vs.length; ++i) {
      for (let j = 0; j < i; ++j) {
        if (Math.abs(Dist(vs[i],vs[j]) - d) <= 1e-6) es.push([vs[i], vs[j]]);
      }
    }
  }

  const scale =
      curvature>0 ? .35 :  // spherical: get all verts in the picture
      curvature===0 ? 1/5.5 :  // planar: get a good sampling in the picture
      1;  // hyperbolic: get the poincare disk in the picture

  let svg_html = '<svg width="'+svgsize+'" height="'+svgsize+'"><path d="';
  for (let [a,b] of es) {
    const r = ArcRadius(a,b,curvature)*scale/2*svgsize;

    // if a or b is at infinity, then draw straight outward
    // from the other point
    if (abs(a) > 1e2) a = timesreal(b, 1e2);
    if (abs(b) > 1e2) b = timesreal(a, 1e2);

    const x0 = (a[0]*scale+1)/2*svgsize;
    const y0 = (a[1]*scale+1)/2*svgsize;
    const x1 = (b[0]*scale+1)/2*svgsize;
    const y1 = (b[1]*scale+1)/2*svgsize;

    if (!Number.isFinite(r)) {
      svg_html += 'M'+x0+','+y0+'L'+x1+','+y1;  // straight line
    } else {
      // circular arc of signed radius r
      svg_html += 'M'+x0+','+y0+'A'+r+','+r+',0,0,'+(r<0?1:0)+','+x1+','+y1;
    }
  }
  svg_html += '" stroke="black" fill="none"/></svg>';
  return svg_html;
 }; // doit

 // IMPLEMENTATION ENDS HERE
 // ========================

 document.body.innerHTML += doit(512, 3, 7, 5, 1000)
 document.body.innerHTML += "<br>";

 const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

 const svgsize = 128;
 const max = 9;
 const steps = 5;
 const maxverts = 1000;  // keep from going off the rails
 for (let p = 3; p <= max; ++p) {
   for (let q = 3; q <= max; ++q) {
     await sleep(0);  // flush previously drawn stuff before computing next
     document.body.innerHTML += doit(svgsize, p, q, steps, maxverts);
   }
   document.body.innerHTML += "<br>";
 }

 const t1 = performance.now();
 console.log("        out script async function in "+(t1-t0)/1000+"s")
   })();
   console.log("    out script")
  </script>
 </body>
</html>
```
> 3 votes

---
Tags: code-golf, graphical-output
---