title: Rotate a number

text:
# Question
Title: Rotate a number
Given a positive number `n`, rotate its base-10 digits `m` positions rightward. That is, output the result of `m` steps of moving the last digit to the start. The rotation count `m` will be a non-negative integer.

You should remove leading zeroes in the final result, but not in any of the intermediate steps. For example, for the test case `100,2 => 1`, we first rotate to `010`, then to `001`, then finally drop the leading zeroes to get `1`.

## Tests

```
n,m => Output

123,1 => 312
123,2 => 231
123,3 => 123
123,4 => 312
1,637 => 1
10,1 => 1
100,2 => 1
10,2 => 10
110,2 => 101
123,0 => 123
9998,2 => 9899

```

# Answer
> 14 votes
# Japt `-N`, 2 bytes

Takes `m` as a string and `V=n` as an integer or string, outputs an integer. Prepend `s` or `ì` for +1 byte if we *have* to take both as integers.

```
éV

```

Try it

# Answer
> 10 votes
# , 51 bytes

```
function(n,m,p=10^nchar(n))sum(n*p^(0:m))%/%10^m%%p

```

Try it online!

Numeric solution (that fails for combinations of n & m that cause it to exceed R's numeric range): chains the digits of n, m times (so: `123` =\> `123123123123` for m=4) and then calculates DIV 10^m (so: `12312312` for m=4) MOD 10^digits(n) (so: `312`).

---

# , ~~61~~ 53 bytes

*Edit: -8 bytes thanks to Giuseppe*

```
function(n,m,N=nchar(n),M=10^(m%%N))n%%M*10^N/M+n%/%M

```

Try it online!

~~Text-based function that~~ Rotates by combining the two parts of the number together, so does not go out of numeric range: puts the last (m MOD digits(n)) digits of n first, followed by the other digits of n.

# Answer
> 6 votes
# Python 3, ~~61~~ 57 bytes

```
i=input
n=i()
k=int(i())%len(n)
print(int(n[-k:]+n[:-k]))

```

Try it online!

Uses string slicing to move the last k digits at the beginning and converts it to an integer to remove the leading zeroes.

*-4 bytes thanks to Lyxal*

# Answer
> 5 votes
# Perl 5 \+ `-pl`, 26 bytes

```
eval'$_=chop.$_;'x<>;$_|=0

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 4 bytes

```
(._ï

```

Try it online!

## Explanation

```
(._ï
(     : get negative of m
 ._   : rotate n left negative m times
   ï  : remove leading zeros

```

# Answer
> 5 votes
# Python 3, 39 bytes

```
lambda n,m:int(((n*m)[-m:]+n)[:len(n)])

```

**Try it online!** Or see the test-suite.

### How?

Rotating `n` right by `m` is the same as rotating `n` right by `m` modulo length `n` (`m%len(n)`), which is the concatenation of the last `m%len(n)` digits with the first `len(n)-m%len(n)` digits.

A simple slice would give us

```
lambda n,m:int(n[-m%len(n):]+n[:-m%len(n)])

```

for 43 bytes. To remove the need for the repeated `-m%` we can instead concatenate the last `m%len(n)` digits with all the digits of `n` and ***then*** take the first `len(n)` digits. This is

```
lambda n,m:int((n[-m%len(n):]+n)[:len(n)])

```

for 42 bytes. The `n[-m%len(n):]` can then be replaced with taking the rightmost `m` digits of `m` `n`s concatenated together, `(n*m)[-m:]` giving us the 39 byte solution.

# Answer
> 5 votes
# \[Taxi\], ~~1698~~ 1678 bytes

No need to wrap single-byte plan names in quote marks. 0.6% byte reduction!

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Addition Alley.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l. Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to The Underground.Go to Chop Suey:n 1 r 2 r.[1]Switch to plan 2 if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 1.[2]Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan 3 if no one is waiting.Pickup a passenger going to Chop Suey.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 2.[3]Go to Chop Suey:e 1 r 1 l 1 r.[a]Go to The Underground:s 1 r 1 l.Switch to plan b if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Pickup a passenger going to Chop Suey.Switch to plan a.[b]Go to Chop Suey:n 2 r 1 l.[4]Switch to plan 5 if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan 4.[5]Go to Narrow Path Park:n 1 l 1 r 1 l.[c]Switch to plan d if no one is waiting.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 2 l.Switch to plan c.[d]Go to KonKat's:e 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s.Pickup a passenger going to The Babelfishery.Go to KonKat's:n.Go to The Babelfishery:s.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

```

Try it online!

I chose to get fired rather than sacrifice the bytes required to return to the garage at the end. I have checked both very long inputs and very long rotations and the net gain is positive so you never run out of gas.

---

Formatted for legibility and with comments:

```
[ Pick up the inputs, add 1 to the second, and chop the first into pieces. ]
Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to Chop Suey.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Addition Alley.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 1 l 2 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:w 1 r 3 r 1 r 1 r.
Pickup a passenger going to The Underground.
Go to Chop Suey:n 1 r 2 r.

[ Reverse the order the charaters are stored in so we can right-shift instead of left-shift. ]
[1]
Switch to plan 2 if no one is waiting.
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park:n 1 l 1 r 1 l.
Go to Chop Suey:e 1 r 1 l 1 r.
Switch to plan 1.
[2]
Go to Narrow Path Park:n 1 l 1 r 1 l.
Switch to plan 3 if no one is waiting.
Pickup a passenger going to Chop Suey.
Go to Chop Suey:e 1 r 1 l 1 r.
Switch to plan 2.
[3]
Go to Chop Suey:e 1 r 1 l 1 r.

[ Loop the required times, rotating the passengers at Chop Suey each time. ]
[a]
Go to The Underground:s 1 r 1 l.
Switch to plan b if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up:s.
Go to Chop Suey:n 3 r 1 l.
Pickup a passenger going to Chop Suey.
Switch to plan a.
[b]
Go to Chop Suey:n 2 r 1 l.

[ Reverse the character order again. ]
[4]
Switch to plan 5 if no one is waiting.
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park:n 1 l 1 r 1 l.
Go to Chop Suey:e 1 r 1 l 1 r.
Switch to plan 4.
[5]
Go to Narrow Path Park:n 1 l 1 r 1 l.

[ Concatenate the passengers at Narrow Path Park. ]
[c]
Switch to plan d if no one is waiting.
Pickup a passenger going to KonKat's.
Go to KonKat's:e 1 r.
Pickup a passenger going to KonKat's.
Go to Narrow Path Park:n 2 l.
Switch to plan c.

[ Convert to a number to remove leading zeros and then back to a string so the Post Office can handle it. ]
[d]
Go to KonKat's:e 1 r.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s.
Pickup a passenger going to The Babelfishery.
Go to KonKat's:n.
Go to The Babelfishery:s.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.

```

Try it online!

# Answer
> 4 votes
# APL+WIN, ~~8~~ 7 bytes

Prompts for n as integer and m as string:

```
⍎(-⎕)⌽⎕

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 4 votes
# JavaScript (ES6), 36 bytes

Expects `(m)(n)`, where `n` is a string and `m` is either a string or an integer.

```
m=>g=n=>m--?g(n%10+n.slice(0,-1)):+n

```

Try it online!

# Answer
> 4 votes
# Pyth, 4 bytes

```
v.>z

```

Try it online!

# Explanation

```
v.>zQ
    Q  : first line of input evaluated
   z   : second line of input as string
 .>    : cyclically rotate second line right by number in first line
v      : evaluate to remove leading 0s

```

# Answer
> 4 votes
# MATL, 3 bytes

```
YSU

```

Try it online!

Takes `n` as a string and `m` as an integer.

### Explanation

```
YS   % Shift first input second input number of times
  U  % Convert to integer to remove leading 0s

```

---

# MATL, 5 bytes

```
ViYSU

```

Try it online!

This answer takes both the inputs as integers.

# Answer
> 4 votes
# Charcoal, 9 bytes

```
ＩＩ⭆θ§θ⁻κη

```

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

```
   θ        Input `n` as a string
  ⭆         Map over characters and join
       κ    Current index
      ⁻     Subtract
        η   Input `m`
    §       Cyclically indexed into
     θ      Input `n` as a string
 Ｉ          Cast to integer
Ｉ           Cast to string
            Implicitly print

```

Conveniently if you try to Subtract an integer and a string then the string gets cast to integer.

# Answer
> 4 votes
# C (gcc)`-lm`, ~~65~~ \\$\cdots\\$ ~~56~~ 55 bytes

Saved a byte thanks to ceilingcat!!!

```
e;f(n,m){for(e=log10(n);m--;)n=n%10*exp10(e)+n/10;m=n;}

```

Try it online!

Inputs integers \\$n\\$ and \\$m\\$.
Base-10 digitally rotates \\$n\\$ right \\$m\\$-times and returns it.

# Answer
> 4 votes
# Python 3, 47 bytes

```
f=lambda n,m:m and f(n[-1]+n[:-1],m-1)or int(n)

```

Try it online!

Inputs \\$n\\$ as a string and \\$m\\$ as an integer.
Returns rotated \\$n\\$ as an integer.

# Answer
> 3 votes
# Keg, `-hr`, 11 bytes

```
÷(¿|")⑷⅍⑸⅀ℤ

```

Try it online!

## Explained

```
÷(¿|")⑷⅍⑸⅀ℤ
÷               # Split m into individual numbers
 (¿|")          # n times, shift the stack right
      ⑷⅍⑸      # turn each character into a string
           ⅀ℤ   # sum stack and convert to integer. `-hr` prints it as integer

```

# Answer
> 3 votes
# Java (JDK), 66 bytes

```
(n,x)->new Long((""+n+n).substring(x=(n=(""+n).length())-x%n,x+n))

```

Try it online!

# Answer
> 2 votes
# , 11 bytes

```
(".@|.":)~-

```

Try it online!

### How it works

Uses @Bubbler's tacit trick for `(F x) G (H y) = (G~F)~H`.

```
(".@|.":)~-
          - negate y to shift right
(       )~  flip arguments, so ((-y) ".@|. (":x))
      ":    convert x to string
    |.      shift that by negated y
 ".@        and convert back to number

```

# Answer
> 2 votes
# Io, 89 bytes

Uses a `reduce` trick to assign different lines of STDIN to variables.

```
File standardInput readLines reduce(a,b,a splitAt(-b asNumber)reverse join)asNumber print

```

Try it online!

# Io, 56 bytes

```
method(a,b,doString(a splitAt(-b asNumber)reverse join))

```

Try it online!

# Answer
> 2 votes
# Ruby, ~~44~~ 40 bytes

```
->a,b{a.to_s.chars.rotate(-b).join.to_i}

```

-4 from Dingus.

Try it online!

# Ruby, 19 bytes

```
->a,b{a.rotate(-b)}

```

Try it online!

taking a list of digits

# Answer
> 2 votes
# Jelly, (4?) 5 bytes

4 if we may accept a list of digits (remove the leading `D`).

```
DṙN}Ḍ

```

**Try it online!**

### How?

```
DṙN}Ḍ - Link: integer, n; integer, m
D     - convert to base ten
   }  - use m as the input of:
  N   -   negate
 ṙ    - rotate (n) left by (-m)
    Ḍ - convert from base ten

```

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~42~~ 40 bytes

```
lambda x,r:int(x[(a:=-r%len(x)):]+x[:a])

```

Try it online!

# Answer
> 2 votes
# Ruby `-nl`, 34 bytes

```
->m{($_*-~m*2)[~~/$/*m,~/$/].to_i}

```

Try it online!

Takes \\$n\\$ from STDIN and \\$m\\$ as an argument. Concatenates \\$n\\$ \\$2(m+1)\\$ times, then from this string takes the substring of length \\$d\\$ (where \\$d\\$ is the number of digits in \\$n\\$) that begins \\$m(d+1)\\$ characters from the end. In the code, `$_` is \\$n\\$ and `~/$/` gives \\$d\\$.

### Example

For \\$n=123\\$, \\$m=2\\$:

1. Concatenate \\$n\\$ \\$2(m+1)=6\\$ times: `123123123123123123`
2. Count back from the end \\$m(d+1)=8\\$ characters: `1231231231**2**3123123`
3. Take substring of length \\$d=3\\$: `1231231231**231**23123`

# Answer
> 2 votes
# CJam, 10 7 6 bytes

Saved 3 bytes by remembering that you can preform most array operations on strings.

-1 byte from @my pronoun is monicareinstate noting that `m>` takes arguments in either order.

```
rr~m>~

```

Try it online

Explanation:

```
rr       Read two string inputs
  ~      Parse m to number
   m>    Rotate n string right m times
     ~   Parse n to number to remove leading zeros
         (implicit) output

```

## Old version, 7 bytes:

```
q~\sm>~

```

Try it online

Explanation:

```
q~        Take input as a string, evaluate to two numbers
  \       Swap order
   s      Convert n to string
    m>    Rotate n string right m times
      ~   Parse n to number to remove leading zeros
          (implicit) output

```

# Answer
> 2 votes
# APL (Dyalog Extended), 4 bytes (SBCS)

Anonymous tacit infix function. Takes string `n` as right argument and number `m` as left argument.

```
⍎-⍛⌽

```

Try it online!

execute the result of

`-⍛` negating the left argument, then using that to

cyclically rotate the right argument

# Answer
> 2 votes
# (non-competing) L=tn, 10

```
cα;θ2$cD=0

```

Explanation (in order of execution):

```
cα;         -  Turn first number into a list of digits
    2$c     -  Fetch second number as a number
   θ        -  Shift list from first step by number from second step
       D=0  -  Drop while equals to zero

```

It prints result as a string.

Note: The language is in progress and I did add stuff to code golf this. So it is not a competing submission.

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

```
FromDigits@RotateRight[IntegerDigits@#,#2]&

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 29 bytes

```
,.+
$*_
+`(.*)(\d)_
$2$1
^0+

```

Try it online! Link includes test cases. Takes input as `n,m`. Explanation:

```
,.+
$*_

```

Convert `m` to unary.

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

```

Rotate `n` `m` times. This is O(m³) because of the way the regex backtracks trying to find a second match. Right-to-left matching, anchoring the match at the start, or rewriting the code to take input as `m,n` would reduce the time complexity (at a cost of a byte of course).

```
^0+

```

Delete leading zeros.

# Answer
> 1 votes
# Scala, 61 bytes

```
(n,m)=>{val s=n+""size;val(a,b)=n+""splitAt s-m%s;b++a toInt}

```

Try it in Scastie

# Answer
> 1 votes
# PHP, 45 43 bytes

Saved 2 bytes, realized we can shorten the variable names.

```
<?=(int)(substr($s,-$n).substr($s,0,-$n))?>

```

Try it online

Explanation:

```
<?= ?>       Shorthand for <?php echo ;?>
  (int)      Typecast string to int, removes 0s from prefix
   substr()  substr(string,start,[length]), returns part of string,
             if range go out of bounds, starts again from the opposite end.
             Basically returns part of from a 'circular' string.

```

# Answer
> 1 votes
# JavaScript (V8), 47 bytes

```
(n,m,k=(e=n+'').length)=>+(e+e).substr(k-m%k,k)

```

Try it online!

# Answer
> 1 votes
# V (vim), 11 bytes

```
Àñ$x0Pñó^0«

```

Try it online!

```
Àñ    ñ       # (M-@)rg number of times
  $           # end of line
   x          # delete character (cut)
    0         # beginning of line
     P        # paste character
       ó      # (M-s)ubsitute
        ^0«   # ^0\+
              # (implicitly) with nothing

```

# Answer
> 1 votes
# Haskell, 57 bytes

```
f n m=read(foldr(\_ y->last y:init y)(show n)[1..m])::Int

```

Try it online!

```
f n m=            - function expecting two integers

foldr ... [1..m]  - folds `m` times..
      .. (show n)  - starting with `n` converted to string
      . (\_ y->last y:init y)  - moving the last element in head
read( ... )::Int  - convert the result to Int

```

# Answer
> 1 votes
# \[Excel/Google Sheets\], 63 bytes

With n and m in columns a and b, and this formula in column c

```
=VALUE(RIGHT(A4, MOD(B4,LEN(A4)))&LEFT(A4,LEN(A4)-MOD(B4,LEN(A4

```

# Answer
> 1 votes
# SimpleTemplate 0.84, 106 bytes

This challenge really got my head spinning...

```
{@fnR N,T}{@forfrom Tto1}{@ifN matches"@(.+)(.)@"M}{@setN"#{M.2}#{M.1}"}{@/}{@/}{@set+N N,0}{@returnN}{@/}

```

This creates a function `R` that takes the `N`umber and the amount of `T`imes you want to swap the numbers around.

The way it works is by evaluating if the `N`umber matches a regular expression (`{@ifN matches"@(.+)(.)@"M}`) and storing the `M`atched parts.

Then, it reconstructs the number with the last digit at the beginning (`{@setN"#{M.2}#{M.1}"}`).

To remove leading zeroes, I've simply stored the sum of whatever is the `N`umber with 0, returning it after.

---

**Ungolfed:**

It is a lot easier to follow an ungolfed example:

```
{@fn rotate_n number, times}
    {@for i from times to 1}
        {@if number matches "@^(.+)(.)$@" matches}
            {@set number "#{matches.2}#{matches.1}"}
        {@/}
    {@/}
    {@set+ number number, 0}
    {@return number}
{@/}

```

The `i` is totally useless there, but removing it is a golfing step.

---

---

You can try this on: http://sandbox.onlinephpfunctions.com/code/91d0d49d2f750022e21cc7b1c18e6beec55f9c8b

You can change the values on line 1071.

# Answer
> 1 votes
# Golfscript - 28 bytes

```
~:a;`{1/)\+}a*1/{(~:b!}do b\

```
* input: `10450 4`
* output: `4501`

Try it online!

**Explanation**

```
~:a;`                         # Parses the input "123 3" -> "123" on stack and a = 3
     {1/)\+}a*                # Pushes the last digit away and rejoins, repeat a times "123" -> "12" "3" -> "3" "12" -> "312" repeat
              1/{(~:b!}do b\  # Discard the leading elements until a non-zero element is found

```

There's room for improvement.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
ǔṅ⌊

```

Try it Online or Verify all the test cases

# Answer
> 1 votes
# K (ngn/k), 29 25 bytes

```
{.(y#a),(y:-(#a)!y)_a:$x}

```

Try it online!

*¯4 thanks to @ovs*

# Answer
> 1 votes
# PHP, 89 bytes

```
list($n,$m)=explode(",",$argn);while($m--){$n=$n[-1].substr($n,0,-1);}echo ltrim($n,"0");

```

Try it online!

Explanation: A PHP answer that works by looping m times through the given string n moving the last character of n to the beginning of the string.

# Answer
> 1 votes
# K (ngn/k), 18 bytes

```
{.y{(*|x):':x}/$x}

```

Try it online!

Right rotate inspired by @chrispsn.

# Answer
> 1 votes
# Desmos, ~~76~~ 70 bytes

```
f(n,m)=mod(n,t)10^d/t+floor(n/t)
d=floor(log(n+0^n))+1
t=10^{mod(m,d)}

```

Try it on Desmos!

Port of R answer.

*-6 bytes thanks to Aiden Chow*

# Answer
> 0 votes
# GolfScript, 14 bytes

```
~\`\{1/)\+}\*~

```

Try it online!

```
~              # Puts n and m on top of the stack as integers
 \`\           # Parses n to string
    {1/)\+}    # This block goes to the top of the stack without being executed
           \*  # Executes previous block m times
             ~ # Parses the answer from string to integer, this removes the leading zeroes

```

What the block does:

```
     1/        # Parses the string to an array of strings
       )\      # Separates the last digit and puts it in the begining
         +     # Concatenates them again

```

# Answer
> 0 votes
# Factor, 19 bytes

```
[ neg rotate dec> ]

```

Attempt This Online!

# Answer
> 0 votes
# Lua 5.1 (58 bytes)

```
n=n..""for _=1,m do n=n:sub(-1)..n:sub(1,-2)end print(n*1)

```

# Answer
> 0 votes
# Thunno 2, 2 bytes

```
ẒN

```

Try it online!

#### Explanation

```
    # Implicit input
Ẓ   # Rotate right that many times
 N  # Convert to integer to remove leading zeros
    # Implicit output

```

# Answer
> 0 votes
## awk

```
awk '($++NF=(__=$++_)*(_!_)^((__=length(__))-$(_+_)%__)%((_!_)^__-_--))' FS=,

```

---

```
123 1 => 312 312
123 2 => 231 231
123 3 => 123 123
123 4 => 312 312
1 637 => 1 1
10 1 => 1 1
100 2 => 1 1
10 2 => 10  10
110 2 => 101 101
123 0 => 123 123
9998 2 => 9899 9899

```

# Answer
> 0 votes
# Uiua, 6 bytes

```
⍜⊙°⋕↻¯

```

Test pad

Takes the amount to rotate on top of the stack.

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


title: Output a random unary string

text:
# Question
Title: Output a random unary string
Your task is simple: output the letter `x` a random number of times. Every possible length of `x`s must have a non-zero probability of being output.

Of course, there must be some lengths whose probabilities tend to \\$ 0 \\$, in order for the total probabilities to sum to \\$ 1 \\$, but all must still be theoretically possible.

* You may choose whether to include the empty string as a possible output
* You may have any consistent separator between the `x`s, and you may output the separator more than once. The separator may not contain the unary character
* You may use any other consistent single character instead of `x`
* Per standard rules, your program must always halt in finite time. (Terminating "with probability 1" is allowed, though)
* You can assume your language's random number generator is perfectly random. If it is supposedly continuous, you may assume it has infinite precision.

This is , so the shortest code wins.

# Answer
# \>\<\>, 3 bytes

```
x7n

```

Terminates on an error once x sends the IP left.

Try it online!

~~4 bytes:
```
x7
n

```
Try it online!
~~

~~This will terminate with an error when `n` has been executed more times than `7`, which has probability 1 of eventually occurring, thought there is no upper limit on how many times `7` will be executed first.~~
> 14 votes

# Answer
# MATLAB, ~~28~~ 25 bytes

```
while rand<.5 disp(1),end

```

Outputs "1" a random number of times, with newline in between. Each length l of has half the probability of length l-1.

Thanks @Luis Mendo for the 3 bytes!
> 9 votes

# Answer
# Pari/GP, 43 bytes

```
setrand(getwalltime)
while(random,print(1))

```

(Don't) Try it online! This version is very likely to time out on TIO; here's a slightly longer version that produces nicer results: Try it online!

### Explanation

```
setrand(getwalltime)

```

Seed the random number generator with `getwalltime`, which is "time in ms since UNIX Epoch."

```
while(random,print(1))

```

While a random integer in the range \\$\[0,2^{31})\\$ is not equal to zero, print `1` with a trailing newline.
> 9 votes

# Answer
# Vyxal 2.4.1, 6 bytes

```
{×₴₀℅|

```

Try it Online!

We use v2.4.1 because it seems in 2.6 and later there's no way to get a random bit in two bytes.

```
{      # Forever...
 ×₴    # Print an asterisk
     | # While...
   ₀℅  # A random bit is nonzero

```
> 9 votes

# Answer
# , 20 bytes

```
while(rexp(1))cat(1)

```

Try it online!

3 bytes longer than Giuseppe's R answer, but can output unary values greater than 2147483647.

In fact, it will nearly *always* output unary values that are significantly greater than 2147483647, since the chance of stopping after any outputted `1` character is about `1e-324` (the lower limit of 's double-precision numeric type, below which values are truncated to zero).
This will also nearly always exceed the output limit on TIO, so here is a link using a modified version of the `rexp` function with only 1 decimal place of precision.
> 9 votes

# Answer
# MathGolf, ~~4~~ 3 bytes

```
⌂v▲

```

Pushes `*` with a probability of \\$\frac{4\text{,}294\text{,}967\text{,}294}{4\text{,}294\text{,}967\text{,}295}\\$ (99.999999999767%) each iteration, and won't include the empty output (so will always output at least one `*`).

*Don't try it online.*

**Previous 4 byter:**

```
⌂v¶▼

```

Pushes `*` with a probability of \\$\frac{837\text{,}973\text{,}946}{858\text{,}993\text{,}459}\\$ (~97.55%) each iteration, and won't include the empty output (so will always output at least one `*`).

Try it online.

**Explanation:**

```
  ▲   # Do while falsey with pop:
⌂     #  Push character '*'
 v    #  Push a random integer in the range [-2³¹, 2³¹)
      #  (only 0 is a falsey integer in MathGolf)
      # (after which the entire joined stack is output implicitly as result)

```

```
   ▼  # Do while truthy with pop:
⌂     #  Push character '*'
 v    #  Push a random integer in the range [-2³¹, 2³¹)
  ¶   #  Pop and check if this integer is a (positive) prime number
      # (after which the entire joined stack is output implicitly as result)

```

The mentioned probability is basically the amount of non-prime numbers within the range \\$\[-2^{31},2^{31})\\$ (which is \\$4\text{,}189\text{,}869\text{,}730\\$ according to WolframAlpha) as numerator and total amount of integers within the range \\$\[-2^{31},2^{31})\\$ (basically \\$2^{32}-1=4\text{,}294\text{,}967\text{,}295\\$) as denominator (and then simplified by dividing both by their greatest common divisor \\$5\\$).
> 8 votes

# Answer
# JavaScript (Node.js), 29 bytes by noodle man

```
_=>''.padEnd(1/Math.random())

```

Try it online!

# JavaScript (Node.js), 30 bytes

```
f=_=>Math.random()>.5?'':1+f()

```

Try it online!

Simple
> 6 votes

# Answer
# Pip, 4 bytes

```
1X/r

```

Outputs one or more `1`s (usually not very many of them). Attempt This Online!

### Explanation

```
   r  Random number in [0, 1)
  /   Invert
1X    Repeat 1 that many times

```

Theoretically, I think it's possible for this to output nothing if `r` returns exactly `0`, but that's within the rules anyway.
> 6 votes

# Answer
# Random Brainfuck, ~~7~~ 6 bytes

*-1 byte thanks to je je's observation that Null bytes are accebtale as output.*

```
+[>.?]

```

Try it online!

Outputs at least 1 `0x01` character, and terminates each iteration with a 1/256 chance. `?` sets the current cell to a random byte, and this will only terminate when that byte is 0.

## Detailed Explanation

```
+       set first cell to 1
[       while the current cell is non-zero:
  >         move right one cell
  .         output it (0x00)
  ?         set current cell to a random byte from 0 to 255
]       end while

```
> 6 votes

# Answer
# Haskell, 56 bytes

```
import System.Random
main=print 1>>randomIO>>=([main]!!)

```

Try it online!

Random improvements applied to AZTECCO's answer. Halts by non-recoverable error, so it needs to be a full program. Prints at least once, but has \\$\frac{1}{2^{64}}\\$ chance of continuing to print. (The return type of `randomIO` is inferred to be `Int`, which is a signed 64-bit integer in TIO's environment.)

# Haskell, 59 bytes

```
import System.Random
f=do print 1;n<-randomIO;mapM_ id[f|n]

```

Try it online!

A function that terminates gracefully and has 1/2 chance of continuing. `[f|n]` becomes `[f]` or `[]` with 1/2 chance each, and `mapM_ id` (one byte shorter than `sequence_`) runs all monads in the list sequentially. Deleting `_` results in a type inference error.
> 6 votes

# Answer
# Thue, 20 bytes

```
x::=xx
x::=~x
::=
x

```

Try it online! (I'm not sure why the final blank line is necessary, but the program doesn't output anything if I delete it.)

### Explanation

Thue starts with an initial string and executes rewriting rules nondeterministically until it cannot execute any more, at which point it halts. This program consists of two rules:

```
x::=xx

```

Replace an `x` in the string with `xx`.

```
x::=~x

```

Delete an `x` from the string and output `x`.

The program's starting string is:

```
x

```

Thus, at each stage of execution, the string consists of one or more `x`s; it can either get longer by one `x`, or get shorter by one `x` and output an `x`. Once all the `x`s have been output, the program halts. This occurs with probability 1, although in practice sometimes the interpreter segfaults.
> 6 votes

# Answer
# , ~~19~~ 17 bytes

```
strrep(1,rexp(1))

```

Try it online!

Samples from an \\$Exp(1)\\$ distribution to determine the length. This allows any positive real number to be generated, which `strrep` truncates, though most of them will be rather small.
> 5 votes

# Answer
# Python 3, 50 bytes

```
lambda:'x'*int(1/(1-random()))
from random import*

```

Attempt This Online!

*Thanks to users `pxeger` and `DominicVanEssen` for their clarifications.*

Outputs the character `x` a random number of times. Random sequences of `x`s are separated by the newline character.
> 5 votes

# Answer
# Factor \+ `random.c`, ~~26~~ ~~25~~ 21 bytes

```
[ 1 . rand 9 > ] loop

```

Try it online!

This uses similar logic as flipping a coin until it lands on tails. Only you're using a severely weighted coin, so you usually get heads, leading to fairly long runs. `rand` is C's `rand()` function, returning an integer between 0 and 2147483647 (probably, though it doesn't matter). Each iteration of the loop, print `1` followed by a newline. If the output of `rand` is greater than 9, perform another iteration; otherwise, end the program.
> 5 votes

# Answer
# Pure Bash (no external utilities), 30 26

```
for((;RANDOM;));{ echo x;}

```

Try it online!
> 5 votes

# Answer
# Python 3, ~~62~~ ~~60~~ ~~59~~ ~~45~~ ~~43~~ 41 bytes

```
import os
while os.urandom(1)[0]:print(1)

```

Try online!

Thanks to @pxeger, @mvirts, @MarcMush and @loopywalt.
> 5 votes

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

```
2ȮX$’¿

```

A niladic Link that prints `2`s as a side-effect (it also yields `1`). Only prints strictly positive numbers (as allowed in the specification).

**Try it online!** (The footer suppresses the printing of `1` that a full program would otherwise do implicitly.)
Or see forty at once (plus a single trailing newline).

### How?

```
2ȮX$Ḋ¿ - Link: no arguments
2      - two - let's call this V
     ¿ - while...
    ’  - ...condition: decrement V (V=2 -> 1 (truthy); V=1 -> 0 (falsey))
   $   - ...do: last two links as a monad - f(V):
 Ȯ     -   print V, yield V
  X    -   random integer in [1,V] -> next V = 1 or 2 (probability = 0.5)

```

---

Previous @ 7 bytes:

```
2XȮß$Ị¡

```

A niladic Link that prints `1`s as a side-effect (it also yields `2`). This one includes the empty output (i.e. zero).

Try it online! (The footer suppresses the printing of `2` that a full program would otherwise do implicitly.)
> 4 votes

# Answer
# MATL, 5 bytes

```
`1rEk

```

Outputs `1` separated by newlines `n` times, where `n` is a (shifted) geometric random variable with parameter `1/2`. This means `n` is `1,2,3...` with probability `1/2`,`1/4`, `1/8` ... The program halts with probability `1`.

**Try it online!**

```
`     % Do...while
  1   %   Push 1
  r   %   Push uniform random number in the interval (0,1)
  E   %   Multiply by 2
  k   %   Round down. This gives 0 or 1 with probability 1/2
      % End (implicit). The top of the stack is used as loop condition
      % If 1 a new iteration is executed, otherwise the loop is exited
      % Display stack (implicit)

```
> 4 votes

# Answer
# 05AB1E, 5 bytes

```
[?₄Ω#

```

Outputs `0`s with a probability of \\$\frac{3}{4}\\$ each time. Could be a probability of \\$\frac{2}{3}\\$ or \\$\frac{1}{2}\\$ for the same byte-count by replacing the  with `т` or `T` respectively.

Try it online.

**Explanation:**

```
[      # Loop indefinitely:
 ?     #  Print an empty string without newline in the first iteration,
       #  or the 0 that was previously on the stack in other iterations
  ₄    #  Push 1000 (or 100 for `т` or 10 for `T`)
   Ω   #  Pop and push a random digit from this integer
    #  #  If it's 1: stop the infinite loop

```
> 4 votes

# Answer
# Cascade, 6 bytes

```
$/
.x/

```

Try it online!

# Cascade, 6 bytes

```
\$
.|x

```

Try it online!

*Likely* optimal, considering one row has to have width at least 3 for `$` to produce distinct random outcomes.

Both programs consist of two random branches from `$`, one of which returns the codepoint of `x`, and the other of which prints (the character value of) and returns the return value of (a fresh evaluation of) the `$`.
> 4 votes

# Answer
# TI-Basic (TI-84), ~~11~~ 10 bytes

```
Repeat checkTmr(startTmr
Disp 1
End

```

the program can only end when the check `checkTmr(startTmr` happens between two seconds (`checkTmr(startTmr) = 1` instead of `0`). This way, any number of ones is possible (the shortest I got was 3 ones, the longest printed during approx 10 seconds)

`Repeat` always executes the loop the first time, so the empty string is not included (`repeat until` or `do while not`)

For calculators without time (TI-83), replace `checkTmr(startTmr` with `rand>.9` but it's not true randomness (same output on each reset of the calculator)
> 4 votes

# Answer
# Charcoal, 4 bytes

```
Ｗ‽φx

```

Try it online! Link is to verbose version of code. Prints an average of 999 `x`s. (Other average counts from `1` to `9` are also possible by substituting an appropriate character for `φ`.)
> 3 votes

# Answer
# , ~~10~~ 9 bytes

```
1#~>.@%?0

```

-1 byte by using Reflex `~` instead of Bond `&1`

Try it online!
> 3 votes

# Answer
# C (gcc), 29 bytes

```
f(){putchar(63)&rand()&&f();}

```

Try it online!
> 3 votes

# Answer
# Java, ~~58~~ ~~45~~ 44 bytes

```
String f(){return.5<Math.random()?"":1+f();}
```

Attempt This Online!

-1 thanks to @Kevin Cruijssen

Same strategy as the NodeJS answer. Previous answer did not fit challenge spec, this version turned out to be shorter as well.
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~28~~ 24 bytes

```
Dot@@Table[x,1/Random[]]

```

Thanks to att for –4!

Try it online!
> 3 votes

# Answer
# Zsh, 19 bytes

```
grep -oam1 x /*/ur*
```

Attempt This Online!

Explanation:

* `/*/ur*`: glob for `/dev/urandom`, an infinite stream of random bytes
* `grep x`: search for the letter `x`
* `-o`: print only the letter `x`s
* `-a`: force output even though `/dev/urandom` is a binary file
* `-m1`: quit after the first matching line

---

# Pure Zsh, 20 bytes

```
for ((;RANDOM;))<<<x
```

Attempt This Online!

Loop breaks with probability \\$ \frac 1 {32768} \\$ for each iteration.

Explanation:

* `for ((;RANDOM;))`: loop while `$RANDOM` (which is a random integer in the range \\$ \[0, 32768) \\$, is nonzero
* `<<<x`: print `x`

Here's a version for 2 bytes more with a probability of \\$ \frac 1 2 \\$, and is much more easy to demonstrate:

```
for ((;RANDOM%2;))<<<x
```

Attempt This Online!
> 3 votes

# Answer
## Batch, 28 bytes

```
@if %random% gtr 9 echo x&%0

```

Outputs an average of about 3276 `x`s, assuming `CMD.EXE` doesn't stack overflow first.
> 3 votes

# Answer
# Brachylog, 7 bytes

```
9w9ṙ9|↰

```

Try it online!

### Explanation

```
9w         Write 9
  9ṙ       Pick a random integer in 0..9
    9      If it is 9, terminate
     |↰    Else, recurse

```
> 3 votes

# Answer
# Alchemist, 14 bytes

```
_->Out__+_
_->

```

Try it online!

Breaks the loop with probability \\$\frac12\\$ at each iteration.

### Explanation

The program starts with a single `_` atom. Since both instructions consume only a `_` atom, they are both satisfied and one is chosen randomly. The first outputs the number of `_` atoms remaining (0) and produces another `_` atom to continue the loop. The second just consumes the atom, ending the loop.
> 3 votes

# Answer
# Julia 1.0, 22 bytes

```
!_=.1<rand()&&!show(1)

```

Try it online!
> 3 votes

# Answer
# C++, ~~112~~ 86 bytes

-26 bytes thanks to Unrelated String

```
#include<iostream>
main(){srand(time(0));for(int i=0;i<rand()%100;i++){std::cout<<1;}}

```

Try It Online!
> 3 votes

# Answer
# x86 32-bit machine code (Linux), 22 bytes

```
00000000: 31db f7e3 4243 6a31 89e1 0404 cd80 580f  1...BCj1......X.
00000010: c7f0 a801 75ea                           ....u.

```

Asssembly:

```
section .text
	global main
main:
	;call write(fd=ebx, *buf=ecx, count=edx)
	xor ebx, ebx	;ebx=0
	mul ebx		;eax=edx=0
	inc edx		;edx=1
	inc ebx		;ebx=1
	push 0x31	;push '1'
	mov ecx, esp 	;ecx=ptr to '1'
	add al, 4	;eax=4
	int 0x80	;syscall to print '1'
	pop eax		;fix stack

	;get rand & loop
	rdrand eax	;eax=rand()
	test al, 1	;eax%2==0?
	jnz main 	;if so, jmp to main

```

There is a 50% probability for each character printed for another one to print.

Try it online!
> 3 votes

# Answer
# Jelly, 5 bytes

```
2XĿȮ

```

Try it online!

Function submission. There are two functions defined in the above code; the one being submitted is `1Ŀ`, with `2Ŀ` being a helper function. Outputs strings of `2` to standard output (the TIO link has a footer to suppress implicit output of the function's return value, because that isn't part of the output).

## Explanation

Jelly isn't very good at this challenge, as golfing languages go, but I managed to beat the existing Jelly answer by one byte.

The function `1Ŀ` is defined as `2XĿȮ`. `2X` generates a random number, either 1 or 2. Then `Ŀ` runs the function with that number – this is either a recursive call if 1 was chosen as the random number, or a call to `2Ŀ` if 2 was chosen. Finally, it produces output (`Ȯ`) – the output will always be 2 because that's the argument implicitly chosen for the function calls. If `1Ŀ` calls itself many times recursively, it'll output from every recursive level, which is what produces a random-length string of 2s.

The function `2Ŀ` is defined with zero-length source code, and returns its input (i.e. the 2 that it was provided as input when called by `1Ŀ`).
> 3 votes

# Answer
# Retina, 6 bytes

```
?+`$
x

```

Try it online! Outputs an average of 1 `x`. Explanation: The `?` causes the loop created by `+` to run with a geometric distribution with a mean of `1`. Each iteration of the loop appends an `x` to current value, which is then output when the loop terminates.
> 2 votes

# Answer
# Excel, ~~19~~ 17 bytes

```
=REPT(1,1/RAND())

```

*-2 bytes excluding 0 length string*

Link to Spreadsheet
> 2 votes

# Answer
# Haskell, ~~75~~ 70 bytes

```
import System.Random
f=do n<-randomIO;putStr"x";if n then pure()else f

```

Try it online!

* Saved 5 thanks to @pxeger suggestions to use pure instead of return and semicolons;
> 2 votes

# Answer
# MSX-BASIC, 28 bytes

```
1IFRND(-TIME)<.9THEN?1:GOTO1

```
* `RND` with a negative value gets the first value from the pseudo-random sequence whose seed is the passed value.
* `TIME` is a system 16 bit variable that increases continuously (and goes back to 0 on overflow) at 50 or 60Hz.
* `?` is a convenient shortcut for `PRINT`.
> 2 votes

# Answer
# INTERCAL, 23 bytes

```
DOREADOUT#0DO%9TRYAGAIN

```

Try it online!

Prints a nonempty string of underscores separated by triple newlines, running a loop that continues 9% of the time (insert another digit if you want better odds).
> 2 votes

# Answer
## C - 76 Bytes

```
j;main(i){for(;j++<2+rand()%10;puts(""))for(i=0;i++<1+rand()%10;printf("x"));}

```

**Ungolfed**

```
j;

main(i)
{
    for(; j++ < 2 + rand() % 10; puts(""))
        for(i = 0; i++ < 1 + rand() % 10; printf("x"));

}

```

**Explanation**

A simple but complete program that prints a random number of strings of character 'x' of indeterminate length.
> 2 votes

# Answer
# Alice, ~~22~~ 17 bytes

```
2' e+EUw.n$@t'xoK

```

Try it online!

My first Alice attempt, I'm keen to see what can be made shorter!

## Explanations:

```
2' e+E              Pushes max int on the stack 2^(32-1)
      U             Random between max int and 0
       w.n$@     K  While the top of the stack is not 0
            t       -1 to the top of the stack
             'x     Pushes x on the stack
               o    Prints the top of the stack as a character

```
> 2 votes

# Answer
# Awk, 33 ~~34~~ bytes

```
END{for(srand();rand();)print"x"}

```

Try it online!

It is possible for awk's `rand()` to return 0, but very unlikely.

Thanks to Marius\_Couet for the byte!
> 2 votes

# Answer
# PHP, 74 bytes

With "include the empty string as a possible output".

```
while(0<$r=rand(0,100)/10){echo $r<0.1?'':str_repeat('p',round($r))."\n";}

```

Try it online!

---

# PHP, 52 bytes

```
while(0<$r=rand(0,9)){echo str_repeat('p',$r)."\n";}

```

Try it online!
> 1 votes

# Answer
# Perl 5, ~~18~~ 16 bytes

```
say while.9>rand

```

Try it online!

Saved two bytes by making the unary character a newline.
> 1 votes

# Answer
# Nim, 48 bytes

```
import random;randomize();while rand(1)<1:echo 1
```

Attempt This Online!

This program has a newline as a separator and a `'1'` as the character. `wc -c` was utilized to count the number of bytes. I am reasonably certain this is optimal for Nim; I therefore will offer a bounty of 50 rep to the person who outgolfs it.
> 1 votes

# Answer
# APL, 20 bytes

```
∇X←P
X←⍬
X,←'x'
→?4∇

```

The output strings are usually extremely short, but hypothetically they could be any length.
> 1 votes

# Answer
# Racket, 30 bytes

```
(do()((>(random).5))(print 1))

```

Try it online!

## Explanation

Creates a `do` loop that will only run if the `random`ly generated number is less than `.5`. The first argument of the `do` loop are the local variables and/or iterators. The second argument is the `stop?-expr`. If this argument returns true (`#t`), the loop will stop. Otherwise the body of the loop will be run.

```
(do () ((> (random) .5))
  (print 1))

```
> 1 votes

# Answer
# Fish, 31 bytes

```
while [ (random) = 0 ];echo;end

```

This uses the newline (U+000A) as the unary character. `random` returns any value from 0-32768 without arguments, so on most runs this will echo nothing. However, it is *technically* possible for this to echo an unlimited number of characters, just not very likely
> 1 votes

# Answer
# Befunge-93, 4 bytes

```
?@#.

```

Try it online!

## Explanation

The `?` instruction sends the program counter (PC) in a random direction. If the PC goes right, it hits the `@` instruction, which terminates the program. If it goes up or down, it makes a new random choice. If it goes left, it hits the `.` instruction, which pops the top of the stack and prints it as an integer. There is no stack underflow in Befunge (or at least not in the implementation tio uses), so the value popped is the default value, zero (`0`). So the program prints `0`, with a single space () as a separator. The bridge command `#` makes sure that another random choice will occur and the `@` isn't immediately triggered.
> 1 votes

# Answer
# VBA, 20 bytes

Anonymous immediate window function that outputs a sequence of newline literals of random length to the immediate window console.

```
While(rnd>.5):?:Wend

```
> 1 votes

# Answer
# Bash, 31 bytes

```
while(($RANDOM));do echo 1;done

```

Try it online!
> 0 votes

# Answer
# Emmental, 20 bytes

When the computer runs out of stack space it will crash.

```
;#58:#46#35#63#!#1#?

```

Try it online! When the computer runs out of stack space it will crash.
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
(¢TLɼ

```

Attempt This Online!

#### Explanation

```
(      # loop while the following is true:
 ¢     #  print a 0 without a trailing newline
  TL   #  push the range [1..10]
    ɼ  #  choose a random item from that list

```
> 0 votes

# Answer
# Thue 17 bytes

```
E::=
E::=E*
::=
E

```

On the interpreter that I use, it is randoms
> 0 votes

# Answer
# Ly, 8 bytes

```
1?[01?]p

```

Try it online!

Pushes the number 1 onto the stack a random number of times then exits. The accumulated numbers are printed automatically with a space between them. The probabilities favor small (or zero) numbers, but there's a non-zero change of any length output.

```
1?        - Push "1" on the stack, replace with 0|1 randomly
  [   ]   - Loop while the top of the stack is non-zero
   01?    - Push "0 1", pop them and push 0|1 randomly
       p  - Pop the "0" that ended the loop off the stack

```
> 0 votes

# Answer
# Volatile, 7 bytes

```
~(:-.~)

```

Assumes that the `.` instruction is present in the interpreter. Prints a random length of `0` characters. Empty string is possible. Zeroes may be separated by another character, depending on the implementation you're using.
> 0 votes

# Answer
```
jot 19 | mawk 'NF+=int(rand()*19)' OFS=x

```

---

```
1xxxxxxx
2xxxxxxxxxx
3xxxxx
4
5xxxxxxxxxxxxxxx
6xxxxxxxxx
7xxxxxxx
8xxxxx
9xxxxxxxxx
10xxxxxx
11xxx
12xxxxx
13xxxxxxxx
14x
15xxxxxxxxx
16xxxxxxxx
17xxxxxxxxxxxxxxxxxx
18xxxxx
19

```
> 0 votes

# Answer
# Yabasic, 22 bytes

Function that outputs a sequence of newline literals of random length.

```
While(ran()>.5):?:Wend

```

Try it online!
> 0 votes

---
Tags: code-golf, random, open-ended-function
---


title: Busy Letters & Evil CEOs

text:
# Question
Title: Busy Letters & Evil CEOs
Imagine you are given an array/string containing \\$5\\$ letters of the English alphabet, with each letter having any value from **A** to **Z** (inclusive).

Every *day*, each letter will perform a job, which can affect itself or other letters in the array. The letter's job is determined by the letter itself.

Most letters are, due to unemployment rates, jobless. However, a key few still have unique tasks they can perform each day:

* \\$A\\$: Yells at the letter to its right, forcing that letter to change to the next letter in the alphabet. If there is no letter to its right, does nothing.
* \\$Z\\$: Yells at the letter to its left, forcing that letter to change to the previous letter in the alphabet. If there is no letter to its left, does nothing.
* \\$L\\$: This one's pushy. It rotates the array by 1 element to the left, wrapping around so the first element becomes the last.

The final letter is \\$X\\$, The CEO. If it shows up *at any point*, that means *everyone is in trouble*. However, if \\$X\\$ does not show up within 30 days (30th day included), that means everything is alright and the busy letters are safe.

A single day concludes once every letter has finished doing its job. A configuration like `AJLF` will evolve like this over the course of 3 days:

```
AJLF    at start of Day 1
KLFA    at start of Day 2
LFAL    at start of Day 3
FAML    at start of Day 4

```

**A couple of important things to remember**:

* Any letter that is not part of those mentioned earlier does nothing.
* The letters themselves overflow. If a letter increases past `Z`, it becomes `A`. Similarly, decreasing past `A` will turn the letter to `Z`.
* Letters on the left do their job first. For example, if you have `A Z`, after a day the result is `A A` since the `Z` gets yelled at before it does its job. Another example is that `A K` will be `L A` at the start of the next day, as the `K` turns into an `L` and then does its job.
* A letter that wraps around due to \\$L\\$ will not do anything until the day is over, but the letter may still be changed.
* \\$X\\$ can appear even in the middle of the day, so a configuration like `AWZ` is *not* safe.

*Your* job is, given an array containing an arbitrary configuration of \\$5\\$ letters, find out if the letters are safe (that is, \\$X\\$ does not show up before 30 days pass). This initial configuration corresponds to the start of day \\$1\\$.

# Input

An array containing \\$5\\$ valid letters. You may assume \\$X\\$ will never be part of this initial array. If it makes things easier, you are allowed to treat the letters as case insensitive, and you may use any representation for those letters you want, as long as it is consistent and it does not affect your results.

# Output

Whether or not the busy letters are safe after 30 days. If they are, output `true` (or any equivalent value that indicates it). If they are not safe, output the day at which \\$X\\$ appeared.

## Rules

This is , so shortest number of bytes wins.

## Test Cases

```
Input     Safe?
------------------
RABOA     No: Day 15
HAWPE     No: Day 1
ZHLFF     Safe
EALZJ     Safe
KWLFZ     No: Day 30
AZVLB     No: Day 2
LLLEA     No: Day 12
LADZV     Safe

```

# Answer
> 1 votes
# Perl 5 `-pa`, 148 bytes

```
for$;(1..30){map{$_&&$F[$_]==26?--$F[$_-1]:$_<4&&$F[$_]==1?++$F[$_+1]:$F[$_]-12||push@F,shift@F;$\||=$;if grep/24/,@F}0..4;@F=map$_%26,@F[-5..-1]}}{

```

Try it online!

Input as integers (A=1, B=2, etc.). Output is the day of the CEO's arrival or Perl's `undef` which appears as blank.

# Answer
> 1 votes
# Python 3, 156 bytes

An incredible 13-bytes reduction by @JonathanAllan:

```
def g(x):
 for m in range(150):
  if 23in x:return m//5+1
  K=m%5and K;i=m%5-K;c=x[i];j=c==11;x=x[j:]+x[:j];K+=j;C=(c<1<4>i)-(c>24>0<i);x[C+i]=(x[C+i]+C)%26

```

Try it online!

A function that receives a list of integers \\$0 \leq n \lt 26\\$ of length 5, representing the letters from the alphabet. It returns `None` if the CEO does not appears, otherwise it returns the day it appeared.

This version removes nearly all if-statements from the previous implementation by taking advantage of the short-circuiting behavior of `and` and the relationship between `bool`s and `int`s. It also uses some dark magic regarding chained comparisons when calculating `C`.

Using if-statements inside a loop (or any indentation block) is expensive, since it requires a new-line and therefore including more indentation to match the outer block.

# Python 3, 169 bytes (original version)

```
def g(x):
 for m in range(150):
  if m%5<1:K=0
  if 23in x:return m//5+1
  i=m%5-K;c=x[i]
  if c==11:x=x[1:]+x[:1];K+=1
  C=(c<1)*(i<4)-(c>24)*(i>0);x[i+C]=(x[i+C]+C)%26

```

Try it online!

**How does it work?**

The loop iterates \\$150\\$ times: \\$30\\$ days \\$\times\\$ \\$5\\$ letters.

Variable `K` contains the number of rotations happened in the current day, according to

> A letter that wraps around due to \\$L\\$ will not do anything until the day is over, but the letter may still be changed.

The condition `if m%5<1:K=0` implements the "until the day is over" part.

We then check whether X is present in the array. If it is, `m//5 + 1` is returned. Since \\$0 \leq m \lt 150\\$, then \\$0 \leq m/5 \lt 30\\$, the current day (where the CEO appeared).

Variable `i` stores the index of the current letter (0-4) and variable `c` stores the current letter. Since whenever a rotation occurs, the current letter should be shifted back, a subtraction by `K` is made.

The condition `if c==11:` checks if the current letter is L. If it is, it rotates the array (`x=x[1:]+x[:1]`) and increments `K`.

The next line is a bit more complex. It evaluates two conditions: *i)* whether the current letter is A (`c<1`) and it's not the last letter (`i<4`); and *ii)* whether the current letter is Z (`c>24`) and it's not the first letter (`i>0`). Then, a subtraction is evaluated between *i)* and *ii)*:

* If *i)* is true (1) and *ii)* is false (0), `C` will be +1, implementing "Yells at the letter to its right, forcing that letter to change to the next letter in the alphabet"
* If *i)* is false (0) and *ii)* is true (1), `C` will be -1, implementing "Yells at the letter to its left, forcing that letter to change to the previous letter in the alphabet"
* Otherwise, if *i)* and *ii)* are equal, `C` will be 0, implementing "Any letter that is not part of those mentioned earlier does nothing"

The next statement changes the previous or the next element on the array (`i+C`) and forces it to the previous or the next letter on the alphabet, handling the overflow (`(x[...]+C)%26`).

# Answer
> 0 votes
# Charcoal, 93 bytes

```
ＦＳ⊞υ⌕αιＦ³⁰«≔⁰θＦＬυ«≔§υκη§≔υ⊕κ⁺§υ⊕κ∧¬η‹⊕κ⁺Ｌυθ≧⁺⁼η¹¹θ§≔υ⊖κ⁻§υ⊖κ∧⁼η²⁵›κ⁰≧﹪²⁶υ¿∧¬ⅈ№υ²³Ｉ⊕ι»ＵＭυ§υ⁺λθ

```

Try it online! Link is to verbose version of code. Outputs nothing if the input is safe. Explanation:

```
ＦＳ⊞υ⌕αι

```

Convert the input from a string of letters to a list of integers.

```
Ｆ³⁰«

```

Check for `30` days.

```
≔⁰θ

```

Start with no `L`s on any given day.

```
ＦＬυ«≔§υκη

```

Loop through the letters and their original indices.

```
§≔υ⊕κ⁺§υ⊕κ∧¬η‹⊕κ⁺Ｌυθ

```

Increment the next letter if this letter is an `A` and it is not currently the rightmost letter.

```
≧⁺⁼η¹¹θ

```

Keep track of any `L`s.

```
§≔υ⊖κ⁻§υ⊖κ∧⁼η²⁵›κ⁰

```

Increment the previous letter if this letter is a `Z` and is not the leftmost letter.

```
≧﹪²⁶υ

```

Overflow any increments from `Z` to `A` or decrements from `A` to `Z`.

```
¿∧¬ⅈ№υ²³Ｉ⊕ι

```

If this is the first appearance of `X` then output the day number.

```
»ＵＭυ§υ⁺λθ

```

Actually rotate the letters as necessary.

# Answer
> 0 votes
# Funge-98, 200 bytes

```
"HTRF"4("RBUS"4(4k&'v00pfa*10p020p
>10g:!3j@.0_1-10p4L20g10g5%`!3jJ21_20g1-20p
^:0w4L10g5%!!+'%:051C$4L4L4L4L
^  [:'\ w4L4L4L4L410g5%`-'%:051C$4L
^#_^#!-b:<>j#'p02+1g02p01+1g01
'-3jR11_'10g5/-.@

```

Try it online!

Takes input as a list of 5 integers between 0 and 25. Outputs 0 if the letters are safe, and a number between 1 and 30 if they are not.

Contains non-printable characters, so here is a hex dump:

```
00000000: 2248 5452 4622 3428 2252 4255 5322 3428  "HTRF"4("RBUS"4(
00000010: 346b 2627 7630 3070 6661 2a31 3070 3032  4k&'v00pfa*10p02
00000020: 3070 0a3e 3130 673a 2133 6a40 2e30 5f31  0p.>10g:!3j@.0_1
00000030: 2d31 3070 344c 3230 6731 3067 3525 6021  -10p4L20g10g5%`!
00000040: 336a 4a32 315f 3230 6731 2d32 3070 0a5e  3jJ21_20g1-20p.^
00000050: 3a30 7734 4c31 3067 3525 2121 2b27 1a25  :0w4L10g5%!!+'.%
00000060: 3a30 3531 4324 344c 344c 344c 344c 0a5e  :051C$4L4L4L4L.^
00000070: 2020 5b3a 2719 5c20 7734 4c34 4c34 4c34    [:'.\ w4L4L4L4
00000080: 4c34 3130 6735 2560 2d27 1a25 3a30 3531  L410g5%`-'.%:051
00000090: 4324 344c 0a5e 235f 5e23 212d 623a 3c3e  C$4L.^#_^#!-b:<>
000000a0: 6a23 1327 7030 322b 3167 3032 7030 312b  j#.'p02+1g02p01+
000000b0: 3167 3031 0a27 172d 336a 5231 315f 271e  1g01.'.-3jR11_'.
000000c0: 3130 6735 2f2d 2e40                      10g5/-.@

```

---
Tags: code-golf, string, array, decision-problem
---


title: Very Simple Grid Marks

text:
# Question
Title: Very Simple Grid Marks
Write a program or function that takes in three positive integers, W, H, and N. Print or return a W×H grid of `.`'s where every Nth `.` in normal English reading order is replaced with an `X`.

For example, given W = 7, H = 3, N = 3, the grid is 7 characters wide and 3 high, and every third character reading from the top left is an `X`:

```
..X..X.
.X..X..
X..X..X

```

Similarly, if the input is W = 10, H = 4, N = 5, the output would be:

```
....X....X
....X....X
....X....X
....X....X

```

### Notes

* "Normal English reading order" means going left to right on each line, from the top line to the bottom.
* When N is 1 then all the `.`'s will become `X`'s.
* You may use any two distinct printable ASCII characters in place of `.` and `X`.
    + If you use space () then trailing spaces are not required when the result would be visually the same. (Empty lines are still required.)
    + You may not using something else in place of the newlines that shape the grid.
* The exact input format and order of W, H, and N is not super important. Things like `[H,W,N]` or `N\nW,H` are alright.
* A trailing newline in the output is fine.
* The shortest code in bytes wins!

# Examples

```
W = 5, H = 3, N = 1
XXXXX
XXXXX
XXXXX

W = 5, H = 3, N = 2
.X.X.
X.X.X
.X.X.

W = 5, H = 3, N = 3
..X..
X..X.
.X..X

W = 5, H = 3, N = 4
...X.
..X..
.X...

W = 5, H = 3, N = 5
....X
....X
....X

W = 5, H = 3, N = 6
.....
X....
.X...

W = 5, H = 3, N = 7
.....
.X...
...X.

W = 5, H = 3, N = 15
.....
.....
....X

W = 5, H = 3, N = 16 (or more)
.....
.....
.....

W = 1, H = 1, N = 1
X

W = 1, H = 1, N = 2 (or more)
.

W = 8, H = 6, N = 2
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X

W = 8, H = 6, N = 3
..X..X..
X..X..X.
.X..X..X
..X..X..
X..X..X.
.X..X..X

W = 8, H = 6, N = 4
...X...X
...X...X
...X...X
...X...X
...X...X
...X...X

W = 8, H = 6, N = 7
......X.
.....X..
....X...
...X....
..X.....
.X......

W = 8, H = 6, N = 16
........
.......X
........
.......X
........
.......X

W = 37, H = 1, N = 4
...X...X...X...X...X...X...X...X...X.

W = 1, H = 10, N = 8
.
.
.
.
.
.
.
X
.
.
```

# Answer
# J, ~~9~~ 5 bytes

```
$":&1

```

Uses spaces and `1`'s and expects input in the form `H W f N`

Explanation:

```
$":&1
   &1 bonds the fixed right argument 1 to ":
 ":   formats the right argument number (1) to take up left argument (N) number of cells
      padding with spaces, resulting  in "  1"
$     reshape to H-by-W with repeating the string if necessary

```

Usage:

```
   3 7 ($":&1) 3
  1  1
 1  1
1  1  1

```

Try it online here.
> 13 votes

# Answer
# Python 2, 60 bytes

```
w,h,n=input()
s='%%%dd'%n%0*w*h
exec"print s[:w];s=s[w:];"*h

```

This prints space and `0` in place of `.` and `X`. Input is taken as a tuple in the form of `w,h,n`.
> 11 votes

# Answer
## J, 12 bytes

```
$'X'_1}#&'.'

```

This is a dyadic function that takes the array `H W` as its left argument and `N` as its right argument. Usage:

```
  f =: $'X'_1}#&'.'
  3 5 f 3
..X..
X..X.
.X..X

```

### Explanation

```
$'X'_1}#&'.'
         '.'  The character '.'
       #&     repeated N times
    _1}       with the last character
 'X'          replaced by 'X'
$             reshaped into an HxW array

```
> 7 votes

# Answer
# BBC Basic, 67 ASCII characters, tokenised filesize 43 bytes

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

```
INPUTw,h,n:WIDTHw:PRINTLEFT$(STRING$(w*h,STRING$(n-1,".")+"X"),w*h)

```

BBC basic has a handy command for limiting the field width. We use `STRING$` to make `w*h` copies of the string of `n-1` periods followed by an X. Then we use LEFT$ to truncate this to `w*h` characters.
> 5 votes

# Answer
## Minkolang 0.14, ~~34~~ ~~30~~ ~~28~~ 22 bytes

```
n2-D1n$zn[z[1Rd6ZO]lO]

```

Check one case here and check all test cases here. Expects input like `N W H`.

### Explanation

```
n                 Take number from input (N)
 2-               Subtract 2
   D              Duplicate the top of stack (which is 0 because it's empty) N-2 times
    1             Push a 1 onto the stack
n                 Take number from input (W)
 $z               Store W in the register (z)
n                 Take number from input (H)
 [                Open a for loop that repeats H times
  z[              Open a for loop that repeats W times
    1R            Rotate 1 step to the right
      d           Duplicate top of stack
       6Z         Convert number to string
         O        Output as character
          ]       Close for loop
           lO     Output a newline
             ]    Close for loop

```

As Minkolang's codebox is toroidal, this will wrap around to the beginning. As every `n` will now take in `-1`, this eventually crashes with an error and no further output, which is allowed.
> 4 votes

# Answer
## APL, 13 bytes

```
{⍪,/⍕¨⍺⍴⍵=⍳⍵}

```

This takes `H W` as the left argument and `N` as the right argument.

Explanation:

```
{⍪,/⍕¨⍺⍴⍵=⍳⍵}     Dyadic function (args are ⍺ on left, ⍵ on right):
        ⍵=⍳⍵      ⍵ = (1 2 3...⍵); this is ⍵-1 0s followed by a 1
      ⍺⍴          Shape by the left argument; e.g. 5 3 gives a 5x3 array
    ⍕¨            Stringify each entry
  ,/              Join the strings in each row
 ⍪                Make column vector of strings

```

Try it online: first test cases, last test case. Note that although this shows boxed output, my copy of Dyalog doesn't.
> 4 votes

# Answer
## CJam (16 bytes)

```
{1$*,:)@f%:!/N*}

```

Takes input on the stack in the order `N W H`, returns string using characters `0` and `1`. Online demo

### Dissection

```
{        e# Anonymous function. Stack: N W H
  1$*,   e# Stack: N W [0 1 ... W*H-1]
  :)     e# Stack: N W [1 2 ... W*H]
  @f%    e# Stack: W [1%N 2%N ... W*H%N]
  :!     e# Map Boolean not, taking 0 to 1 and anything else to 0
  /      e# Split into W-sized chunks (i.e. the lines of the grid)
  N*     e# Join the lines with newlines
}

```
> 4 votes

# Answer
# CJam, 20 Bytes

```
q~:Z;_@*,:){Z%!}%/N*

```

Takes input as H W N.
> 2 votes

# Answer
# Japt, ~~33~~ ~~32~~ ~~27~~ 25 bytes

```
SpW-1 +Q p-~U*V/W f'.pU)·

```

Takes input in format `W H N`. Uses  and `"` in place of `.` and `X`, respectively. Try it online!

### Ungolfed and explanation

```
SpW-1 +Q p-~U*V/W f'.pU)·qR
          // Implicit: U = width, V = height, W = interval
SpW-1 +Q  // Create a string of W - 1 spaces, plus a quotation mark.
p-~U*V/W  // Repeat this string ceil(U*V/W) times.
f'.pU)    // Split the resulting string into groups of U characters.
qR        // Join with newlines.
          // Implicit: output last expression

```

Suggestions welcome!
> 2 votes

# Answer
# Vitsy, ~~25~~ ~~23~~ ~~22~~ ~~21~~ 19 Bytes

Thanks to @Sp3000 for pointing out that I don't need a duplicate and saving me 2 bytes!

Takes input as `N W H`. Try it online!

```
1}\0XrV\[V\[{DN]aO]
1                         Push 1 to the stack.
 }                        Push the backmost to the front and subtract 2.
  \0X                     Duplicate the 0 temp variable times.
     r                    Reverse the stack.
      V                   Save as final global variable.
       \[         ]       Repeat top item times.
         V\[   ]          Repeat global variable times.
            {DO           Duplicate, output, then shift over an item.
                aO        Output a newline.
```
> 2 votes

# Answer
# K, ~~21~~ ~~19~~ ~~18~~ 14 bytes

Takes arguments as `(H W;N)`:

```
{".X"x#y=1+!y}

```

In action:

```
  f:{".X"x#y=1+!y};

  f.'((3 5;1);(3 5;2);(3 7;3);(4 10;5);(3 5;16))
(("XXXXX"
  "XXXXX"
  "XXXXX")
 (".X.X."
  "X.X.X"
  ".X.X.")
 ("..X..X."
  ".X..X.."
  "X..X..X")
 ("....X....X"
  "....X....X"
  "....X....X"
  "....X....X")
 ("....."
  "....."
  "....."))

```
> 2 votes

# Answer
# MATLAB, ~~61 55~~ 54 bytes

```
function c=g(d,n);b=ones(d);b(n:n:end)=0;c=[b'+45,''];

```

Wow, I thought MATLAB would be competitive in this one, but how wrong I was!

The function creates an array of 1's of the correct dimensions, and then sets every n'th element to be 0 (MATLAB implicitly handles wrapping around the indices into 2D). We then add on 45 ('-') to this number and converted to a char array to be returned.

The questions allows any distinct two ASCII characters to be used for the grid, I am using '-' in place of 'x' to save some bytes. The input format is also not fixed, so it should be supplied as `[w h],n` \- i.e. an array of width and height, and then n as a second parameter.

---

This also works with **Octave** and can be tried online here. The function is already set up in the linked workspace, so you can simply call for example:

```
g([4,5],3)

```

Which outputs:

```
..-.
.-..
-..-
..-.
.-..

```
> 2 votes

# Answer
## Processing, 93 bytes (Java, 104 bytes)

```
void f(int a,int b,int c){for(int i=0;i<a*b;i++)print((i%c>c-2?"X":".")+(i%a>a-2?"\n":""));}}

```

The reason I used Processing instead of Java is that you don't need to acces the pointer by tiping `System.out` because a local variable is directly accessible. I earned 11 bytes with this. The function doesn't return the result but prints it.
> 2 votes

# Answer
# K (ngn/k), 10 bytes

```
{y#|x$"X"}

```

Try it online!

Takes input as two arguments; `N` as the first/left arg, and `(H;W)` as the second/right arg. Uses `" "` and `"X"` as the output characters.

* `|x$"X"` right pad "X" to the desired length (fills with spaces), and reverse it (to put the "X" at the end)
* `y#` reshape the above to the desired dimensions; the above gets repeated over and over until it is long enough
> 2 votes

# Answer
# Pyth - ~~19~~ ~~18~~ 17 bytes

Hope to golf it more. Takes input as `N\n[W, H]`.

```
jc.[k+*dtvzN*FQhQ

```

Test Suite.
> 1 votes

# Answer
# R, 66 bytes

```
function(w,h,n){x=rep(".",a<-w*h);x[1:a%%n<1]="X";matrix(x,h,w,T)}

```

This is a function that accepts three integers and returns a matrix of character values. To call it, assign it to a variable.

Ungolfed:

```
f <- function(w, h, n) {
    # Get the area of the square
    a <- w*h

    # Construct a vector of dots
    x <- rep(".", a)

    # Replace every nth entry with X
    x[1:a %% n == 0] <- "X"

    # Return a matrix constructed by row
    matrix(x, nrow = h, ncol = w, byrow = TRUE)
}

```
> 1 votes

# Answer
# JavaScript (ES6), ~~65~~ 60 bytes

```
(w,h,n)=>eval('for(i=r=``;i++<w*h;i%w?0:r+=`\n`)r+=i%n?0:1')

```

## Explanation

```
(w,h,n)=>eval('    // use eval to remove need for return keyword
  for(
    i=             // i = current grid index
      r=``;        // r = result
    i++<w*h;       // iterate for each index of the grid
    i%w?0:r+=`\n`  // if we are at the end of a line, print a newline character
                   // note: we need to escape the newline character inside the template
  )                //       string because this is already inside a string for the eval
    r+=i%n?0:1     // add a 0 for . or 1 for X to the result
                   // implicit: return r
')

```

## Test

```
W = <input type="number" id="W" value="7" /><br />
H = <input type="number" id="H" value="3" /><br />
N = <input type="number" id="N" value="3" /><br />
<button onclick="result.innerHTML=(

(w,h,n)=>eval('for(i=r=``;i++<w*h;i%w?0:r+=`\n`)r+=i%n?0:1')

)(+W.value,+H.value,+N.value)">Go</button>
<pre id="result"></pre>
```
> 1 votes

# Answer
## Mathematica, 85 bytes

```
""<>(#<>"
"&/@ReplacePart["."~Table~{t=# #2},List/@Range[#3,t,#3]->"X"]~Partition~#)&

```

As with many other solutions, this creates a single row, then partitions it.
> 1 votes

# Answer
# JavaScript (ES6), 55 bytes

```
(w,h,n)=>(f=i=>i++<w*h?+!(i%n)+(i%w?"":`
`)+f(i):"")(0)

```

Uses the IIFE `f` to loop to save a return statement.

Output for w=5, h=3, n=7:

```
00000
01000
00010

```
> 1 votes

# Answer
**C#, 185 bytes**

```
using System;class x{void a(int w,int h,int n){int c=1;for(int i=0;i<h;i++){for(int j=1;j<=w;j++){if(c%n==0){Console.Write("x");}else{Console.Write(".");}c++;}Console.WriteLine();}}}

```

For a more readable Reading:

```
using System;
class x
{
  void a(int w, int h, int n)
  {
    int c = 1;
    for (int i = 0; i < h; i++)
    {
        for (int j = 1; j <= w; j++)
        {
            if (c % n == 0)
            {
                Console.Write("x");
            }
            else
            {
                Console.Write(".");
            }
            c++;
        }
        Console.WriteLine();
     }
  }
}

```

Usage:

```
new x().a(7, 3, 3);

```
> 1 votes

# Answer
# Vyxal 3 `jR`, 8 bytes

```
×ƛ?Ḋ]¹Ẇ“

```

input as `W,H,N` Try it Online!

```
×ƛ?Ḋ]¹Ẇ“
×ƛ  ]     # Map over the range H x W
  ?Ḋ      # Divisible by N?
     ¹Ẇ“  # Split into chunks of length W and join on nothing
# j flag joins on newlines

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Ruby, ~~67~~ 56 bytes

```
->w,h,n{(1..h).map{(1..w).map{o,$.=$.%n<1?1:0,$.+=1;o}}}

```

Printing an array since it is accepted.

**67 bytes**

```
->w,h,n{i=1;puts (1..h).map{(1..w).map{o,i=i%n<1?1:0,i+=1;o}.join}}

```

**Ungolfed:**

```
-> w, h, n {
  (1..h).map {
    (1..w).map {
      o, $. = $.%n < 1 ? 1 : 0, $.+ = 1
      o
    }
  }
}

```

Usage:

```
->w,h,n{(1..h).map{(1..w).map{o,$.=$.%n<1?1:0,$.+=1;o}}}[8,6,7]
=> [[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]]

```
> 0 votes

# Answer
# Julia, 50 bytes

```
f(w,h,n)=reshape([i%n<1?"X":"." for i=1:w*h],w,h)'

```

This creates a function `f` that accepts three integers and returns a 2-dimensional array of strings.

Ungolfed:

```
function f(w::Integer, h::Integer, n::Integer)
    # Construct an array of strings in reading order
    a = [i % n == 0 ? "X" : "." for i = 1:w*h]

    # Reshape this columnwise into a w×h array
    r = reshape(a, w, h)

    # Return the transpose
    return transpose(r)
end

```
> 0 votes

# Answer
## MATLAB, 44 bytes

Note: Very different approach than the one used by Tom Carpenter.

```
@(x,y)char(reshape(~mod(1:prod(x),y),x)'+46)

```

Defines an anonymous function that accepts inputs as `[W,H],N`. I approached this problem using not-the-modulo-of-*N* for an array 1:W\*H and then simply reshaping the solution to a two-dimensional array, which is then converted to a character array.

Example output for `[5,3],7`:

```
.....
./...
.../.

```
> 0 votes

# Answer
# Common Lisp, SBCL, 94 bytes

```
(lambda(a b c)(dotimes(i(* a b))(format t"~:[.~;X~]~@[~%~]"(=(mod(1+ i)c)0)(=(mod(1+ i)a)0))))

```

### Explanation

```
~:[.~;X~] <-- takes argument - if argument is true write ., if false write X
~@[~%~] <-- takes argument - if argument is true write newline, if not treat argument as if it was not used

```

`(=(mod(1+ i)c)0)(=(mod(1+ i)a)0)` looks pretty silly (because it's so similiar but I don't know if it can be solved, saving bytes

I use `(1+ i)` instead of `i` because `dotimes` starts from `i=0` and I want to start from `1`. It is also helpful because I can use `(* a b)` instead of `(1+(* a b))`
> 0 votes

# Answer
# Japt `-R`, 9 bytes

Takes input as `[W,H],N` and uses spaces instead of `.`s & `"`s instead of `X`s.

```
×îQùV)òUÎ

```

Try it
> 0 votes

# Answer
# Uiua, 17 bytes

```
↯⇌⊟⊙⊙(⇌⊂@X↯:@.-1)

```

Test pad
> 0 votes

# Answer
# Perl 5 `-a`, 44 bytes

```
print$_%$F[1]&&1,$/x!($_%"@F")for 1.."@F"*<>

```

Try it online!

Input format is:

```
W N
H

```

Output uses `1` for the spacer and `0` for the character.
> 0 votes

# Answer
# Java, ~~185~~ 183 bytes

Thanks Thomas Kwa, for saving me 2 bytes!

```
interface B{static void main(String[] a){int w = Byte.parseByte(a[0]);for(int i=0;i++<w*Byte.parseByte(a[1]);)System.out.print((i%Byte.parseByte(a[2])>0?".":"X")+(i%w<1?"\n":""));}}

```

Ungolfed (ish):

```
interface A {
  static void main(String[] a) {
    int w = Byte.parseByte(a[0]);
    for(
      int i = 0;
      i++ < w*Byte.parseByte(a[1]);
    )
      System.out.print((
        i%Byte.parseByte(a[2]) > 0 ? "." : "X"
        )+(
        i%w < 1 ? "\n" : ""
      ));
  }
}

```

Usage:

```
$ java B 5 3 7
.....
.X...
...X.

```

Maybe java will win one day :P
> -1 votes

---
Tags: code-golf, arithmetic, grid
---


title: Generating Minesweeper grids

text:
# Question
Title: Generating Minesweeper grids
**Minesweeper** is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.

Given a grid size, and a set of mines, generate the Minesweeper grid for that set of mines.

**Input:** Two integers indicating the grid size, and an undefined number of integers indicating the mine positions. Positions will be given as (column position, row position), and the indexes will start at row 1.

**Output:** The Minesweeper grid. If there are no mines around a block, print an `x`. For each new row, print a newline. Please output all mines as an asterisk `*`. Do not leave any whitespace between the values in the row when printing.

**Test Cases:**

Input "5 5 1 3 3 5 2 4":

```
xxxxx
11xxx
*21xx
2*21x
12*1x

```

Input "3 4 3 1 1 4 2 3 3 2":

```
x2*
13*
2*2
*21

```

Shortest code wins.

# Answer
### GolfScript ~~122 98 94 93 91 88 87 85 82 81 80~~ 71

```
~]2/(\:m;~\:w*,{[.w%)\w/)]:^m\?)42{m{^*~-.*@@-.*+3<},,72or 48+}if}%w/n*

```

**Online demos:**

Test Case 1: link

Test Case 2: link
> 11 votes

# Answer
## J, 124 116 112 101 87 86 85 84 83 82 79 76 75 72 68 characters

```
'0x'charsub|:1":3 3(+/@,+9*4&{@,);._3[1(}.x)}0$~2+>{.x=._2<\".1!:1[1

```

Found what I was looking for - a way to get rid of the spaces (`1":`) - and finally I'm competitive. Now I just need to figure out the empty set of mines problem.

Takes input from the keyboard.

**Edit**

New version makes use of a side effect of `1":` \- numbers larger than 9 are replaced by `*`.
> 10 votes

# Answer
# brainfuck, ~~1001~~ 896 bytes

```
,[>,]-[<]>>++[<[<+<+>>-]<[>+<-]>[>]>[>>[>>>>]>]++[-<+]-[<]<++[>>[>]>[>>[>>>>]>]+<++[-<+]-[<]<-]>>>-]>[>]>[>>[>>>>]<<<->>>>]+[-<+]-[<]>>[[>]>--<<[<]>>[[>]+[->+]+>>[>>>>]>--<+[-<+]-[<]>>-]>[>]+[->+]+>>--<+[-<+]-[<]<[>>[>]+[->+]+>>>>--<+[-<+]-[<]<-]>>[>]+[->+]+>++[-<+]-[<]>>]>[+>>[>>>>]>]<<<<<[<<<<]>>-<+[-<+]>>>>[>>>>]>[-[--<<<<<[<<<<]>>>>--[>>>>]>>>[>>>>]>>>--<+[-<+]++>>>>>>[>[<--<<<[-[>>>>>>+<<<<<+<-]>+<]>[<+>-]>>>>+++[<<<+[-<+]->[-[+[->+]->>>+<<<<+[-<+]->>+<-]>+<]>[<+>-]+[->+]->>-[<<<+[-<+]+>>>>-->+[->+]->>[<<<+>>>-]]<<<[>>>+<<<-]>>>]<<<+[-<+]+<<<<-->+[->+]->>>>>[-[<<+>>>+<-]>+<]>[<+>-]<<<<+++[+[->+]->[-[<<+[-<+]->>>++[->+]->>+<-]>+<]>[<+>-]<<<+[-<+]->>-[+[->+]+>>>>--<+[-<+]->>[<<<+>>>-]]<<<[>>>+<<<-]>>>]+[->+]+<<<<--<+[-<+]->-[>>[-]<<++++++[>++++++<-]>.[-]+<<<]<[>>>[<++++++[>++++++++<-]>.[-]<]<<<[<++++++++[<+++++++++++>-]<.[-]>]<]>>>>+<<++>]>[<+>-]>>]->+[->+]++[-<+]++++++++++.[-]]>]

```

Try it online! or try the old version with integer input

One day of programming and three days of bugfixing ^^

This uses a few parts of my Game Of Life code. Instead of counting living cells, this counts bombs. Since input as codepoints is allowed by the general rules, this uses them instead of "readable" integers.

```
[
Data: colCount, rowCount, {BombCoordinates}, -1 (start of arrays/"soa"), 0, {RowData}
BombCoordinates: bombCol, bombRow
RowData: rowFlag, 0, {CellData}, 0
CellData: cellFlag, cellState, temp, bombCount

rowFlag: 0=EOF, 1=inactive (all cells inactive), 2=active
cellFlag: -1=marker for finding cell (cell to be counted or current cell), 0=EOF, 1=normal
cellState: 0=inactive, 1=normal, 2=bomb
temp: helper to exit if-statements
bombCount: count of neighbor cells that contain bombs
inactive cells or rows will not be printed. They are only used for an easier counting algorithm.
]

#### input values as codepoints ####
,[>,]

#### setup two dimensional array ####
-                   set soa
[<]>>               go to rowCount
++                  add two inactive rows
[                   for each row
  <[<+<+>>-]          copy colCount two times to the next left cells
  <[>+<-]             move one of the copies back to the original cell
  >[>]>[>>[>>>>]>]    go to new row position
  +                   set rowFlag (only 1 while initialization)
  +[-<+]-[<]<         go to copy of colCount
  ++                  add two inactive cells per row
  [                   for each col
    >>[>]>[>>[>>>>]>]   go to new cell position
    +<+                 set cellFlag and cellState = normal
    +[-<+]-[<]<         return to copy of colCount
    -                   decrement
  ]
  >>>-                decrement rowCount
]

#### setup active/inactive flags of cells ####
>[>]>[              for each row
  >>[>>>>]<<<-        set last cell inactive
  >>>>                go to next row
]

#### mark the bombs ####
+[-<+]-[<]>>        go to bombRow
[                   while there are bombRow values left
  [>]>--              set rowFlag of first row = neg 1 (as a marker)
  <<[<]>>             return to bombRow
  [                   for each bombRow
    [>]+[->+]           find first marker after soa
    +                   set rowFlag = 1
    >>[>>>>]>           go to next rowFlag
    --                  make a marker of it
    <+[-<+]-[<]>>       return to bombRow
    -                   decrement
  ]
  >[>]+[->+]          go to selected rowFlag
  +                   set rowFlag = 1
  >>--                set cellFlag of first cell = marker
  <+[-<+]-[<]<        go to bombCol
  [                   for each bombCol
    >>[>]+[->+]         find first marker after soa
    +                   set cellState = 1
    >>>>                go to next cellState
    --                  set it neg 1 (as a marker)
    <+[-<+]-[<]<        return to bombCol
    -                   decrement
  ]
  >>[>]+[->+]         find first marker after soa
  +                   set cellFlag = normal
  >+                  set cellState = bomb
  +[-<+]-[<]>>        go to next bombRow
]

#### setup active/inactive flags of rows ####
>[                  for each row
  +                   set rowFlag = 2 (active)
  >>[>>>>]>           go to next rowFlag
]
<<<<<[<<<<]>>-      set rowFlag of last row = 1 (inactive)

#### count bombs in neighborhood ####
<+[-<+]>>>>[>>>>]>  go to second row
[                   for each row
  -[                  if active
    --                  set it neg 1 (marker)
    <<<<<[<<<<]>>>>     go to cellFlag of first cell in previous row
    --                  set it neg 1 (marker)
    [>>>>]>>>[>>>>]>>>  go to cellFlag of first cell in next row
    --                  set it neg 1 (marker)
    <+[-<+]             return to rowFlag
    ++                  set rowFlag = 2 (active)

    >> >>>>[            for each cell (starting with second)
      >[                  if active
        <--                 set cellFlag = neg 1 (marker)

        # check if cell to the left is a bomb
        < <<                go to cellState of previous cell
        [                   if active
          -[                  if bomb
            >> >>>>+            increment bombCount
            <<<< <              go back to checked cell
            +                   set temp = 1
            <-                  set cellState = 0 to exit if
          ]
          >+<                 increment temp
        ]
        >[<+>-]             restore cellState

        # check if cells on top are bombs
        > >>>               go to temp of current cell
        +++[                do three times
          <<<+[-<+]-          go to next marker to the left
          >[                  if active
            -[                  if bomb
              +[->+]-             return to current cell
              >>>+                increment bombCount
              <<<<+[-<+]->        return to counted cell
              >+                  set temp = 1
              <-                  set cellState = 0 to exit if
            ]
            >+<                 increment temp
          ]
          >[<+>-]             restore cellState
          +[->+]-             go to current cell
          >>-                 decrement temp
          [                   if temp != 0
            <<<+[-<+]           go to marked cell
            +                   set cellFlag = normal
            >>>>--              set cellFlag of next cell = marker
            >+[->+]->>          return to currentCell temp
            [<<<+>>>-]          store value of temp in previous cell bombCount (to exit if)
          ]
          <<<[>>>+<<<-]>>>    restore temp value
        ]
        <<<+[-<+]           go to marked cell
        +                   set cellFlag = normal
        <<<<--              set previous cellFlag = marker
        >+[->+]-            return to current cell

        # check if cell to the right is a bomb
        >>> >>              go to cellState of next cell
        [                   if active
          -[                  if bomb
            <<+                 increment bombCount
            >>>                 go back to checked cell
            +                   set temp = 1
            <-                  set cellState = 0 to exit if
          ]
          >+<                 increment temp
        ]
        >[<+>-]             restore cellState

        # check if cells below are bombs
        <<< <               go to currentCell temp
        +++[                do three times
          +[->+]-         go to next marker to the right
          >[              if active
            -[              if bomb
              <<+[-<+]-       return to current cell
              >>>+            increment bombCount
              +[->+]->        return to counted cell
              >+              set temp = 1
              <-              set cellState = 0 to exit if
            ]
            >+<             increment temp
          ]
          >[<+>-]         restore cellState
          <<<+[-<+]-      go to current cell
          >>-             decrement temp
          [               if temp != 0
            +[->+]          go to marked cell
            +               set cellFlag = normal
            >>>>--          set cellFlag of next cell = marker
            <+[-<+]->>      return to currentCell temp
            [<<<+>>>-]      store value of temp in previous cell bombCount (to exit if)
          ]
          <<<[>>>+<<<-]>>>restore temp value
        ]
        +[->+]          go to marked cell
        +               set cellFlag = normal
        <<<<--          set previous cellFlag = marker
        <+[-<+]-        return to current cell

        # print
        >-[             if bomb
          >>[-]<<         delete bombCount
          ++++++[>++++++<-]>.print "*"
          [-]+            set temp = 1
          <<<             use previous cell bombCount as exitIf
        ]
        <[              else
          >>>[            if bombCount != 0
            <++++++[>++++++++<-]add 48 to get ascii number
            >.              print
            [-]             set number = 0 (for use as exitIf from next cell)
            <               go to temp for exit if
          ]
          <<<[            else
            <++++++++[<+++++++++++>-]<.print "X"
            [-]             delete value (for use as exitIf from next cell)
            >               go to exitIf
          ]
          <               go to exitElse
        ]
        > >>>+          increment temp
        <<++>           set cellFlag = normal
      ]
      >[<+>-]         restore cellState
      >>              go to cellFlag of next cell
    ]
    -               set marker
    >+[->+]         go to next marker
    +               set cellFlag = normal
    +[-<+]          return to marker
    +++++ +++++.[-] print newline
  ]
  >               go to next row
]

```
> 6 votes

# Answer
# APL (Dyalog Unicode), ~~59~~ ~~57~~ 54 bytes

With a more flexible input format this could be 39 bytes

```
{⍉{5⌷,⍵:'*'⋄×r←+/,⍵:⍕r⋄'x'}⌺3 3⊢1@(1↓⍵)⊢0⍴⍨⊃⍵}⊢⊂⍨2|⍳∘≢

```

Try it online!

The whole structure is a train, first `⊢⊂⍨2|⍳∘≢` splits the input into pairs, then the large *dfn* is called on the list of pairs:

`0⍴⍨⊃⍵` Create a matrix of 0's where the dimensions are given by the first pair.

`1↓⍵` all but the first pair
`1@(...)` at those indices place 1's in the matrix.

`{ ... }⌺3 3` apply the left function on each 3×3 neighborhood (padded with zeros):

`5⌷,⍵` If the value at index 5 of the flattened neighborhood (the center) is 1, return `'*'`
`×r←+/,⍵` If the sum of the neighborhood is positive, return it as a string `⍕r`
Otherwise return `'x'`

transpose the matrix because the order of axis is different in APL and the challenge.
> 5 votes

# Answer
## VBA - 298 chars

```
Sub m(x,y,ParamArray a())
On Error Resume Next:ReDim b(x,y):For i=0 To (UBound(a)-1) Step 2:c=a(i):d=a(i+1):b(c,d)="*":For e=c-1 To c+1:For f=d-1 To d+1:v=b(e,f):If v<>"*" Then b(e,f)=v+1
Next:Next:Next:For f=1 To y:For e=1 To x:v=b(e,f):s=s & IIf(v<>"",v,"x")
Next:s=s & vbCr:Next:MsgBox s
End Sub

```

Skipping over errors with `On Error Resume Next` saved me some characters, but this still isn't nearly as good as some of the other answers. :-/
> 3 votes

# Answer
# C++, 230 chars

```
#import<iostream>
int*p,n,m,x,y,i,j,k,a[999][999];main(){for(std::cin>>m>>n;std::cin>>y>>x;)for(i=2;~i--;)for(j=2;~j--;*p+=i|j&&~*p?:~*p)p=a[x+i]+y+j;for(;k<n*m;std::cout<<char(x?~x?x+48:42:120)<<(j<m)+"\n")x=a[k/m+1][j=k++%m+1];}

```

-11 bytes thanks to `ceilingcat`

-15 bytes thanks again to `ceilingcat`. Truly bigbrain

-14 bytes thanks to `ceilingcat` and I

-8 bytes thanks to `ceilingcat` and I

Try it online
> 3 votes

# Answer
# 05AB1E, 50 bytes

```
#2ôć¬UPL<s<íXδβ©såXô2Fø0δ.ø}2Fø€ü3}OOJJ'*®ǝ0'x:Xô»

```

Try it online or verify both test cases.

**Explanation:**

05AB1E lacks multi-dimensional index builtins and uses 0-based indexing, so we mostly work with the flattened list and lower all indices by 1 (before converting it back to a matrix to calculate the amount of surrounding mines per cell).

```
#              # Split the (implicit) input-string on spaces
 2ô            # Split it into parts of size 2
   ć           # Extract head; pop and push remainder-list and first pair
    ¬          # Get the first item of this first pair (without popping)
     U         # Pop and store it in variable `X`
    P          # Take the product of this first pair
     L<        # Pop and push a list in the range [0,value)
    s          # Swap so the list of pairs is at the top again
     <         # Decrease each inner value by 1 to make things 0-based
      í        # Reverse each inner pair, to reverse column,row to row,column
        δ      # Map over each reversed and lowered pair:
       X β     #  Convert it from base-`X` to an integer,
               # (which are all flattened 0-based indices of the mines)
          ©    # Store this list in variable `®` (without popping)
           s   # Swap so the [0,value)-ranged list is at the top
            å  # Check for each value whether its in the indices-list,
               # resulting in a list of 0s and 1s, with 1s at the mine-positions
Xô             # Split it into `X`-sized parts to a matrix
  2Fø0δ.ø}     # Add a border of 0s around the matrix:
  2F     }     #  Loop 2 times:
    ø          #   Zip/transpose; swapping rows/columns
      δ        #   Map over each inner list:
     0 .ø      #    Surround it with a leading/trailing 0
  2Fø€ü3}      # Convert it to a matrix of overlapping 3x3 blocks:
  2F    }      #  Loop 2 times again:
    ø          #   Zip/transpose; swapping rows/columns
     €         #   Map over each inner list:
      ü3       #    Convert it to a list of overlapping triplets
  OO           # Sum each inner 3x3 block
    JJ         # Join all these digits together to a single string
      '*®ǝ    '# Replace the digit at the `®`-indices with "*"s
      0'x:    '# Replace all 0s with "x"s
      Xô       # Split it into `X`-sized parts again to a list of rows
        »      # Join it by newlines
               # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Vyxal, 42 bytes

```
⌈⌊2ẇḣ$2+Þm$R(n1ÞȦ)2(3vl∩)ƛƛf4ǔṫß×∑\x$∨}vṅ⁋

```

Try it Online! (would be 28ish with looser I/O)

```
⌈⌊                                         # Parse integers from input
  2ẇ                                       # Group into pairs
    ḣ                                      # Remove the first pair (dimensions)
     $2+                                   # Add 2 to each
        Þm                                 # Create a matrix of 0s with those dimensions
          $R(    )                         # Over each remaining coordinate pair (with x and y swapped)
               ÞȦ                          # Place in the matrix
              1                            # A 1
             n                             # At those coordinates
                  2(    )                  # Twice
                    3vl                    # Get all sliding windows of length 3 of each
                       ∩                   # Transpose
                         ƛƛ           }
                           f               # Flatten into a 9-element array
                            4ǔ             # Rotate so the centre (current cell) is at the end
                              ṫ            # Extract the last element (current cell)
                               ß×          # If that is truthy, push a mine
                                 ∑         # Sum to get number of nearby mines
                                  \x$∨     # If 0, replace with x
                                       vṅ⁋ # Concatenate each and join by newlines

```
> 3 votes

# Answer
# Mathematica - 247 chars

```
s[q_] :=
  Module[{d, r},
    d = ToExpression@Partition[Cases[Characters@q, Except@" "], 2];
    r = Rest@d;
    StringJoin @@@
    ReplacePart[
    Table[ToString@
       Count[ChessboardDistance[{i, j}, #] & /@ Reverse /@ r, 1], {i,d[[1, 2]]},
       {j, d[[1, 1]]}] /. {"0" -> "x"}, # -> "*" & /@ Reverse /@ r] // TableForm]

```

Examples:

```
s@"5 5 1 3 3 5 2 4"
s@"3 4 3 1 1 4 2 3 3 2"

```

Output:

`ChessboardDistance` computes how far each cell is from a mine, where 1 corresponds to "next to a mine". The `Count` of 1's yields the cell's number. Then mines (\*) are inserted into array.
> 2 votes

# Answer
## *Mathematica*, ~~140~~ ~~139~~ 137

```
Grid[(ListConvolve[BoxMatrix@1,#,2,0]/. 0->x)(1-#)/. 0->"*"]&@Transpose@SparseArray[{##2}->1,#]&@@#~Partition~2&@@#~ImportString~"Table"&

```

Writing that in a more readable form:

```
"5 5 1 3 3 5 2 4"

ImportString[%, "Table"][[1]] ~Partition~ 2

Transpose @ SparseArray[{##2} -> 1, #]& @@ %

ListConvolve[BoxMatrix@1, %, 2, 0]

(% /. 0 -> x) (1 - %%) /. 0 -> "*" // Grid

```
> 2 votes

# Answer
# Vyxal 3 `j`, 37 bytes

```
2ẆVḤ\ðYY$v•ÞẠ:Þȯᵛƛ•C]ZᵗZᵛᵛ₳•c[•]0'xr“

```

Try it Online! -12 from Using reduce lambdas on zipped list instead of the weird index method. -1 because i didnt need a map lambda at the end
> 2 votes

# Answer
## Python, 192 182 180 chars

I could save some if the input was comma-separated. Then the first line would be `d=input()` and the length 171 chars.
Having the mine coordinates 0-based rather than 1-based would also help. It cost me 8 chars to overcome.

```
d=map(int,raw_input().split())
m=zip(d[2::2],d[3::2])
for y in range(d[1]):print"".join((str(sum(abs(a-x-1)|abs(b-y-1)<2for a,b in m)or'x')+'*')[(x+1,y+1)in m]for x in range(d[0]))

```

Ungolfed version:

```
d=map(int,raw_input().split())          # Read whitespace terminated numbers into a list of numbers
xsize,ysize = d[:2]                     # The first two numbers are the board size
mines=zip(d[2::2],d[3::2])              # Convert items 3,4,5,6... to pairs (3,4),(5,6) representine mine coordinates

def dist(point,mine):                   # Distance between point (0-based coordinates) and mine (1-based coordinates)
    dx = abs(mine[0]-(point[0]+1))
    dy = abs(mine[1]-(point[1]+1))
    return dx | dy                      # Should be max(dx,dy), but this is close enough. Wrong for d>=2, but returns >=2 in this case.

for y in range(ysize):                  # Print lines one by one
    line_chars = [
        (str(
            sum(dist((x,y),(a,b))<2 for a,b in mines)   # Number of neighboring mines
            or 'x'                                  # 'x' instead of 0
        )
        +'*')                                       # For a single neighbor, we get "1*"
        [(x+1,y+1)in mines]                         # If a mine, get the '*', else the neighbor number
        for x in range(xsize)
    ]
    print "".join(line_chars)

```
> 1 votes

# Answer
# Scala, 280 chars

```
val n=readLine split" "map{_.toInt}
val b=Array.fill(n(1),n(0))(0)
n drop 2 sliding(2,2)foreach{case Array(x,y)=>b(y-1)(x-1)=9
for{i<-(x-2 max 0)to(x min n(0)-1);j<-(y-2 max 0)to(y min n(1)-1)}b(j)(i)+=1}
b.map{r=>println(r.map{case 0=>"x"case x if x>8=>"*"case x=>""+x}mkString)}

```
> 1 votes

# Answer
# Haskell, 155 bytes

```
main=interact$f.map read.words
f(x:y:a)=unlines[["x12345678*"!!min((i,j)#a)9|i<-[1..x]]|j<-[1..y]]
p@(a,b)#(x:y:z)=div 9(9^max(abs$a-x)(abs$b-y))+p#z
_#_=0

```

Try it online!
> 1 votes

# Answer
## C++ - 454 chars

This is worse than my VBA answer, which probably means I don't know what I'm doing in C++. However, I am trying to build on what I know of C++, so here it is. If anyone has any suggestions for improvement, I'd be grateful to hear them!

```
#define Z for(int i=
#define Y for(int j=
#define X d[i][j]
#define W Z 0;i<x;i++){
#define V Y 0;j<y;j++){
#define U cout<<
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int main(){using namespace std;int x,y,a,b;cin>>y>>x;string c[x][y];int d[x][y];W V X=0;}}while(cin>>b>>a){c[--a][--b]="*";Z a-1;i<=a+1;i++){Y b-1;j<=b+1;j++){if(x>i&&i>=0&&y>j&&j>=0){X=X+1;}}}}W V if(c[i][j]!="*"){if(X>0){U X;}else{U"x";}}else{U"*";}}U endl;}return 0;}

```
> 0 votes

# Answer
**C# (691 Chars)**

```
using System;namespace M{class P{static char C(char[][] g,int r,int c){int n=0;for(int i=r-1;i<=r+1;i++){if(i<0||i>=g.Length)continue;for(int j=c-1;j<=c+1;j++){if((j<0||j>=g[0].Length)||(i==r&&j==c))continue;if(g[i][j]=='*')n++;}}return n==0?'x':(char)(n+48);}static char[][] G(int[] p){char[][] r=new char[p[1]][];for(int i=0;i<r.Length;i++)r[i]=new char[p[0]];for(int i=2;i<p.Length;){r[p[i+1]-1][p[i]-1]='*';i+=2;}for(int i=0;i<r.Length;i++)for(int j=0; j<r[0].Length;j++)if(r[i][j]!='*')r[i][j]=C(r,i,j);for(int i=0;i<r.Length;i++){for(int j=0;j<r[0].Length;j++)Console.Write(r[i][j]);Console.WriteLine();}return r;}static void Main(string[] args){G(new int[]{3,4,3,1,1,4,2,3,3,2});}}}

```

Non-golfed Version:

```
using System;
namespace M
{
    class P
    {
        static char C(char[][] g, int r, int c)
        {
            int n = 0;
            for (int i = r - 1; i <= r + 1; i++)
            {
                if (i < 0 || i >= g.Length) continue;
                for (int j = c - 1; j <= c + 1; j++)
                {
                    if ((j < 0 || j >= g[0].Length) || (i == r && j == c)) continue;
                    if (g[i][j] == '*') n++;
                }
            }
            return n == 0 ? 'x' : (char)(n + 48);
        }

        static char[][] G(int[] p)
        {
            char[][] r = new char[p[1]][];
            for (int i = 0; i < r.Length; i++)
                r[i] = new char[p[0]];
            for (int i = 2; i < p.Length; )
            {
                r[p[i + 1] - 1][p[i] - 1] = '*';
                i += 2;
            }
            for (int i = 0; i < r.Length; i++)
                for (int j = 0; j < r[0].Length; j++)
                    if (r[i][j] != '*') r[i][j] = C(r, i, j);
            for (int i = 0; i < r.Length; i++)
            {
                for (int j = 0; j < r[0].Length; j++)
                    Console.Write(r[i][j]);
                Console.WriteLine();
            } return r;
        }
        static void Main(string[] args)
        {
            G(new int[] { 3, 4, 3, 1, 1, 4, 2, 3, 3, 2 });
        }
    }
}

```
> 0 votes

# Answer
# K, 175

```
f:{g::(y;x)#(x*y)#"x";{.[`g;x;:;"*"]}@'-1+|:'(_(#z)%2;2)#z;{if[~"0"~z;$["x"=g .(x;y);.[`g;(x;y);:;z];]]}.'i,'$s:+/'{"*"=g . x}''{,/((x-1)+!3),\:/:(y-1)+!3}.'i:,/(!x),\:/:!y;g}

```

.

```
k)f[5;5;1 3 3 5 2 4]
"xxxxx"
"11xxx"
"*21xx"
"2*21x"
"12*1x"
k)f[3;4;3 1 1 4 2 3 3 2]
"x2*"
"13*"
"2*2"
"*21"

```
> 0 votes

# Answer
**ECMAScript 2019 (Modern Javascript) - 116 bytes**

```
m.map((r,i)=>r.map((c,j)=>c=='X'?c:[,...m].splice(i,3).map(r=>[,...r].splice(j,3)).flat().filter(v=>v=='X').length))

```

**ungolfed version**

```
m.map(
  (r,i) => r.map(
    (c,j) => c=='X' ? c :
      [,...m].splice(i,3).map(r=>[,...r].splice(j,3)).flat().filter(v=>v=='X').length
  )
)

```

*this solution doesn't strictly adhere to the input/output format but demonstrates a succinct algorithm.*

example: https://gist.github.com/missinglink/ee02084cfb523665e8c9d34c24f01537
> -1 votes

---
Tags: code-golf, minesweeper
---


title: Find the follow sets

text:
# Question
Title: Find the follow sets
**The challenge below requires you to be familiar with formal parser theory.** If you don't know what the question is asking because you don't know what the terms mean, context-free grammars and first/follow sets are covered in a lot of university courses.

I can recommend this Stanford course, in particular handouts 08 and 09 (from page 7). I've extracted also extracted a cheat sheet from these handouts - *I recommend anyone attempting this challenge to read it*.

---

Write a program or function that given a context-free grammar finds the follow set of every nonterminal. Informally, the follow set of a nonterminal is a set of terminals and `$` (meaning end-of-input) that you can possibly find after that terminal in a valid sentence.

The input is given as a single printable ASCII string or array of printable ASCII lines. You may output the sets in any reasonable format, using `$` (either as literal output, or string inside a set, etc) to indicate the end of input. **You may assume that the input is always valid according to the format below.**

The context free grammar is given in a very simplified manner. Every line contains a single production. Every production is a space separated list of symbols. A terminal is a string of characters surrounded by apostrophes (e.g. `'**'`). For simplicity you may assume that terminals do not contain spaces, but it would be nice if your program allows it. A nonterminal may be any string not containing spaces or `$`. The empty production (normally indicated with ε) is simply a line containing only the left hand side nonterminal. The first line is the production defining the start symbol.

As an example, the following grammar:

S → aSa | bSb | ε

Will be given as:

```
S 'a' S 'a'
S 'b' S 'b'
S

```

---

Example input / outputs:

```
In:
S 'a' S 'a'
S 'b' S 'b'
S

Out:
S {'a', 'b', $}

In:
S A B C
A 'a'
A C 'b'
A
B C
B 'd' A
B
C 'e'
C 'f'

Out:
S {$}
A {'d', 'e', 'f'}
B {'e', 'f'}
C {'b', 'e', 'f', $}

In:
Start Alice Bob
Alice Charlie 'a'
Alice
Bob Bob 'a' Alice Charlie
Bob '!!!'
Charlie 'b'
Charlie

Out:
Start {$}
Alice {'a', '!!!', 'b', $}
Bob {'a', $}
Charlie {'a', $}

```

---

Shortest code in bytes wins.

# Answer
# Perl, 257 bytes

Includes +4 for `-0p`

Give grammar on STDIN (without trailing spaces. Make sure to remove the extra space in the second example). Assumes non-terminal names only contain letters, digits and `_`. Uses `#` instead of `$` to indicate end of input. Can handle literals containing spaces

```
perl -M5.010 follow.pl
E T e
e '+' T e
e
T F t
t '*' F t
t
F '(' E ')'
F 'id'
^D

```

Outputs the follow sets as a list of `non-terminal literal` in no particular order. For the example above it outputs:

```
F ')'
F #
t ')'
t #
T ')'
T #
F '+'
t '+'
T '+'
F '*'
e ')'
e #
E ')'
E #

```

`follow.pl`:

```
#!/usr/bin/perl -0n
s/'.*?'/~$&/eg;s% (?=(\w.*\n))%$_.=">$1"%reg;/\s/;$_.=">$` #\n";s%^((\w+)\K ?\S*).*%$s{$1}++||"\$a.=s/ $2\\b/$&/rg"%eemgr,s%^(\w+ ).*?(\w+)$%"\$a.=s/>$1/>$2 /rg"%eermg,$_.=$a,s%>.*\xd8\K .*%%g,s%.+\n%$&x!/\n$&/g%eg until$$_++;s/\xd8.*?\xd8/~$&/eg;say/>(\w+ \W\S*\n)/g

```

Works as shown, but replace `\xd8` and `\n` by their literal versions to get the claimed score.

It should be possible to improve this since converting the `first` sets to the `follow` sets is currently very awkward.
> 3 votes

# Answer
# Python3, 271 bytes

```
def f(g):
 d={g[0][0]:{''}}
 q=[(i[1:],[])for i in g]
 for a,S in q:
  for i,A in enumerate(a):
   if A and"'"!=A[0]:
    if a[i+1:]and"'"==a[i+1][0]:d[A]={*d.get(A,[]),a[i+1],''}
    for j,*k in g:
     if j==A and(j,k)not in S:q+=[(a[:i]+k+a[i+1:],S+[(j,k)])]
 return d

```

Try it online!
> 0 votes

---
Tags: code-golf, grammars
---