# Question
Title: Monday Mini-Golf #4: JARVIS (Just Another Rather Vast set of Integer Sequences)
**Monday Mini-Golf:** A series of short questions, posted (hopefully!) every Monday.
(Sorry I'm late again; I was away from my computer basically all of yesterday and today.)

Us programmers (especially the code-golfers) sure love arbitrary integer sequences. We even have an entire site dedicated to these sequences that currently has around 200,000 entries. In this challenge, we'll be implementing yet another set of these sequences.

# Challenge

Your challenge is to write a program or function that takes in an integer *N*, and outputs a sequence of base 10 integers, where each next integer is determined in this way:

* Start at 1.
* For each digit *D* in the previous integer's base 10 representation:

+ If *D* is 0, add one to the current integer.
    + Otherwise, multiply the current integer by *D*.

## Details

* You may assume that 0 \< *N* \< 231.
* You must output each integer in the sequence, starting with the input number, until a number less than 10 is reached.
* The output may be an array, or a string separated by spaces, commas, newlines, or a combination of these.
* A trailing space and/or newline is allowed, but *not* a trailing comma.
* There should never be any leading zeroes.

# Examples

**Example 1:** `77`

This example is fairly straightforward:

```
77 = 1*7*7 = 49
49 = 1*4*9 = 36
36 = 1*3*6 = 18
18 = 1*1*8 = 8

```

Thus, the proper output is `77 49 36 18 8`.

**Example 2:** `90`

Here we have:

```
90 = 1*9+1 = 10
10 = 1*1+1 = 2

```

So the output would be `90 10 2`.

**Example 3:** `806`

Read the equations left-to-right:

```
806 = 1*8+1*6 = 54 (((1*8)+1)*6)
 54 = 1*5*4   = 20
 20 = 1*2+1   = 3

```

Output should be `806 54 20 3`.

# Test-cases

The first number in each line is the input, and the full line is the expected output.

```
77 49 36 18 8
90 10 2
249 72 14 4
806 54 20 3
1337 63 18 8
9999 6561 180 9
10000 5
8675309 45369 3240 25 10 2
9999999 4782969 217728 1568 240 9
1234567890 362881 2304 28 16 6

```

As a reference, here's the proper next integers from 10 to 100:

```
Current | Next
--------+-----
     10 |  2
     11 |  1
     12 |  2
     13 |  3
     14 |  4
     15 |  5
     16 |  6
     17 |  7
     18 |  8
     19 |  9
     20 |  3
     21 |  2
     22 |  4
     23 |  6
     24 |  8
     25 | 10
     26 | 12
     27 | 14
     28 | 16
     29 | 18
     30 |  4
     31 |  3
     32 |  6
     33 |  9
     34 | 12
     35 | 15
     36 | 18
     37 | 21
     38 | 24
     39 | 27
     40 |  5
     41 |  4
     42 |  8
     43 | 12
     44 | 16
     45 | 20
     46 | 24
     47 | 28
     48 | 32
     49 | 36
     50 |  6
     51 |  5
     52 | 10
     53 | 15
     54 | 20
     55 | 25
     56 | 30
     57 | 35
     58 | 40
     59 | 45
     60 |  7
     61 |  6
     62 | 12
     63 | 18
     64 | 24
     65 | 30
     66 | 36
     67 | 42
     68 | 48
     69 | 54
     70 |  8
     71 |  7
     72 | 14
     73 | 21
     74 | 28
     75 | 35
     76 | 42
     77 | 49
     78 | 56
     79 | 63
     80 |  9
     81 |  8
     82 | 16
     83 | 24
     84 | 32
     85 | 40
     86 | 48
     87 | 56
     88 | 64
     89 | 72
     90 | 10
     91 |  9
     92 | 18
     93 | 27
     94 | 36
     95 | 45
     96 | 54
     97 | 63
     98 | 72
     99 | 81
    100 |  3

```

You can find this list expanded to 10000 here.

# Scoring

This is , so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 19. Good luck!~~

**Edit:** Congrats to your winner, **@isaacg**, using Pyth yet again for **14 bytes**!

# Answer
# Pyth, ~~15~~ 14 bytes

```
.uu|*GHhGjNT1Q

```

*1 byte thanks to Dennis*

Test Suite

This challenge feels like it was made for Pyth's reduce functions. One reduce over the digits, one reduce until the value stops changing, and we're good.
> 10 votes

# Answer
# PowerShell, ~~92~~ ~~91~~ ~~90~~ ~~88~~ 87 bytes

```
($n=$args);while($n-gt9){$x=1;[char[]]"$n"|%{$x=if($y=$_-48){$x*$y}else{$x+1}};($n=$x)}

```
> 4 votes

# Answer
# CJam, ~~26~~ ~~25~~ ~~24~~ 22 bytes

```
riA,{_pAb{_2$*@)?}*j}j

```

or

```
ri{_pAb{_2$*@)?}*_9>}g

```

Try it online.

### How it works

Both program essentially do the same; the first is a recursive approach, the second an iterative one. I'll explain the first, which I consider more interesting.

```
ri                     Read an integer from STDIN and push it on the stack.
  A,{               }j Initialize a memoized, recursive function j with the array
                       [0 ... 9] as "base cases". If j is called on an integer
                       below 10, it returns the element at that index of the base
                       cases (which is same integer) and does not execute the code
                       block. The base case array is filled with new values as j is
                       called again and again, but we do not use this feature.
     _p                Copy and print the integer on the stack.
       Ab              Convert it into its base-10 digits.
         {       }*    Fold; push the first digit, for each remaining digit:
          _2$*         Multiply copies of the accumulator and the current digit.
              @)       Increment the original accumulator.
                ?      Select the product if the digit is non-zero, else the sum.
                   j   Call j on the result.
                       If the result was less than 10, it is retrieved from the
                       base cases and pushed on the stack. CJam prints it before
                       exiting the program.

```
> 3 votes

# Answer
# Pip, ~~28~~ ~~25~~ 23 bytes

```
Tt>Pa{Y1FdaYy*d|y+1a:y}

```

Takes a number as command-line argument and outputs the sequence on successive lines.

Explanation:

```
                         a is cmdline arg; t is 10 (implicit)
Tt>Pa{                }  Loop till a<10, printing it each time the test is made:
      Y1                   Yank 1 into variable y
        Fda                For each digit d in a:
           Yy*d|y+1          If y*d is truthy (nonzero), yank it; otherwise, yank y+1
                   a:y     Assign value of y back to a

```

Now I'm glad I changed `P` from a statement to an operator several revisions ago. `Pa` is an expression that evaluates to `a`'s value but also outputs it, so I can print `a` and simultaneously test whether it's less than ten using `t>Pa`.
> 3 votes

# Answer
## Minkolang 0.7, ~~52~~ 46 bytes

```
ndN((d25*%1R25*:)r11(x2~gd4&x1+!*I1-)dNd9`,?).

```

Woohoo nested loops!

### Explanation

```
ndN     Takes integer input and outputs it
(       Starts overall loop

 (        Starts loop that separates top of stack into digits
  d25*%   Modulus by 10
  1R      Rotates stack 1 unit to the right
  25*:    Divides by 10
 )

 r11   Reverses stack and pushes two 1s; 1 for the dump and 1 for the multiply
 (     Starts the multiply/add loop
  x    Dumps top value

      -This top-of-stack dump is because
       while loops end when the stack is
       empty or the top of stack is 0. The
       top of stack is *not* popped for
       this conditional check, so if the loop
       continues, I need to dump the left-over
       from the previous iteration.

  2~gd    Gets next-to-last stack value and duplicates for the conditional
  4&      Jumps 4 spaces if top of stack is positive
   x1+!   Dumps the 0 leftover, adds 1 to top of stack, and jumps the multiply
   *      Multiplies the top two elements of stack
  I1-     Pushes length of stack - 1
 )        Exits the loop if top of stack is 0 (i.e., len(stack)=1)
 dN       Outputs as integer
 d9`,?    Jumps out of the loop if top of stack <=9
)
.    Stop.

```
> 2 votes

# Answer
## Python, ~~85~~ 80 bytes

```
def g(n):y=reduce(lambda i,x:i*int(x)or i+1,`n`,1);return[n]+(g(y)if n>9else[])

```

This now properly prints out the entire list, instead of just the first value.
> 2 votes

# Answer
# Mathematica, 66 bytes

```
Most@FixedPointList[Fold[If[#2<1,#+1,1##]&,1,IntegerDigits@#]&,#]&

```
> 2 votes

# Answer
# Python 3, 74, ~~76~~ bytes

There was already a Python answer here with reduce, so I wanted to do one without it. It should be called with an int.

```
def j(n,m=1):
 print(n)
 if n>9:
  for d in str(n):m=m*int(d)or m+1
  j(m)

```
> 2 votes

# Answer
# Julia, ~~93~~ ~~89~~ ~~88~~ ~~86~~ ~~83~~ 77 bytes

```
f(n)=(println(n);if(d=n>9)for i=reverse(digits(n)) i<1?d+=1:d*=i end;f(d)end)

```

This creates a recursive function `f` that prints the sequence elements on separate lines.

Ungolfed:

```
function f(n::Int)
    println(n)
    if (d = n > 9)
        for i in reverse(digits(n))
            i < 1 ? d += 1 : d *= i
        end
        f(d)
    end
end

```

Try it online

Saved 6 bytes thanks to Dennis!
> 1 votes

# Answer
# K5, 24 bytes

```
(1{(x*y;x+1)@~y}/.:'$:)\

```

Gathering a list of items while iterating to a fixed point is precisely what the scan operator `\` does. On each iteration I first cast the number to a string and then evaluate each character (`.:'$:`), exploding the number into its digits. Then I perform a reduction (`/`) starting with 1 and using the lambda `{(x*y;x+1)@~y}`. In this case `x` is the reducing value and `y` is each successive term of the sequence.

In action:

```
  f: (1{(x*y;x+1)@~y}/.:'$:)\

  f'77 90 249 806 1337 9999 10000 8685309 9999999 1234567890
(77 49 36 18 8
 90 10 2
 249 72 14 4
 806 54 20 3
 1337 63 18 8
 9999 6561 180 9
 10000 5
 8685309 51849 1440 17 7
 9999999 4782969 217728 1568 240 9
 1234567890 362881 2304 28 16 6)

```
> 1 votes

# Answer
# Ruby 83, 72 bytes

**Original** declared as a function:

```
def f(d)loop{p d;break if d<10;d=d.to_s.bytes.inject(1){|r,i|i>48?r*(i-48):r+1}}end

```

I tried to use `Enumerator.new` but it uses so many bytes :-(

**Improved** using recursion:

```
def f(d)p d;f(d.to_s.bytes.inject(1){|r,i|i>48?r*(i-48):r+1})if d>10 end

```
> 1 votes

# Answer
## C# & LINQ, 165 146 bytes

```
void j(int a){r.Add(a);var l=a.ToString().Select(d=>int.Parse(d.ToString()));int n=1;foreach(int i in l)n=i==0?n+1:n*i;if(n>9)j(n);else r.Add(n);}

```

**j** (for jarvis) is the recursive function. **r** is the List of int of the result.

tested in LINQPAD:

```
void Main()
{
    j(806);
    r.Dump();
}
List<int> r = new List<int>();

void j(int a){r.Add(a);var l=a.ToString().Select(d=>int.Parse(d.ToString()));int n=1;foreach(int i in l)n=i==0?n+1:n*i;if(n>9)j(n);else r.Add(n);}

```
> 0 votes

# Answer
# Haskell, 71 bytes

```
x!'0'=x+1
x!c=x*read[c]
g x|h>9=x:g h|1<2=[x,h]where h=foldl(!)1$show x

```

Usage: `g 8675309` -\> `[8675309,45369,3240,25,10,2]`.
> 0 votes

# Answer
# Matlab, 108

```
N=input('');disp(N)
k=1;while k
x=1;for n=num2str(N)-48
if n
x=x*n;else
x=x+1;end
end
disp(x)
N=x;k=x>9;
end

```
> 0 votes

# Answer
# Java 8, 148 Bytes

```
String f(int j){String s="";Function r=i->(""+i).chars().map(x->x-48).reduce(1,(x,y)->y>0?x*y:x+1);while((j=(int)r.apply(j))>9)s+=j+" ";return s+j;}

```

formatted

```
String f(int j) {
    String s = "";
    Function r = i -> ("" + i).chars().map(x -> x - 48).reduce(1, (x, y) -> y>0 ? x*y : x+1);
    while ((j = (int)r.apply(j)) > 9) s += j+" ";
    return s+j;
}

```
> 0 votes

# Answer
# Jelly, 9 bytes

```
D×‘ṛ?ƒ1ƊƬ

```

Try it online!
> 0 votes

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


title: Find equally-weighted complete graphs

text:
# Question
Title: Find equally-weighted complete graphs
Graph theory is used to study the relations between objects. A graph is composed of vertices and edges in a diagram such as this:

```
A-----B
|    / \
|   /   \
|  /     E
| /     /
|/     /
C-----D

```

In the above diagram, `A` is linked to `B` and `C`; `B` is linked to `A`, `C`, and `E`; `C` is linked to `A`, `B`, and `D`; `D` is linked to `C` and `E`; and `E` is linked to `B` and `D`. As that description was rather wordy, a graph can be represented as a symmetric boolean matrix where a 1 represents a connection and a 0 represents the lack thereof. The above matrix is translated to this:

```
01100
10101
11010
00101
01010

```

For the purpose of this problem, the matrix definition can be extended to include the distances or weights of the paths between nodes. If individual ASCII characters in the diagram have weight 1, he matrix would be:

```
05500
50502
55050
00502
02020

```

A "complete graph" consists of a set of points such that each point is linked to every other point. The above graph is incomplete because it lacks connections from `A` to `D` and `E`, `B` to `D`, and `C` to `E`. However, the subgraph between `A`, `B`, and `C` is complete (and equally weighted). A 4-complete graph would look like this:

```
A---B
|\ /|
| X |
|/ \|
C---D

```

and would be represented by the matrix:

```
01111
10111
11011
11101
11110

```

This problem is as follows: **Given a symmetric matrix representing a graph and a positive integer `n`, find the number of distinct equally-weighted complete subgraphs of size `n` contained within**.

You may assume that the input matrix is numeric and symmetric, and may choose input/output format. An entry in the matrix may be part of multiple equally-weighted subgraphs as long as they are distinct and of equal size. You may assume that `n` is a positive integer greater than or equal to 3.

The winning criterion for this challenge is **code golf**. Standard rules apply.

# Answer
# Jelly,  ~~18 16~~  15 bytes

Assumes self-connections may be any weight (i.e. they are not necessarily only either \\$0\\$ or the equal weight).

```
Jœcṗ2EÐḟœị³EƲ€S

```

**Try it online!**
the two subsets of size 3 being ACE and BCD
With n=2 all 10 subsets of size 2 work as its symmetric.

### How?

```
Jœcṗ2EÐḟœị³EƲ€S - Link: list of lists of integers, M; integer, n
J               - range of length of M = [1,2,3,...,length(M)]
 œc             - Combinations of length n e.g. [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
             €  - for each:
            Ʋ   -   last four links as a monad:
   ṗ2           -     Cartesian power with 2
      Ðḟ        -     discard if:
     E          -       all-equal (i.e. diagonal co-ordinates like [3,3])
        œị      -     multi-dimensional index into:
          ³     -       program's 3rd argument (1st input), M
           E    -     all equal?
              S - sum

```
> 1 votes

# Answer
# Jelly, 16 bytes

```
ịⱮịŒDḊẎE
Jœcç€⁸S

```

Try it online!
> 1 votes

# Answer
# Python 2, 195 bytes 178 bytes 168 bytes

I'm sure there's a lot more golfing possible here, but for a change I want to get an entry in before there are dozens of other ones. I've provided a couple of test cases on TIO, but would love more examples.

First round of suggested golf steps: Remove some spaces, be smarter about the import. Shorter way of testing if the single link value in a set is zero (Thanks to M. XCoder).

Second round: ElPedro points out that in this case a program is shorter than the function. I was hoping to find a way to package this as a lambda, so was thinking "function" from the start. Thanks.

```
from itertools import*
r=set()
M,n=input()
for g in set(combinations(range(len(M)),n)):
 s={M[i][j]for i in g for j in g if i>j}
 if len(s)==1and{0}!=s:r.add(g)
print r

```

Try it online!

A slightly ungolfed version, to clarify logic:

```
from itertools import combinations
def f3(M,n):
  r = set()
  groups = set(combinations(range(len(M)), n)) # all possible combinations of indexes
  for group in groups:
      # Generate a set of link values associated with the current combination
      # This selects only non-diagonal indexes, assuming matrix symmetry.
      s = {M[i][j]for i in group for j in group if i>j}
      # If the set has only one member, and that's not zero, you have
      # a connected subgraph.
      if len(s) == 1 and 0 not in s:
          r.add(group)
  return r

```
> 1 votes

# Answer
# Clean, 152 bytes

```
import StdEnv,Data.List
$m n=sum[1\\i<-subsequences[0..size m-1]|length i==n,j<-permutations i|case[m.[x,y]\\x<-i&y<-j]of[u:v]=all((==)u)v&&u>0;_=1<0]/2

```

Try it online!

TIO driver takes `n` as a command-line argument and the matrix through STDIN (weights up to 9).

The actual function `$ :: {#{#Int}} Int -> Int` works with any size weights.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 90 bytes

There is probably some room to further golf this, after some test cases are posted.

We construct a graph from the unitized adjacency matrix, and then use the `FindClique` function with `All` as the third argument to list out the vertices with complete subgraphs. We then select the submatrices of the original input corresponding to the cliques (which will have zeros along the diagonal) and count the number of distinct elements which should be 2 if the weights are equal.

In this implementation, self connections can have a weight other than zero and the graph will still be considered complete and equal weighted, so long as the weights of all self connections in the subgraph are identical.

```
Count[Length@*Union@@@(b[[#,#]]&/@FindClique[AdjacencyGraph[Unitize/@(b=#)],{#2},All]),2]&

```

Try it online!
> 0 votes

---
Tags: code-golf, matrix, graph-theory
---


# Question
Title: Monday Mini-Golf #6: Meeesesessess upp teeexexextext
**Monday Mini-Golf:** A series of short challenges, posted (hopefully!) every Monday.

True story1: The other day, I was playing around on my tablet when I had the idea to visit the page I normally use on my PC for testing JavaScript. After the page loaded, I entered this simple program:

```
alert("Hello!")

```

I then proceeded to press the Execute button, and was surprised when it told me that the code I had entered was invalid. I took a second look at the textbox and saw this:

```
alllelelerlerlertlert("Heeelelellellelloello!")

```

Wha??? That's not what I entered! So what happened here? To figure it out, I entered two simple lines:

```
abcdefg
0123456

```

This turned out as:

```
abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefg
0112123123412345123456

```

By now, I still had no clue about what happened to letters, but the numbers seemed simpler, so I took a closer look. As it turned out, the webpage was simply entering the first character, then repeating all the rest in the string every time a new one was pressed:

```
0112123123412345123456
0
 1
  12
    123
       1234
           12345
                123456

```

But what about the sections of letters? After pondering for a minute, I realized that it's just the same, but instead of repeating each subsection once, it repeats it *twice*:

```
abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefg
a
 bb
   bcbc
       bcdbcd
             bcdebcde
                     bcdefbcdef
                               bcdefgbcdefg

```

A combination of the two works with a combination of these techniques:

```
abc123z
abbbcbcbc1bc12bc123bc123zbc123z
a
 bb
   bcbc
       bc1
          bc12
              bc123
                   bc123zbc123z

```

Whatever glitch causes this seems to reset at punctuation and spaces, so `abc def` becomes `abbbcbc deeefef`.

By this point, I was so absorbed in figuring it out and turning it into an interesting challenge that I forgot why I had been on there in the first place. (I did figure out how to type normally, however: pressing space-backspace after every character. Pretty tedious, but you gotta do what you gotta do.)

# Challenge

The goal of the challenge is to write a program or function that takes in the text to be processed, makes the changes listed above, and outputs/returns the result.

## Details

* The input will only contain printable ASCII, and no tabs or newlines.

# Test-cases

**Inputs:** (one per line)

```
Mess up text
This is some longer text.
CAPS LOCK && "Punc-tua"+'tion'
under_score_style
CaPs wItHIn loWERs
1337 numb3r5
abcdefghij 0123456789
Code-golf is the best!

```

**Outputs:**

```
Meeesesessess upp teeexexextext
Thhhihihishis iss sooomomomeome looononongongongeongeongeronger teeexexextext.
CAAAPAPAPSAPS LOOOCOCOCKOCK && "Puuunununcunc-tuuuaua"+'tiiioioionion'
unnndndndendendernder_scccococorcorcorecore_stttytytyltyltyletyle
CaaaPaPaPsaPs wIIItItItHItHItHIItHIItHInItHIn loooWoWoWEoWEoWERoWERoWERsoWERs
1333337 nuuumumumbumbumb3umb3rumb3rumb3r5
abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefgbcdefghbcdefghbcdefghibcdefghibcdefghijbcdefghij 0112123123412345123456123456712345678123456789
Cooodododeode-gooolololfolf iss thhhehe beeesesestest!

```

# Scoring

This is , so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Nov 2. Good luck!~~

**Edit:** And the winner is... **@MartinBüttner** using **Retina** for an incredible **43-byte** solution!

1 Yes, this story is completely true, and if you need any more clarification, see footnote 1.

# Answer
# Retina, 43 bytes

```
.(?<=[^_\W]([^_\W]+))(?<=(\1)(?<=\D))?
$1$2

```

Run the code from a single file with the `-s` flag. Since this is just a single regex substitution, you can test it here (click the Context tab to see the results).

## Explanation

This matches any digit and letter which is not the first in a run. While `.` can match any non-linefeed character, the lookbehinds ensure the other conditions:

```
(?<=[^_\W]([^_\W]+))

```

This matches *backwards* from the position after the `.`. First it matches one or more alphanumeric characters and captures them into group `1` with `([^_\W]+)`. This immediately ensures that the `.` corresponds to an alphanumeric character itself. Then the additional `[^_\W]` makes sure that there is one more alphanumeric character in the current run, which we *don't* include the match. Now group `1` is what we want to replace the match with if it is a digit - if it is a letter we want to replace it with twice this string. That's where the second lookbehind comes into play:

```
(?<=(\1)(?<=\D))?

```

This one is optional, so if it fails it won't affect the match at all. It first ensures that the `.` was *not* a digit via `(?<=\D)` \- so this lookbehind is only relevant when we're matching letters. In that case, we match group `\1` once more (this always matches, because we've captured the group from the same position), but capture it into group `2`.

Hence, we simply replace the regex with the contents of both groups (`$1$2`). If the match was a digit, `$2` will still be empty and we write back the prefix only once. If it was a letter, `$2` is the same as `$1` and we write it back twice.
> 13 votes

# Answer
# JavaScript(ES6) 82

Using the regexp optimization suggested by Mwr247

```
s=>s.replace(/([\W_])|./g,(x,y)=>y?(f=0,x):f?(p+=x,p+(-x-1?z:p)):(p=z,f=x),f=z='')

```

Test running the snippet below in any recent browser

```
F=s=>s.replace(/([\W_])|./g,(x,y)=>y?(f=0,x):f?(p+=x,p+(-x-1?z:p)):(p=z,f=x),f=z='')

// document.write(F(prompt('Insert string')))

// TEST
console.log=x=>O.innerHTML+=x+'\n'

function test()
{
  O.innerHTML=F(I.value)
}

;[
 ['Mess up text','Meeesesessess upp teeexexextext']
,['This is some longer text.',
  'Thhhihihishis iss sooomomomeome looononongongongeongeongeronger teeexexextext.']
,['CAPS LOCK && "Punc-tua"+\'tion\'',
  'CAAAPAPAPSAPS LOOOCOCOCKOCK && "Puuunununcunc-tuuuaua"+\'tiiioioionion\'']
,['CaPs wItHIn loWERs'
  ,'CaaaPaPaPsaPs wIIItItItHItHItHIItHIItHInItHIn loooWoWoWEoWEoWERoWERoWERsoWERs']
,['1337 numb3r5','1333337 nuuumumumbumbumb3umb3rumb3rumb3r5']
,['abcdefghij 0123456789'
 ,'abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefgbcdefghbcdefghbcdefghibcdefghibcdefghijbcdefghij 0112123123412345123456123456712345678123456789']
,['Code-golf is the best!'
  ,'Cooodododeode-gooolololfolf iss thhhehe beeesesestest!']
].forEach(t => (
  i=t[0],x=t[1],r=F(i),
  console.log('Test ' + (r==x?'OK':'Fail')+'\nInput:  '+i+'\nResult: '+r+'\nCheck:  '+x+'\n')
))
```

```
#I { width: 50% }
```

```
Your test<input id=I><button onclick="test()">-></button>
<pre id=O></pre>
```
> 8 votes

# Answer
# JavaScript (ES6), ~~92~~ ~~88~~ 87

```
f=>f.replace(/[^_\W]+/g,m=>m[0]+[...m].slice(1).reduce((a,e)=>a+=(y+=e,++e?y:y+y),y=''))

```

I have no idea how to golf this down...

*Thanks Mwir247 for the golfed down regex and ETHproductions for one byte golf in reduce function*.
> 5 votes

# Answer
# Haskell, ~~215~~ 200 bytes

```
import Data.List
import Data.Char
c=concatMap
p c=[isDigit c,isAlpha c]
r(Just n)=c id.replicate(n+1)
r _=id
f(h:t)=h:(c(\s->r(findIndex id.p$last s)s).tail.inits)t
m=c f.groupBy(\a b->or$p a==or$p b)

```

It's a mess.

Have fun reading all the weird quirks, I never thought I would use `id` this much.

Too bad the stuff that already does half the work here needs to be imported (`isDigit`,`isAlpha`,`inits`).
> 3 votes

# Answer
# Gema, 57 characters

```
\X?=?@set{s;}
<D1>=@append{s;$0}$s
<L1>=@append{s;$0}$s$s

```

Sample run:

```
bash-4.3$ gema '\X?=?@set{s;};<D1>=@append{s;$0}$s;<L1>=@append{s;$0}$s$s' <<< '1337 numb3r5'
1333337 nuuumumumbumbumb3umb3rumb3rumb3r5

```
> 3 votes

# Answer
# Haskell, ~~183~~ 181 bytes

```
import Data.Char
b(x:y)|h x=x:c[]y|2>1=x:b y
b[]=[]
h y=isDigit y||isAlpha y
c x l@(y:z)|h y=c(y:x)z|2>1=c x[]++b l
c x[]=reverse$g$x
g[]=[]
g a@(x:y)|isDigit x=a++g y|2>1=a++a++g y

```

Usage:

```
b"Hello, world!"
>"Heeelelellellelloello, wooorororlorlorldorld!"

```

Don't know if it is essentially different with Leif Willerts' answer. But here's the algorithm.

1. Search for valid letter(Letter or Num)
2. If it letter, begin collecting letter. However, it is stored reversely, make the string reversed. And first item is omitted.
3. As it hit invalid letter, do the question's transform with reversed input. The question's transform is reverse.g.reverse, but since it is already reversed, then we just do reverse.g

I somehow keep redudant brackets.
> 2 votes

# Answer
**T-SQL, 357 bytes**

```
create proc x(@s varchar(99),@z int=0,@i int=0,@y varchar(99)='',@x varchar(99)='',@w varchar(99)='') as

while LEN(@s)>0
begin
    select @z=patindex('%[^0-z]%',@s+' '),@i=1,@w+=LEFT(@s,1)
    while @i<@z-1
    begin
        select @y=SUBSTRING(@s,2,@i)
        ,@x+=@y
        ,@i+=1
        if @y like'%[a-z]'set @x+=@y
    end
select @w+=@x+SUBSTRING(@s,@z,1)
        ,@x=''
        ,@s=REPLACE(@s,left(@s,@z),'')
end

select @w

```

ex: `exec x(@s='1337 numb3r5')` returns `1333337 nuuumumumbumbumb3umb3rumb3rumb3r5`
> 0 votes

# Answer
# Python 2, 131 Bytes

```
i=raw_input();s=r='';g=1
for c in i:
 s+=c
 if g:r+=c;g=0;s=''
 elif c.isalpha():r+=s*2
 elif '/'<c<':':r+=s
 else:g=1;r+=c
print r

```

Loops through characters, and saves/repeats if required.
> 0 votes

# Answer
# Pip, 41 bytes

```
aR`[^_\W]+`{Y0a@0.Ya@{1,++y}X2-(_Q+_)MJa}

```

Takes the text as a command-line argument. We use a regex replacement to replace all alphanumeric runs (`[^_\W]+`) with a callback function. This function maps another function to each character of the word, generating progressively larger runs of characters (with the global variable `y` keeping track of the index) and repeating them X2 if the character is not a number. (The logic for which uses `+` to convert to a number and then `Q` to check whether this is string-equal to the original character.) This process leaves out the first character, though, so we have to add it on afterward (`a@0.`).
> 0 votes

# Answer
# Python 3, 86 bytes

```
f=0
m=''
for i in input():g=i.isalnum();m=m*g*f+i*f;print(end=m*-~i.isalpha()or i);f=g

```

Try it online!
> 0 votes

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


title: Shortest code for infinite disk I/O

text:
# Question
Title: Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

```
using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}

```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

# Answer
> 26 votes
## DOS/Batch: 4 bytes

```
%0>x

```

This batch file will call itself (`%0`) and redirect (`>`) the output to a file called `x`. Since echo is on by default, this will output the path and command.

# Answer
> 48 votes
## PowerShell v2+, 10 bytes

```
for(){1>1}

```

Simply loops infinitely with an empty `for` loop. Each iteration, we output the integer `1` (implicitly converted to a string) with the `>` redirect operator, which overwrites the file named `1` in the local directory.

# Answer
> 27 votes
# Pyth, 6 bytes

```
#.w]]0

```

Pyth's only file output command is `.w`. When called on a string, it writes that string to a file in append mode, which is no good for the purpose of this question. When called on a 2-d array, it writes the corresponding image to that file, overwriting the file contents. That's what this program does. The default file output name is `o.png`, so this program infinitely overwrites the file `o.png` with a 1-pixel white image. `#` is an infinite loop.

# Answer
> 26 votes
If you want a shorter (but more boring than my other one) answer:

# Bash, 5 bytes

```
>w;$0

```

I could make that shorter if there's a command (less than 3 bytes long) that writes something to disk I/O. Something like `sync` would work, but `sync` is 4 bytes

Note: this doesn't work when run straight from bash, only when put in a script and run as the script name. (i.e. `echo 'w>w;$0' > bomb; chmod 755 bomb; ./bomb`)

# Answer
> 16 votes
## Ruby, ~~22~~ 20 bytes

```
loop{open(?a,?w)<<1}

```

Repeatedly truncates and writes a `1` to the file `a`.

Thanks to Ventero for 2 bytes!

# Answer
> 13 votes
# cmd, 14 bytes

```
:a
cd>1
goto a

```

Infinitly overwrites the file `1` with the string to the current directory

---

I'm new here: Are *windows* new lines (`CR` `LF`) counted as two bytes?

# Answer
> 13 votes
# Bash + coreutils, 10

```
yes \>b|sh

```

Writes a continuous stream of `>b`, which is piped to `sh` for evaluation. `>b` simply truncates a file called `b` to zero bytes each time.

# Answer
> 9 votes
# Perl 5, ~~27~~ ~~32~~ 22 bytes

```
{{open my$h,'>o'}redo}

```

If simply changing the modification timestamp of a file suffices...

Quick explanation:

```
{ # Braces implicitly create/mark a loop.
    { # They also create closures, for `my` variables.
        open my $filehandle, '>', 'o';    # Writing to file "o".
        # close $filehandle;   # Called implicitly when
                               # variable gets destroyed.
    } # $filehandle gets destroyed because there are no references to it.
    redo; # ...the loop.
}

```

---

Previous solution (32 bytes): `{{open my$h,'>o';print$h 1}redo}`

**Edit:** `{open F,'O';print F 1;redo}` ← Didn't test the code before posting; now I had to correct it.

# Answer
> 8 votes
## PHP, ~~60 30 17 16~~ 15 bytes

Updated yet again as per @manatwork suggested:

```
while(!`cd>1`);

```

Also now tested.

---

A bit of cheating 22 bytes:

~~while(exec('\>1 dir'));~~

Earlier suggestion by @manatwork 30 bytes:

~~while(file\_put\_contents(1,1));~~

NOT TESTED (no php available on this computer) 43 bytes:

~~for($a=fopen(1,'w');fputs($a,1);fclose($a))~~

A golfed original 45 bytes:

~~$a=fopen(1,'w');while(fputs($a,1))rewind($a);~~

My first post here, joined because I just had to try this out: as long as file write succeeds, rewind file pointer to start.

---

~~Just can't get smaller than the file\_put\_contents().~~

# Answer
> 7 votes
# C, ~~95~~ ~~94~~ ~~93~~ ~~89~~ ~~78~~ ~~90~~ ~~89~~ ~~76~~ 75 bytes

```
#include<stdio.h>
main(){for(FILE*f=fopen("a","w");;fputc(0,f),fclose(f));}

```

Again, `sudo watch -n1 lsof -p `pidof inf``  seems to say this is valid.

HOW DID I NOT SEE THAT SPACE D:\<

Thanks @Jens for shaving off 13 bytes :D

# Answer
> 7 votes
# sh, 11 bytes

```
w>w;exec $0

```

Save this to a file without special characters, such as loop.sh, make it executable, and run it with `./loop.sh` or similar.

This writes the output of the command `w` to the file `w`, overwriting the previous value each time. Then, it replaces itself with a fresh version of the same program, so it can run infinitely.

# Answer
> 6 votes
# CPython 3.5, ~~33~~ 16 bytes

```
while 1:open("a")

```

Yes, really. :D

# Answer
> 6 votes
# Bash, 26 bytes

```
yes>y&while :;do rm y;done

```

If I were to expand this one-liner, I would get this:

```
yes > y &      # Write out infinitely to the file y in the current directory
while true     # Let's do something forever
do             # Here's what we're going to do
    rm y       # delete y
done           # That's all we're going to do

```

This can't exactly compete with the 10 byte PowerShell line, but it'll hold its own against the others. See my other answer for the 6 byte version.

# Answer
> 6 votes
# TI-BASIC, 12 bytes

```
While 1
Archive A
UnArchive A
End

```

Alternate solution by user lirtosiast with the same size:

```
While 1
SetUpEditor
Archive ∟1
End

```

This will work on the TI-83+ and TI-84+ series of calculators.

*Yes, this also works if A is already archived or is not initialized at all at the start of the program! The program is only 12 bytes because of tokenization*.

# Answer
> 5 votes
# MATL, 10 bytes

```
`1[]T3$Z#T

```

### Explanation

This is an infinite loop that writes number `1` to a file called `inout` in current directory, overwriting previous file's contents.

```
`       % do...while loop
  1     %   push number 1
  []    %   push empty array
  T     %   push "true"
  3$Z#  %   fwrite function. First input is file content. Second is file name;
        %   defaults to "inout" if empty. Third indicates that any previous
        %   file contents should be discarded
  T     %   push "true": loop condition
        % implicitly end loop. Loop condition is "true", so the loop is infinite

```

# Answer
> 5 votes
## Haskell, 20 bytes

```
f=writeFile"b""a">>f

```

Write the string `"a"` to a file named `"b"` and repeat. `writeFile` overwrites the file if it exists.

# Answer
> 4 votes
# ZSH, 14 bytes

```
for ((;;)) :>:

```

Zsh, unlike Bash and other Bourne-like shells, allows loops without the `do ... done` fence, provided the condition is suitably delimited.

Alternatively, with `while`:

```
while {} {:>:}

```

Note that `:` is a builtin. **You can't suspend this loop.**

The principle is the same as in Digital Trauma's answer \- nothing is written to the file, the IO is purely from creating and truncating the file.

# Answer
> 4 votes
## JavaScript (Node.js), ~~43~~ 41 bytes

```
(c=x=>require("fs").writeFile("a",x,c))()

```

Writes `null` to a file named `a`, then repeat.

# Answer
> 3 votes
# Rust, 84 Bytes

```
fn main(){loop{use std::io::Write;std::fs::File::create("a").unwrap().write(b"a");}}

```

`File::create` truncates an existing file, thus ensuring that we don't run out of disk space.

The used Compiler (1.9 Nightly) issues a warning about the unused result of `write(...)` but compiles nevertheless.

# Answer
> 3 votes
# C, 92 bytes

```
#include <stdio.h>
main(){for(FILE*f=fopen("a","w+");fprintf(f," "),!fclose(f);;);return 0;}

```

While it looks like you could save 1 byte by

```
  for(FILE*f=fopen("a","w+");fprintf(f," ")+fclose(f);;){}

```

the problem with that loop is that + doesn't give you the guaranteed order.

Or recursive - shouldn't overflow if the compiler properly implements tail recursion (f is in an explicit inner scope)

# 85 bytes

```
#include <stdio.h>
main(){{FILE*f=fopen("a","w+");fprintf(f," ");fclose(f);}main();}

```

# Answer
> 3 votes
# Mathematica, 14 bytes

```
For[,1>0,a>>a]

```

Repeatedly writes the string `"a"` to a file named `a` in the current directory, creating it if it doesn't exist.

# Answer
> 3 votes
## C, 40 bytes

```
main(){for(;;)write(open("a",1)," ",1);}

```

---

It will quickly run out of file descriptors, though; this can be overcome with:

## ~~45~~, 43 bytes

```
main(f){for(f=open("a",1);;)write(f,"",1);}

```

# Answer
> 3 votes
# C on amd64 Linux, 36 bytes (timestamp only), ~~52~~ 49 bytes (real disk activity)

I hard-code the `open(2)` flags, so this is not portable to other ABIs. Linux on other platforms likely uses the same `O_TRUNC`, etc., but other POSIX OSes may not.

**+4 bytes** to pass a correct permission arg to make sure the file is created with owner write access, see below. (This happens to work with gcc 5.2)

# somewhat-portable ANSI C, 38/51 bytes (timestamp only), 52/67 bytes (real disk activity)

Based on @Cat's answer, with a tip from @Jens.

The first number is for implementations where an `int` can hold `FILE *fopen()`'s return value, second number if we can't do that. On Linux, heap addresses happen to be in the low 32 bits of address space, so it works even without `-m32` or `-mx32`. (Declaring `void*fopen();` is shorter than `#include <stdio.h>`)

---

**Timestamp metadata I/O only**:

```
main(){for(;;)close(open("a",577));}   // Linux x86-64

//void*fopen();       // compile with -m32 or -mx32 or whatever, so an int holds a pointer.
main(){for(;;)fclose(fopen("a","w"));}

```

---

**Writing a byte, actually hitting the disk** on Linux 4.2.0 + XFS + `lazytime`:

```
main(){for(;write(open("a",577),"",1);close(3));}

```

`write` is the for-loop condition, which is fine since it always returns 1. `close` is the increment.

```
// semi-portable: storing a FILE* in an int.  Works on many systems
main(f){for(;f=fopen("a","w");fclose(f))fputc(0,f);}                 // 52 bytes

// Should be highly portable, except to systems that require prototypes for all functions.
void*f,*fopen();main(){for(;f=fopen("a","w");fclose(f))fputc(0,f);}   // 67 bytes

```

---

## Explanation of the non-portable version:

The file is created with random garbage permissions. With `gcc` 5.2, with `-O0` or `-O3`, it happens to include owner write permission, but this is not guaranteed. `0666` is decimal 438. **A 3rd arg to `open` would take another 4 bytes**. We're already hard-coding O\_TRUNC and so on, but this could break with a different compiler or libc on the same ABI.

We can't omit the 2nd arg to `open`, because the garbage value happens to include `O_EXCL`, and `O_TRUNC|O_APPEND`, so open fails with `EINVAL`.

---

We don't need to save the return value from `open()`. We assume it's `3`, because it always will be. Even if we start with fd 3 open, it will be closed after the first iteration. Worst-case, `open` keeps opening new fds until 3 is the last available file descriptor. So, up to the first 65531 `write()` calls could fail with `EBADF`, but will then work normally with every `open` creating fd = 3.

577 = 0x241 = `O_WRONLY|O_CREAT|O_TRUNC` on x86-64 Linux. Without `O_TRUNC`, the inode mod time and change time aren't updated, so a shorter arg isn't possible. `O_TRUNC` is still essential for the version that calls `write` to produce actual disk activity, not rewrite in place.

I see some answers that `open("a",1)`. O\_CREAT is required if `a` doesn't already exist. `O_CREAT` is defined as octal 0100 (64, 0x40) on Linux.

---

No resource leaks, so it can run forever. `strace` output:

```
open("a", O_WRONLY|O_CREAT|O_TRUNC, 03777762713526650) = 3
close(3)                                = 0
... repeating

```

or

```
open("a", O_WRONLY|O_CREAT|O_TRUNC, 01) = 3
write(3, "\0", 1)                       = 1   # This is the terminating 0 byte in the empty string we pass to write(2)
close(3)                                = 0

```

I got the decimal value of the `open` flags for this ABI using `strace -eraw=open` on my C++ version.

On a filesystem with the Linux `lazytime` mount option enabled, a change that only affects inode timestamps will only cause one write per 24 hours. With that mount option disabled, timestamp updating might be a viable way to wear out your SSD. (However, several other answers only do metadata I/O).

---

## alternatives:

**shorter non-working**:

`main(){for(;;)close(write(open("a",577),"",3));}` uses `write`'s return value to pass a `3` arg to close. It saves another byte, but doesn't work with gcc -O0 or -O3 on amd64. The garbage in the 3rd arg to `open` is different, and doesn't include write permission. `a` gets created the first time, but future iterations all fail with `-EACCESS`.

**longer, working, with different system calls**:

`main(c){for(open("a",65);pwrite(3,"",1);)sync();}` rewrites a byte in-place and calls `sync()` to sync all filesystems system-wide. This keeps the drive light lit up.

We don't care which byte, so we don't pass 4th arg to pwrite. Yay for sparse files:

```
$ ll -s a
300K -rwx-wx--- 1 peter peter 128T May 15 11:43 a

```

Writing one byte at an offset of ~128TiB led to xfs using 300kiB of space to hold the extent map, I guess. Don't try this on OS X with HFS+: IIRC, HFS+ doesn't support sparse files, so it will fill the disk.

XFS is a proper 64bit filesystem, supporting individual files up to 8 exabytes. i.e. 2^63-1, the maximum value `off_t` can hold.

`strace` output:

```
open("a", O_WRONLY|O_CREAT, 03777711166007270) = 3
pwrite(3, "\0", 1, 139989929353760)     = 1
sync()                                  = 0
pwrite(3, "\0", 1, 139989929380071)     = 1
sync()                                  = 0
...

```

# Answer
> 2 votes
# Racket, 46 bytes

```
(do()(#f)(write-to-file'a"f"#:exists'replace))

```

# Answer
> 1 votes
# Factor, 73 bytes

```
USING: io.files io.encodings
[ 0 "a" utf8 set-file-contents ] [ t ] while

```

Sets the file contents to the nul byte forever.

# Answer
> 1 votes
# CBM BASIC 7.0, 9 bytes

```
0dS"a":rU

```

This program, when run, repeatedly saves itself to disk. Here's a more readable version which doesn't use BASIC keyword abbreviations:

```
0 dsave "a" : run

```

# Answer
> 1 votes
# Python, 32 bytes

```
while 1:open("a","w").write("b")

```

Note that if run on python 3, this will produce an infinite number of warnings. Also, it will probably run out of fds if run in a non-refcounting implementation.

# Answer
> 1 votes
# Dyalog APL 15.0, 17 bytes (non-competing)

```
(⊢⊣⊃⎕NPUT⊢)⍣≢'A'1

```

Chrome currently renders U+2262 wrong. The above line should look like `(⊢⊣⊃⎕NPUT⊢)⍣̸≡'A'1`.

This is non-competing because version 15 has not been released yet.

Applies  the function `(⊢⊣⊃⎕NPUT⊢)` on `'A'1` until the input is changed (i.e. never):

`⊢⊣⊃⎕NPUT⊢` is a function train:

```
┌─┼───┐
⊢ ⊣ ┌─┼─────┐
    ⊃ ⎕NPUT ⊢

```

The rightmost  returns `'A'1` unmodified; this (filename, overwrite-flag) will be the right argument to \`⎕NPUT'.

'⊃' returns the first element of `'A'1` (`'A'`); this is the data to be written.

Then `⎕NPUT` is run, and reports how many bytes were written (2 or 3 depending on OS); this becomes the right argument to the .

The leftmost  again returns `'A'1` unmodified; this is the left argument to the .

ignores its right argument and returns the left argument (`'A'1`), this becomes the new value fed to .

Since the new value is identical to the old one, the operation is continued (forever).

# Answer
> 1 votes
# SmileBASIC, 12 bytes

```
SAVE"A
EXEC.

```

# Answer
> 0 votes
# vim text editor, 10 bytes

```
qa:w<enter>@aq@a

```

8 bytes if you do not could the execution command `@a`

# Answer
> 0 votes
# Lua, 39 bytes

```
while''do io.open('a',"w"):write('')end

```

# Answer
> 0 votes
# C++, 61 bytes. (or 66 bytes to actually hit the disk on Linux+XFS+`lazytime`)

Timestamp metadata I/O only:

```
#include <fstream>
int main(){for(;;){std::ofstream a("a");}}

```

The disk I/O is due to `a`'s mod time changing, which will be written to disk occasionally. (*very* occasionally with the commonly-use `lazytime` mount option. Also see my C answer.)

---

Write data before closing:

```
#include <fstream>
int main(){for(;;){std::ofstream a("a");a<<4;}}

```

Actually hits the disk: lights up my hard drive light. (Linux 4.2.0, XFS, `lazytime`)

---

The `ofstream` constructor opens the file, and the destructor closes it again. There are **no resource leaks**, so this will actually run forever without running out of memory, file handles, or disk space.

`strace` output:

```
open("a", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "4", 1)                        = 1      # not present with first version
close(3)                                = 0
... repeating

```

# Answer
> 0 votes
# C99, 84 bytes

```
#include<stdio.h>
int main(){while(1){FILE*f=fopen("a","w");fputc(9,f);fclose(f);};}

```

If you don't care about buffers, you can do this instead:

---

# C99, 65 bytes

```
#include<stdio.h>
int main(){while(1){fputc(9,fopen("a","w"));};}

```

I don't know if it closes automatically (no file handle), so please comment and I'll edit.

---

Lots of \ts to write (relax, they're not infinite!).

# Answer
> 0 votes
# Tcl, 36 bytes

```
set f [open a w]
while 1 {puts $f .}

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Corrupting A Binary File By Interpreting It As Text
Using FTP's ASCII mode to transfer binary files is a bad idea. It is likely to corrupt your data. Badly. Let's simulate this corruption!

Your task is to write a program which takes a file as input and outputs the corrupted version of the file. Because how exactly your file gets corrupted is dependent on both the FTP client and server and their systems/implementations, for this challenge, we will use the following rules for corruption, in this order:

* Clear the high bit in each byte of the file. (Masking with 0x7F is an option here)
* When encountering escape (0x1b) followed by `[`, delete from the escape character through the next letter character (`A`-`Z` and `a`-`z`), inclusive.
* Escape followed by any other character should remove both the escape and the character following it.
* All control codes (characters in the range 0x00-0x1F, inclusive, and 0x7F) other than tab (0x09) and linefeed (0x0a) should be removed.

## Other rules

* Input and output can be in any convenient format. You do not need to use actual files.
* Shortest code wins, of course.
* Standard rules and loopholes apply.

# Answer
> 1 votes
# Perl 5, ~~62~~ 53 bytes

```
y/\x80-\xff/\0-\c?/;s/\e(\[.*?[a-z]|.)|[^\t\n -~]//gi

```

Try it online! No, I don't know how to input nonprinting characters, particularly illegal UTF-8 sequences, into TIO. Edit: Saved 10 bytes thanks to @NahuelFouilleul.

# Answer
> 1 votes
## x86 assembly, 85 bytes

Bytecode:

```
8d0c244289deb00331dbcd803c0175418024247f8a042401f375203c1b0f94c374e23c09740c3c0a
74083c1f7ed83c7f74d4b00431db43cd80ebcb3c5b75014380e3fe0c203c617cbb3c7a7fb731dbeb
b3b001cd80

```

Source (with explanation in comments):

```
.section .text
.globl _start

_start:
    leal (%esp), %ecx  # read to (%esp)
    incl %edx          # read one byte

loop:
    movl %ebx, %esi    # save previous %ebx
loopnosave:
    movb $3, %al       # read
    xorl %ebx, %ebx    # stdin
    int $0x80

    cmpb $1, %al       # exit if we didn't get exactly one byte
    jne quit

    andb $0x7f, (%esp)
    movb (%esp), %al   # moving byte into %al saves bytes later on

    addl %esi, %ebx    # restore previous value of %ebx (currently 0)
                       # we use add instead of mov here to update flags
    jnz ignore         # check if we're in the middle of an esc-sequence

    cmpb $0x1b, %al    # check for esc
    sete %bl           # if it is esc, set the "ignore" flag...
    je loop            # ... and skip the output

    cmpb $0x09, %al    # explicitly output tabs and newlines
    je out
    cmpb $0x0a, %al
    je out

    cmpb $0x1f, %al    # don't output control characters
    jle loopnosave
    cmpb $0x7f, %al
    je loopnosave

out:
    movb $4, %al       # write
    xorl %ebx, %ebx
    incl %ebx          # stdout
    int $0x80

    jmp loopnosave     # we clobbered %ebx, so we don't want to keep it

ignore:
    cmpb $'[', %al     # check if it's [
    jne ok             # skip next instruction if not
    incl %ebx          # set %ebx to anything but 1
ok:
    andb $0xfe, %bl    # clear lowest bit on %ebx
    orb $0x20, %al     # uppercase to lowercase
    cmpb $'a', %al
    jl loop
    cmpb $'z', %al
    jg loop
    xorl %ebx, %ebx    # clear ignore flag if letter found
    jmp loop

quit:
    movb $1, %al
    int $0x80

```

Try it online! (with testcases)

Overview / general explanation:

* The program reads one byte at a time. `%al` holds the input byte, `%ebx` holds a flag that gets set when an ESC character is encountered. Since we need `%ebx` to call `sys_read` and `sys_write`, `%esi` is used as a temporary storage space for its previous value.
* The `%ebx` flag is `0` ordinarily, `1` if the previous character was ESC, and `2` or greater if an `ESC[` was found. On every loop, the program first tests if the flag is zero. If it is, we either set the flag (if the next character is ESC) or print the next character and move on.

If it's nonzero, we don't print the character, but instead unset the least significant bit of the flag. This has the effect of zeroing it if it's `1`, but it will remain nonzero if it's any other positive integer (signifying a preceding `ESC[`). Then we set it to zero (by xoring it with itself) if the current character is a letter, terminating the `ESC[` sequence.
* One trick I'd like to point out: it's a little miraculously convenient that the file descriptor for STDIN happens to be `0`. This allows us to postpone moving `%esi` back to `%ebx` until the first time we have to check the flag, which happens to be checking whether it's zero. A `movl` instruction would not update flags, but `addl` does, and since `%ebx` was previously set to zero to read from STDIN, the add instruction happens to be equivalent.
* Uses many of the same tricks as in my cat program.

# Answer
> 1 votes
## 16/32-bit x86 assembly code, 47 bytes

Bytes:

```
AC247F3C7F74253C0974203C0A741C3C1B7514497418AC3C5B7511497410AC24DF2C403C1A77F43C1F7601AAE2D2C3
```

Disassembly:

```
l1: lodsb ;fetch a byte
    and   al, 7fh    ;clear bit 7
    cmp   al, 7fh
    je    l5         ;skip 0x7F
    cmp   al, 9
    je    l4         ;accept 0x09
    cmp   al, 0ah
    je    l4         ;and 0x0A
    cmp   al, 1bh
    jne   l3         ;branch if not ESC
    dec   ecx
    je    l6         ;exit if out of characters
    lodsb            ;fetch a byte
    cmp   al, '['
    jne   l5         ;skip if not '['
l2: dec   ecx
    je    l6         ;exit if out of characters
    lodsb            ;fetch a byte
    and   al, 0dfh   ;clear bit 6 so lowercase -> uppercase
    sub   al, 40h    ;convert potential uppercase to 0x00-0x1A range
                     ;(lesser values will wrap around)
    cmp   al, 1ah    ;check for 'Z'
    jnbe  l2         ;loop if not less or equal
l3: cmp   al, 1fh
    jbe   l5         ;ignore all other values less or equal to 0x1F
l4: stosb            ;store surviving character
l5: loop  l1         ;loop while characters remain
l6: ret
```

Input: (E)SI is pointer to input text, (E)DI is pointer to output buffer, (E)CX is length of input.
Replace ECX with CX for 16-bit code. Code size is not affected.

# Answer
> 0 votes
## Python 3, ~~186~~ ~~100~~ 84 bytes

```
lambda s:re.sub(b"␛\[.*?[A-Za-z]|␛.|[^ -~\n␉]",b"",bytes(b&127for b in s))
import re

```

Applies each filter in turn, with filters 2, 3 and 4 being implemented by a regular expression. (Diagram not to scale.)

-15 bytes thanks to Erik the Outgolfer

Try it online!

## Test cases

I assume that my program's doing the right thing here.

1. ```
f(b"ab\x1b[cde\x1b[;'3GH\x1bIJK\x84\xa2\r\n\t") => b'abdeHJK"\n\t'

```

# Answer
> 0 votes
# Clean, 164 bytes

Escape sequences counted as one byte each, since they're valid code but not valid UTF-8
(so TIO and SE don't like them)

```
import StdEnv
?[]=[]
?['\33':t]= ?(drop 1((if(t%(0,0)==['['])(dropWhile(not o isAlpha))id)t))
?[h:t]|h<' '&&h<>'	'&&h<>'
'||h>'\176'= ?t=[h: ?t]

```

#

```
?o map(\e|e<'\177'=e=e-'\200')

```

Try it online!

# Answer
> 0 votes
# C (gcc), 116 112 bytes

This program assumes that a second `ESC` in a row matches as a non-`[` (e.g. "`ESC` `ESC` `[0a`" -\> "`[0a`".) So that I can send `NUL` characters to the function, I provide a counted string to it instead of a standard string.

Thanks to @ceilingcat for the suggestions.

```
f(t,c,i,s)char*t;{for(s=0;i=*t++&127,c--;)s?s=2*!(s-1?isalpha(i):i-91):i-27?i-9u<2|i>31&&i<127&&putchar(i):s++;}

```

Try it online!

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


title: Transitive Equality

text:
# Question
Title: Transitive Equality
## The Challenge

Your program should take 3 inputs:

* A positive integer which is the number of variables,
* A set of unordered pairs of nonnegative integers, where each pair represents an equality between variables, and
* A positive integer which represents the starting variable,

It should return a set of nonnegative integers which represent all variables which can be shown to be transitively equal to the starting variable (including the starting variable itself).

In other words, given inputs `N`, `E`, and `S`, return a set `Q`, such that:

* `S ∈ Q`.
* If `Z ∈ Q` and `(Y = Z) ∈ E`, then `Y ∈ Q`.
* If `Z ∈ Q` and `(Z = Y) ∈ E`, then `Y ∈ Q`.

This can also be expressed as a problem:

> Given an undirected graph and a vertex in the graph, list the vertices in its connected component.

## Specifications

* You can choose to use 0-based or 1-based indexing.
* The first input counts the number of variables that are present, where variables are given as numbers. Alternatively, you can not take this input, in which case this is assumed to be equal to either the highest variable index present, or one more than this, depending on your indexing scheme.
* You can assume the input is well formed: you will not be given variables outside of the range specified by the first input. For example, `3, [1 = 2, 2 = 0], 1` is a valid input, while `4, [1 = 719, 1 = 2, 3 = 2], -3` is not.
* You *cannot* assume that any variable will have any equalities associated with with it. If given a third input that is "lonely" (has no equalities), the correct output is a singleton set containing only that input (since it is equal to itself).
* You can assume that the equalities will not contain an equality from a variable to itself, and that the same equality will not be given multiple times (this includes things like `1 = 2` and `2 = 1`).
* You can assume that all integers given will be within your language's representable range.
* You can take the second input in any reasonable format.

Here are some reasonable formats:

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

{(0, 2), (0, 3), (1, 0)}

[0, 2, 0, 3, 1, 0]

0 2 0 3 1 0

Graph[{{0, 2}, {0, 3}, {1, 0}}]

[0 = 2, 0 = 3, 1 = 0]

```
* You can output in any reasonable format (i.e. set, list, etc.). Order is irrelevant.

## Scoring

This is , so the shortest valid program (in bytes) wins.

## Test Cases (0-indexed)

```
3, [1 = 2, 2 = 0], 1                      -> {0, 1, 2}
5, [0 = 2, 0 = 3, 1 = 2], 3               -> {0, 1, 2, 3}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 4        -> {2, 4}
6, [0 = 3, 1 = 3, 2 = 4, 5 = 1], 5        -> {0, 1, 3, 5}
5, [0 = 1, 2 = 0, 0 = 3, 4 = 0], 2        -> {0, 1, 2, 3, 4}
6, [0 = 1, 1 = 2, 2 = 3, 3 = 4, 4 = 5], 3 -> {0, 1, 2, 3, 4, 5}
4, [0 = 1, 1 = 2, 2 = 0], 3               -> {3}
5, [0 = 2, 2 = 4], 2                      -> {0, 2, 4}
8, [], 7                                  -> {7}

```

## Test Cases (1-indexed)

```
3, [2 = 3, 3 = 1], 2                      -> {1, 2, 3}
5, [1 = 3, 1 = 4, 2 = 3], 4               -> {1, 2, 3, 4}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 5        -> {3, 5}
6, [1 = 4, 2 = 4, 3 = 5, 6 = 2], 6        -> {1, 2, 4, 6}
5, [1 = 2, 3 = 1, 1 = 4, 5 = 1], 3        -> {1, 2, 3, 4, 5}
6, [1 = 2, 2 = 3, 3 = 4, 4 = 5, 5 = 6], 4 -> {1, 2, 3, 4, 5, 6}
4, [1 = 2, 2 = 3, 3 = 1], 4               -> {4}
5, [1 = 3, 3 = 5], 3                      -> {1, 3, 5}
8, [], 8                                  -> {8}

```

# Answer
> 7 votes
# Brachylog, 22 bytes

```
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt

```

Try it online!

## Explanation

```
{tc⊇,?k.&¬(t∋;.xȮ)∧}ᶠt  Input is a pair, say [2,[[1,3],[2,4],[5,2]]]
{                   }ᶠ   Find all outputs of this predicate:
 t                        Tail: [[1,3],[2,4],[5,2]]
  c                       Concatenate: [1,3,2,4,5,2]
   ⊇                      Choose a subset: [4,5]
    ,?                    Append the input: [4,5,2,[[1,3],[2,4],[5,2]]]
      k                   Remove the last element: [4,5,2]
       .                  This list is the output.
        &¬(      )∧       Also, the following is not true:
           t∋              There is a pair P in the second part of the input.
             ;.x           If you remove from P those elements that occur in the output,
                Ȯ          the result is a one-element list.
                      t  Take the last one of these outputs, which is the shortest one.

```

# Answer
> 5 votes
# Python 2, ~~65~~ 63 bytes

<sup>-2 bytes thanks to ovs</sup>

```
def f(e,s):b={s};exec"for p in e:b|=b&p and p\n"*len(e);print b

```

Try it online!

# Answer
> 2 votes
# Pyth, 12 bytes

```
u|sf@TGQG.{E

```

Test suite.

# Answer
> 2 votes
# Operation Flashpoint scripting language, 364 bytes

```
f={t=_this;r=t select 1;i=0;while{i<t select 0}do{call format["V%1=[%1]",i];i=i+1};i=0;while{i<count r}do{call format(["V%1=V%1+V%2;V%2=V%1"]+(r select i));i=i+1};l=call format["V%1",t select 2];g={i=0;c=count l;while{i<c}do{if(i<count l)then{e=l select i;call _this};i=i+1}};{l=l+call format["V%1",e]}call g;"l=l-[e]+[e];if(count l<c)then{c=count l;i=0}"call g;l}

```

**Call with:**

```
hint format
[
    "%1\n%2\n%3\n%4\n%5\n%6\n%7\n%8\n%9",
    [3, [[1, 2], [2, 0]], 1] call f,
    [5, [[0, 2], [0, 3], [1, 2]], 3] call f,
    [6, [[0, 3], [1, 3], [2, 4], [5, 1]], 4] call f,
    [6, [[0, 3], [1, 3], [2, 4], [5, 1]], 5] call f,
    [5, [[0, 1], [2, 0], [0, 3], [4, 0]], 2] call f,
    [6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]], 3] call f,
    [4, [[0, 1], [1, 2], [2, 0]], 3] call f,
    [5, [[0, 2], [2, 4]], 2] call f,
    [8, [], 7] call f
]

```

**Output:**

**Unrolled:**

```
f =
{
    t = _this;
    r = t select 1;
    i = 0;
    while {i < t select 0} do
    {
        call format["V%1=[%1]", i];
        i = i + 1
    };

    i = 0;
    while {i < count r} do
    {
        call format(["V%1=V%1+V%2;V%2=V%1"] + (r select i));
        i = i + 1
    };

    l = call format["V%1", t select 2];

    g =
    {
        i = 0;
        c = count l;
        while {i < c} do
        {
            if (i < count l) then
            {
                e = l select i;
                call _this
            };
            i = i + 1
        }
    };

    {l = l + call format["V%1", e]} call g;
    "l = l - [e] + [e];

    if (count l<c)then
    {
        c = count l;
        i = 0
    }" call g;

    l
}

```

# Answer
> 2 votes
# Clean, ~~85~~ 81 bytes

```
import StdEnv
$l=limit o iterate(\v=removeDup(flatten[v:filter(isAnyMember v)l]))

```

Try it online!

Defines the function `$ :: [[Int]] -> ([Int] -> [Int])`

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

```
#~VertexComponent~#2~Check~{#2}&

```

Input format: `{2<->3, 3<->1}, 3`. It does not take the first input.

Try it online!

# Answer
> 1 votes
# Jelly,  ~~12~~   ~~11~~  10 bytes

-1 thanks to Erik the Outgolfer (replace the atom `œ&` with `f`)

```
⁹fÐfȯFµÐLQ

```

A dyadic link accepting `E` on the left (as a list of length-two-lists) and `S` on the right (as an integer) returning a \[de-duplicated\] list.

**Try it online!** or see a test-suite.

### How?

```
⁹fÐfȯFµÐLQ - Link: list of lists, E; integer S
      µÐL  - repeat the monadic chain to the left until a fixed point is reached:
  Ðf       -   (for each pair in E) filter keep if:
 f         -     filter discard if in
⁹          -     chain's right argument
           -     (originally [S], thereafter the previous result as monadic)
    ȯ      -   logical OR with implicit right
           -   (force first pass to become S if nothing was kept)
     F     -   flatten to a single list
           -   (S -> [S] / [[1,4],[1,0]]->[1,4,1,0] / etc...)
         Q - de-duplicate

```

# Answer
> 1 votes
# Perl 5 `-n0`, ~~49~~ 39 bytes

Give starting value on a line on STDIN followed by lines of pairs of equivalent numbers (or give the starting value last or in the middle or give multiple starting values, it all works)

```
#!/usr/bin/perl -n0
s/
$1? | $1/
/ while/^(\d+
)/msg;say//g

```

Try it online!

This can output an element in the result set multiple times. This 48 bytes variation outputs each equivalent element only once:

```
s/
$1? | $1/
/ while/^(\d+
)(?!.*^\1)/msg;say//g

```

Try it online!

# Answer
> 1 votes
# Python 2, 53 bytes

```
e,s,n=input()
b={s}
for p in n*e:b|=b&p and p
print b

```

Try it online!

Same length as function:

```
lambda e,s,n:reduce(lambda b,p:b|(b&p and p),n*e,{s})

```

Try it online!

This is based off Rod's nice solution using the short-circuiting update `b|=b&p and p`. Taking the number of variables as an input `n` helps shorten the loop code.

# Answer
> 1 votes
# K (ngn/k), ~~37~~ ~~36~~ 35 bytes

```
{&a[z]=a:{y[x]&:|y x;y}[+y,,&2]/!x}

```

Try it online!

`{` `}` function with arguments `x`, `y`, and `z` representing `N`, `E`, and `S` respectively

`!x` is the list 0 1 ... x-1

`&2` is the list `0 0`

`y,,&2` we add the pair `0 0` to `y` to avoid the special case of an empty `y`

`+y,,&2` same thing transposed from a list of pairs to a pair of lists

`{` `}[+y,,&2]` is a projection, i.e. a function in which `x` will be the value of `+y,,&2` and `y` will be the argument passed in when calling the projection

`|y x` is `y` at indices `x`, reversed (`|`)

`@[y;x;&;|y x]` amend `y` at indices `x` by taking the minimum (`&`) of the existing element and an element from `|y x`

`/` keep calling until convergence

`a:` assign to a

`a[z]=z` boolean mask of the elements of `a` equal to the `z`-th

`&` convert the boolean mask to a list of indices

# Answer
> 1 votes
# Ruby, 39 bytes

```
->e,*s{e.map{e.map{|a|a-s!=a&&s|=a}};s}

```

Try it online!

# Answer
> 1 votes
# Octave, ~~48~~ 45 bytes

```
t=@(A,u)find(((eye(size(A))+A+A')^nnz(A))(u,:));

```

Takes input as "adjacency-matrix", for example uses `[0 0 0; 0 0 1; 1 0 0]` for `[2 = 3, 3 = 1]`, try it online!

## Explanation

First we construct the complete adjacency matrix for the transitive graph, using the sum of `eye(size(A))` (elements are reflexive), `A` (input) and `A'` (the relation is symmetric).

We compute the transitive closure by computing the power to `nnz(A)` which suffices (`nnz(A)` is upper bound for a path's length), so from there all that's left is to get the right row with `(u,:)` and `find` all non-zero entries.

# Answer
> 0 votes
# Python 2, 87 bytes

```
g,v=input();x={v};d=[v]
for c in d:x|={c};d+={k[k[0]==c]for k in g if c in k}-x
print x

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 80 bytes

```
f(g,p)=c=concat;if(p==q=c(c(p=Set(p),[e|e<-g,setintersect(Set(e),p)])),p,f(g,q))

```

Try it online!

# Answer
> 0 votes
## JavaScript (ES6), 87 bytes

```
(a,n)=>a.map(([b,c])=>[...d[b]||[b],...d[c]||[c]].map((e,_,a)=>d[e]=a),d=[])&&d[n]||[n]

```

Deduplication would be possible using `&&[...new Set(d[n]||[n])]` at a cost of 14 bytes.

---
Tags: code-golf, graph-theory, equation
---


title: Print me a Tower Block

text:
# Question
Title: Print me a Tower Block
Print a tower block with the shortest possible code.

**Input:**

The input defines how many floors the tower block has. One floor contains a window on either side of the door. The window is made up of 3x3 hashes.

An example of a 4 storey tower block is below:

```
      =====================
      )V V V V V V V V V V(
     )V V V V V V V V V V V(
    )V V V V V V V V V V V V(
   )V V V V V V V V V V V V V(
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   : : : : : : : : : : : : : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : : : : : : : : : : : : :
   : : : : : : : : : : : : : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : : : : : : : : : : : : :
   : : : : : : : : : : : : : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : ### : : : : : : ### : :
   : : : : : : : : : : : : : :
   : : : : : _______ : : : : :
   : : ### : I     I : ### : :
   : : ### : I     I : ### : :
   : : ### : I     I : ### : :
   : : : : : I     I : : : : :

```

**Update:**

The input has to be one or greater.

Trailing spaces at the end of lines are allowed.

In my example, every line has three leading spaces. This isn't mandatory, just the tower block with the input is.

# Answer
> 6 votes
# , 72 bytes

```
13iV r(É)3ñÄ¯lxñÄ21r=GÙÒ~Ù14R: ÙÄ2w3r#7w.3ÄkdGÀpG4k5w7r_bêojrIÎfIl5r

```

Try it online!

Here is a hexdump, since this contains unprintable characters:

```
00000000: 3133 6956 201b 7228 c929 33f1 c4af 6c78  13iV .r(.)3...lx
00000010: f1c4 3231 723d 47d9 d27e d931 3452 3a20  ..21r=G..~.14R:
00000020: 1bd9 c432 7733 7223 3777 2e33 c46b 6447  ...2w3r#7w.3.kdG
00000030: c070 4734 6b35 7737 725f 1662 ea6f 6a72  .pG4k5w7r_.b.ojr
00000040: 49ce 6649 6c35 7220                      I.fIl5r

```

I ran into a strange bug. The section in the middle: `dGÀpG` should have been: `ÀäGG`, but this does not work for inputs of 1, and I have no idea why. `¯\_(ツ)_/¯`

# Answer
> 8 votes
## Mathematica, 301 288 258 bytes

```
" "~(s=If[#2==0,"",#~StringRepeat~#2]&)~3<>{"="~s~21,"
",s[" ",12-#]<>{")","v "~s~#,"v(
"}&/@9~Range~12,"~"~s~27,"
",s[(x=(u=": ")~s~13<>":
")<>{y=u<>{z=": ### ",v=u~s~5,w=z<>": :
"},y,y,x},#-1],v,"_"~s~7," ",v,"
",m=u<>{z,u,n="I     I ",w},m,m,v,n,w}&

```

Pure function which takes a positive integer and outputs a string. The output string won't look right because Mathematica apparently doesn't display monospace fonts as monospace:

For reasons I don't quite understand, it does format as monospace if you `Print` the string:

Edit: Saved several bytes by not including `" "` at the beginning of each line. Changed the definition of `s` to handle the case where there is only one floor (`StringRepeat` doesn't like repeating a string `0` times).

Edit 2: Thanks to LegionMammal978 and the fact that `StringJoin` is `Listable`, this is now an incomprehensible nightmare of nested lists and also 30 bytes shorter.

# Answer
> 4 votes
# Python 2, ~~275~~ ~~270~~ ~~262~~ ~~246~~ ~~240~~ 236 bytes

Saved a couple with a hint from @Flp.Tkc and by changing the first for loop.

16 saved with more help from @Flp.Tkc

```
a,h,b,c,w=' ',"I  ",": "," :","#"*3;d,e,j=b*2+w+a+b+h,b*5+h,[b*14]
print'\n'.join([a*3+'='*21]+[a*(4-x)+')'+'V '*(x+8)+'V('for x in 1,2,3,4]+['-'*27]+(j+[b*2+w+c*6+a+w+c*2]*3+j)*(input()-1)+[b*5+"_"*7+c*5]+[d+a+d[::-1]]*3+[e+a+e[::-1]])

```

Try it online!

Just builds each line of the tower as a string and adds it to an array them prints the array at the end. If anyone wants a full explanation I'll grudgingly give if I can remember how it works ☺

# Answer
> 3 votes
# T-SQL, ~~378~~ ~~372~~ ~~353~~ ~~331~~ 325 bytes

**Golfed:**

```
DECLARE @ INT=3

,@h varchar(max)=REPLICATE('~',27)SELECT @h+='
: '+a+IIF(n>@*5-6,IIF(n%5=0,'_______ ','I     I '),t)+a+':'FROM(SELECT
IIF(n%5%4=0,t,': ### : ')a,*FROM(SELECT': : : : 't,number n,*FROM spt_values)x)y
WHERE type='P'and n<@*5SET @=0WHILE @<4SELECT
@h=SPACE(@)+')'+REPLICATE('V ',12-@)+'V(
'+@h,@+=1PRINT'   '+REPLICATE('=',21)+'
'+@h

```

**Ungolfed:**

```
DECLARE @ INT=3

,@h varchar(max)=REPLICATE('~',27)
SELECT @h+='
: '+a+IIF(n>@*5-6,IIF(n%5=0,'_______ ','I     I '),t)+a+':'
FROM
(SELECT IIF(n%5%4=0,t,': ### : ')a,*
FROM
(SELECT': : : : 't,number n,*
FROM spt_values)x)y
WHERE type='P'and n<@*5
WHILE @>=0
  SELECT @h=SPACE(3-@)+')'+REPLICATE('V ',9+@)+'V(
'+@h,@-=1
PRINT'   '+REPLICATE('=',21)+'
'+@h

```

**Try it out**

# Answer
> 3 votes
# PowerShell, 193 bytes

```
"   "+"="*21
3..0|%{" "*$_+")"+"V "*(12-$_)+"V("}
"~"*27
--$args[0]..0|%{($b=": "*5)+(($a=": "*4),'_______ ')[!$_]+$b;,(': : ### : '+($a,($c='I     I '))[!$_]+': ### : :')*3;$b+($a,$c)[!$_]+$b}

```

Try it online!

*(I feel there may still be a few bytes here or there. Sub-190 seems doable.)*

The first three lines form the roof, using string multiplication and concatenation, along with a loop `3..0|%{...}` to get the correct number and sloping of `V`s.

The next line runs from the input pre-decremented `--$args[0]` down to `0` as a loop (the pre-decrement allows us to index using `!$_` instead of `$_-eq1` saving several bytes later). Each loop iteration, we're constructing a bunch of strings, setting variables `$b` and `$a` along the way. We're also using pseudo-ternaries `(... , ...)[...]` to choose the appropriate strings for the middle so we can get the doorway on the first floor correct.

Each of the strings are left individually on the pipeline, and the default `Write-Output` inserts newlines between, so we get those for free.

# Answer
> 2 votes
# C, ~~409~~ ~~406~~ 402 bytes

```
#define P(x)p(": ",x);
#define S(x)p(x,1);
#define L P(2)p("#",3);p(" :",6);S(" ###");S(" : :\n")
#define Q p("V ",i+++9)
p(s,n)char*s;{printf(s,--n?p(s,n):0);}i;t(n){p(" ",3);p("=",21);S("\n   )")Q;S("V(\n  )")Q;S("V(\n )")Q;S("V(\n)")Q;S("V(\n")p("~",27);S("\n")for(;--n;){P(13)S(":\n")L;L;L;P(13)S(":\n")}P(5)p("_",7);p(" :",5);S("\n")p(": : ### : I     I : ### : :\n",3);P(5)S("I     I")p(" :",5);}

```

Call with:

```
int main()
{
    t(4);
}

```

# Answer
> 1 votes
## Batch, 373 bytes

```
@echo off
set s=###
echo    %s:#========%
for %%s in ("   )" "  )V " " )V V " ")V V V ")do echo %%~sV%s:#= V V V%(
echo %s:#=~~~~~~~~~%
set t=: : ### : I     I : ### : :
set s=%t:I     I=: : : :%
for /l %i in (2,1,%1)do echo %s:###=: :%&echo %s%&echo %s%&echo %s%&echo %s:###=: :%
set s=%t:###=: :%
echo %s:I     I=_______%
echo %t%
echo %t%
echo %t%
echo %s%

```

Builds the ridge and gutter by noticing that they are multiples of 3, which shaves off a few bytes. Builds the roof by noticing that the suffix is the same for each line (and again includes some threefold repetition). Builds the walls by starting with the most interesting line of wall, which is the ground floor window, and removing details to generate the other parts of the wall.

# Answer
> 1 votes
# Javascript, 335 bytes

```
y=z=>{a="   "+"=".repeat(21);for(b=9;13>b;b++)a+="\n"+" ".repeat(12-b)+")"+"V ".repeat(b)+"V(";a+="\n"+"~".repeat(27);b="\n"+": ".repeat(14);c=": : ### : : : : : : ### : :";for(d=0;d<z-1;d++)a+=b+"\n"+c+"\n"+c+b;a+="\n: : : : : _______ : : : :\n"+": : ### : I     I : ### : :\n".repeat(3)+": : : : : I     I : : : : :";console.log(a)};

```

Creates a function `y()` with argument `z`, such that `y(z)` produces the desired output.

# Example Usage:

```
y=z=>{a="   "+"=".repeat(21);for(b=9;13>b;b++)a+="\n"+" ".repeat(12-b)+")"+"V ".repeat(b)+"V(";a+="\n"+"~".repeat(27);b="\n"+": ".repeat(14);c=": : ### : : : : : : ### : :";for(d=0;d<z-1;d++)a+=b+"\n"+c+"\n"+c+b;a+="\n: : : : : _______ : : : :\n"+": : ### : I     I : ### : :\n".repeat(3)+": : : : : I     I : : : : :";console.log(a)};

console.log(y(3));

```

I'm transitioning from normal JavaScript to code-golf JS. Any tips would be greatly appreciated.

# Answer
> 1 votes
# Canvas, ~~62~~ 61 bytes

```
⁶=⁵×V７× ＊ )×４＊∔／‾²ｍ~７«× ×∔│８ ×:＊５＊#３３＊６２╋│⁸＊∔ｌ４－_７× ５×Iｅ４＊∔╋╋

```

Try it here! Input 0 works as expected even though that's not required.

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


title: Cycling with Rubik's

text:
# Question
Title: Cycling with Rubik's
While idly twisting my Rubik's cube around, my son noticed that it kept going back to the solved state. I'm pretty sure he thought this was some sort of voodoo magic at first, but I explained that if you keep repeating the same sequence of moves, it will always return to its original state. *Eventually.*

Of course, being a kid, he had to try it out for himself and picked a "random" sequence he thought would be tricky. He lost track after ten repeats or so, and asked me how many times he would have to repeat it. Not knowing the sequence he was using, I told him I didn't know, but that we could write a program to find out.

This is where you come in. Of course, I *could* just whip something up, but he'd like to type it in himself. He isn't a very fast typist yet, though, so I need the *shortest program possible*.

### Objective

Given a sequence of turns, output the fewest number of times it must be performed to return the cube to its original state. This is code golf, so least bytes wins. You can write a program or function, and all the other usual defaults apply.

### Input

Input is a sequence of moves, taken as a string, list, or other format suitable for your language. Feel free to use a separator (or not) between moves if in string form.

There are six "basic" moves that must be taken into account, along with their inverses:

```
R - Turn the right face clockwise
L - Turn the left face clockwise
U - Turn the up (top) face clockwise
D - Turn the down (bottom) face clockwise
F - Turn the front face clockwise
B - Turn the back face clockwise

```

The inverses are represented by adding a prime mark `'` after the letter. This indicates you turn that face counterclockwise, so `F'` turns the front face counterclockwise, and `F F'` would return it to the original state right away.

For the interested, this challenge is using a limited set of Singmaster Notation. Ruwix has some nice animations if you'd like to see it in action.

### Output

Output is simply the minimum number of times the input sequence must be performed.

### Examples

```
Input                Output

FF'               ->      1
R                 ->      4
RUR'U'            ->      6
LLUUFFUURRUU      ->     12
LUFFRDRBF         ->     56
LF                ->    105
UFFR'DBBRL'       ->    120
FRBL              ->    315

```

Here's a (quite naive) solver to compare your answers to, written in Java. It also accepts `2` for double moves (so the fourth case is equivalent to `L2U2F2U2R2U2`).

```
import java.util.ArrayList;
import java.util.List;

public class CycleCounter{

    public static void main(String[] args){
        int[] cube = new int[54];
        for(int i=0;i<54;i++)
            cube[i] = i;

        String test = args.length > 0 ? args[0] : "RUR'U'";
        List<Rotation> steps = parse(test);
        System.out.println(steps.toString());

        int count = 0;
        do{
            for(Rotation step : steps)
                cube = step.getRotated(cube);
            count++;
        }while(!isSorted(cube));

        System.out.println("Cycle length for " + test + " is " + count);
    }

    static List<Rotation> parse(String in){
        List<Rotation> steps = new ArrayList<Rotation>();
        for(char c : in.toUpperCase().toCharArray())
            switch(c){
                case 'R':steps.add(Rotation.R);break;
                case 'L':steps.add(Rotation.L);break;
                case 'U':steps.add(Rotation.U);break;
                case 'D':steps.add(Rotation.D);break;
                case 'F':steps.add(Rotation.F);break;
                case 'B':steps.add(Rotation.B);break;
                case '\'':
                    steps.add(steps.get(steps.size()-1));
                case '2':
                    steps.add(steps.get(steps.size()-1));
                    break;
            }
        return steps;
    }

    static boolean isSorted(int[] in){for(int i=0;i<in.length-1;i++)if(in[i]>in[i+1])return false;return true;}

    enum Rotation{
        R(new int[]{-1,-1,42,-1,-1,39,-1,-1,36, -1,-1,2,-1,-1,5,-1,-1,8, 20,23,26,19,-1,25,18,21,24, -1,-1,11,-1,-1,14,-1,-1,17, 35,-1,-1,32,-1,-1,29,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1}),
        L(new int[]{9,-1,-1,12,-1,-1,15,-1,-1, 27,-1,-1,30,-1,-1,33,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 44,-1,-1,41,-1,-1,38,-1,-1, -1,-1,6,-1,-1,3,-1,-1,0, 47,50,53,46,-1,52,45,48,51}),
        U(new int[]{2,5,8,1,-1,7,0,3,6, 45,46,47,-1,-1,-1,-1,-1,-1, 9,10,11,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 18,19,20,-1,-1,-1,-1,-1,-1, 36,37,38,-1,-1,-1,-1,-1,-1}),
        D(new int[]{-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,24,25,26, -1,-1,-1,-1,-1,-1,42,43,44, 29,32,35,28,-1,34,27,30,33, -1,-1,-1,-1,-1,-1,51,52,53, -1,-1,-1,-1,-1,-1,15,16,17}),
        F(new int[]{-1,-1,-1,-1,-1,-1,18,21,24, 11,14,17,10,-1,16,9,12,15, 29,-1,-1,28,-1,-1,27,-1,-1, 47,50,53,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,8,-1,-1,7,-1,-1,6}),
        B(new int[]{51,48,45,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,0,-1,-1,1,-1,-1,2, -1,-1,-1,-1,-1,-1,26,23,20, 38,41,44,37,-1,43,36,39,42, 33,-1,-1,34,-1,-1,35,-1,-1});

        private final int[] moves;
        Rotation(int[] moves){
            this.moves = moves;
        }

        public int[] getRotated(int[] cube){
            int[] newCube = new int[54];
            for(int i=0;i<54;i++)
                if(moves[i]<0)
                    newCube[i] = cube[i];
                else
                    newCube[moves[i]] = cube[i];
            return newCube;
        }
    }
}

```

# Answer
# Pyth, ~~66~~ 63 bytes

```
l.uum.rW}Hdd@_sm_B.iFP.>c3Zk3xZHG_r_Xz\'\39Nf!s}RTcZ2y=Z"UDLRFB

```

Try it online: Demonstration or Test Suite. Notice that the program is kinda slow and the online compiler is not able to compute the answer for `RU2D'BD'`. But be assured, that it can compute it on my laptop in about 12 seconds.

The program (accidentally) also accepts `2` for double moves.

### Full Explanation:

**Parse scramble:**

First I'll deal with the prime marks `'` in the input strings. I simply replace these with `3` and run-length decode this string. Since Pyth's decoding format requires the number in front of the char, I reverse the string beforehand. `_r_Xz\'\39`. So afterwards I reverse it back.

**Describe the solved cube state:**

`=Z"UDLRFB` assigns the string with all 6 moves to `Z`.

We can describe a cube state by describing the location for each cube piece. For instance we can say that the edge, that should be at UL (Up-Left) is currently at FR (Front-Right). For this I need to generate all pieces of the solved cube: `f!s}RTcZ2yZ`. `yZ` generates all possible subsets of `"UDLRFB"`. This obviously also generates the subset `"UDLRFB"` and the subset `"UD"`. The first one doesn't make any sense, since there is no piece that is visible from all 6 sides, and the second one doesn't make any sense, since there is no edge piece, that is visible from the top and the bottom. Therefore I remove all the subsets, that contain the subsequence `"UD"`, `"LR"` or `"FB"`. This gives me the following 27 pieces:

```
'', 'U', 'D', 'L', 'R', 'F', 'B', 'UL', 'UR', 'UF', 'UB', 'DL', 'DR', 'DF', 'DB',
'LF', 'LB', 'RF', 'RB', 'ULF', 'ULB', 'URF', 'URB', 'DLF', 'DLB', 'DRF', 'DRB'

```

This also includes the empty string and all the six 1-letter strings. We could interpret them as the piece in the middle of the cube and the 6 center pieces. Obviously they are not required (since they don't move), but I'll keep them.

**Doing some moves:**

I'll do some string translations to perform a move. To visualize the idea look at the corner piece in `URF`. What happens to it, when I do an `R` move? The sticker on the `U` face moves to the `B` face, the sticker `F` moves to the `U` face and the sticker on the `R` face stays at the `R` face. We can say, that the piece at `URF` moves to the position `BRU`. This pattern is true for all the pieces on the right side. Every sticker that is on the `F` face moves to the `U` face when an `R` move is performed, every sticker that is on the `U` face moves to the `B` face, every sticker on the `B` moves to `D` and every sticker on `D` moves to `F`. We can decode the changes of an `R` move as `FUBD`.

The following code generates all the 6 necessary codes:

```
_sm_B.iFP.>c3Zk3
['BRFL', 'LFRB', 'DBUF', 'FUBD', 'RDLU', 'ULDR']
    ^       ^       ^       ^       ^       ^
 U move  D move  L move  R move  F move  B move

```

And we perform a move `H` to the cube state `G` as followed:

```
m.rW}Hdd@...xZHG
m              G   map each piece d in G to:
 .rW   d              perform a rotated translation to d, but only if:
    }Hd                  H appears in d (d is currently on the face H)
            xZH           get the index of H in Z
        @...              and choose the code in the list of 6 (see above)

```

**Count the number of repeats:**

The rest is pretty much trivial. I simply perform the input scramble to the solved cube over and over until I reach a position that I previously visited.

```
l.uu<apply move H to G><parsed scramble>N<solved state>
u...N   performs all moves of the scramble to the state N
.u...   do this until cycle detected, this returns all intermediate states
l       print the length

```
> 16 votes

# Answer
# GAP, ~~792 783 782~~ ~~749~~ 650 Bytes

This seems to be working. If it messes up with something let me know.

Thanks to @Lynn for suggesting that I decompose some of the primitive moves.

Thanks to @Neil for suggesting that instead of `Inverse(X)` I use `X^3`.

Usage example: `f("R");`

```
R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);A:=R*L^3*F*F*B*B*R*L^3;D:=A*U*A;;F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);d:=NewDictionary((),true);AddDictionary(d,'R',R);AddDictionary(d,'L',L);AddDictionary(d,'U',U);AddDictionary(d,'D',D);AddDictionary(d,'F',F);AddDictionary(d,'B',B);f:=function(s) local i,p,b,t;p:=();
for c in s do if c='\'' then t:=t^2;else t:=LookupDictionary(d,c);fi;p:=p*t;od;return Order(p);end;

```

Here is the ungolfed code with a bit of explanation

```
  # Here we define the primitive moves
R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);
L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);
U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);
#D:=(7,34,21,16)(8,35,20,17)(9,36,19,18)(48,46,52,54)(47,49,53,51);
F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);
B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);

# Here we define D in terms of other primitive moves, saving on bytes
# Thanks @Lynn
# This is actually doable with a maximum of 3 of the primitive moves
# if a short enough sequence can be found.
D:=U^(R*L^3*F*F*B*B*R*L^3);

# create dictionary and add moves to it with appropriate char labels
d:=NewDictionary((),true);
AddDictionary(d,'R',R);
AddDictionary(d,'L',L);
AddDictionary(d,'U',U);
AddDictionary(d,'D',D);
AddDictionary(d,'F',F);
AddDictionary(d,'B',B);

f:=function(s)
    local c,p,t;

    # p will become the actual permutation passed to the function
    p:=();

    for c in s do
        if c='\'' then
            # The last generator we mutiplied (that we still have in t)
            # should have been its inverse. Compensate by preparing to
            # multiply it two more times to get t^3=t^-1. Thanks @Neil.
            t:=t^2;
        else
            t:=LookupDictionary(d,c);
        fi;
        p:=p*t;
    od;

    return Order(p);

end;

```
> 13 votes

# Answer
# Mathematica, ~~413~~ 401 bytes

```
Evaluate[f/@Characters@"RFLBUD"]=LetterNumber@"ABFEJNRMDAEHIMQPCDHGLPTOBCGFKOSNADCBILKJEFGHQRST"~ArrayReshape~{6,2,4};
r[c_,l_]:=(b=Permute[c,Cycles@f@l];MapThread[(b[[#,2]]=Mod[b[[#,2]]+{"F","B","L","R"}~Count~l{-1,1,-1,1},#2])&,{f@l,{3,2}}];b);
p@s_:=Length[c={#,0}&~Array~20;NestWhileList[Fold[r,#,Join@@StringCases[s,x_~~t:""|"'":>Table[x,3-2Boole[t==""]]]]&,c,(Length@{##}<2||c!=Last@{##})&,All]]-1

```

---

**Explanations**

A Rubik's Cube is made up with 20 movable **cubies** (8 corners, 12 edges). Each cubie can be given a number:

*corners*:

```
N   starting position
1     UFR
2     UBR
3     UBL
4     UFL
5     DFR
6     DBR
7     DBL
8     DFL

```

*edges*:

```
N   starting position
9     UF
10    UR
11    UB
12    UL
13    FR
14    BR
15    BL
16    FL
17    DF
18    DR
19    DB
20    DL

```

Note that when the cube is twisted, the cubies are generally not on their starting positions any longer. For example, when `R` is done, the cubie `1` moves from `UFR` to a new position `UBR`.

In such notation, a 90 degree turn can be described by 8 movements of cubies. For example, `R` is described by

```
from  to
UFR   UBR
UBR   DBR
DBR   DFR
DFR   UFR
UR    BR
BR    DR
DR    FR
FR    UR

```

Since each cubie has a unique starting position, each position has a unique starting cubie. That is to say, rule `UFR->UBR` is just `1->2` (means that `R` takes the cubie on the starting position of cubie `1` to the starting position of cubie `2`). Thus, `R` can be simplified further to a cycle

```
Cycles[{{1,2,6,5}, {10,14,18,13}}]

```

---

To fully solve a Rubik's Cube, we also need to align the cubies to their corresponding starting orientations. The faces of a cube is painted in different colors, the scheme that I often use when solving cubes is

```
face color
U    yellow
D    white
F    red
B    orange
R    green
L    blue

```

When we analyzing the orientations of corners, colors other than yellow or white are ignored, and yellow and white are considered as the same color.

Suppose cubie `1` is on its starting position `UFR`, the yellow facet may be aligned to three different faces. We use an integer to represent these cases,

```
0  yellow on U  (correct)
1  yellow on R  (120 degree clockwise)
2  yellow on F  (120 degree counterclockwise)

```

Suppose cubie `1` is on `DFL`, its three possible orientations are

```
0  yellow on D  (correct)
1  yellow on L  (120 degree clockwise)
2  yellow on F  (120 degree counterclockwise)

```

When we analyzing the orientations of edges, red and orange are ignored, and yellow and white are ignored only if the edge has a green or blue facet.

Suppose cubie `10` is on its starting position `UR`, the green facet may be aligned to two different faces. Its two possible orientations are

```
0  green on R  (correct)
1  green on U  (180 degree)

```

Suppose cubie `10` is on `DF`, its two possible orientations are

```
0  green on D  (correct)
1  green on F  (180 degree)

```

---

An array is used to store the state of a cube. The starting state of a cube is

```
{{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},{9,0},{10,0},{11,0},{12,0},{13,0},{14,0},{15,0},{16,0},{17,0},{18,0},{19,0},{20,0}}

```

which means that every cubies are on their starting position with correct orientation.

After `R`, the state of the cube becomes

```
{{5,2},{1,1},{3,0},{4,0},{6,1},{2,2},{7,0},{8,0},{9,0},{13,1},{11,0},{12,0},{18,1},{10,1},{15,0},{16,0},{17,0},{14,1},{19,0},{20,0}}

```

which means that cubie `5` is now on position `1` (`UFR`) with orientation `2`, cubie `1` is now on position `2` (`UBR`) with orientation `1`, cubie `3` is now still on position `3` (`UBL`) with orientation `0`, and so on.

---

**Test cases**

```
p["FF'"]            (* 1   *)
p["R"]              (* 4   *)
p["RUR'U'"]         (* 6   *)
p["LLUUFFUURRUU"]   (* 12  *)
p["LUFFRDRBF"]      (* 56  *)
p["LF"]             (* 105 *)
p["UFFR'DBBRL'"]    (* 120 *)
p["FRBL"]           (* 315 *)

```
> 10 votes

# Answer
# Haskell, 252 bytes

```
r=[-2..2]
s=mapM id[r,r,r]
t m p@[x,y,z]=case m of"R"|x>0->[x,z,-y];"L"|x<0->[x,-z,y];"U"|y>0->[-z,y,x];"D"|y<0->[z,y,-x];"F"|z>0->[y,-x,z];"B"|z<0->[-y,x,z];c:"'"->t[c]$t[c]$t[c]p;_->p
f m=length$s:fst(span(/=s)$tail$iterate(flip(foldl$flip$map.t)m)s)

```

Sample runs:

```
*Main> f ["F","F'"]
1
*Main> f ["R"]
4
*Main> f ["R","U","R'","U'"]
6
*Main> f ["L","L","U","U","F","F","U","U","R","R","U","U"]
12
*Main> f ["L","U","F","F","R","D","R","B","F"]
56
*Main> f ["L","F"]
105
*Main> f ["U","F","F","R'","D","B","B","R","L'"]
120
*Main> f ["F","R","B","L"]
315
*Main> f ["R","U","U","D'","B","D'"]  -- maximum possible order
1260

```

The key observation here is that it’s simpler to model the Rubik’s cube as a 5×5×5 grid of points rather than a 3×3×3 grid of oriented cubies. Corner cubies become cubes of 2×2×2 points, edge cubies become squares of 2×2×1 points, and moves rotate slices of 5×5×2 points.
> 8 votes

# Answer
# Python 2, 343 bytes

```
def M(o,v,e):
 k=1
 for m in e:
  for c in'ouf|/[bPcU`Dkqbx-Y:(+=P4cyrh=I;-(:R6'[m::6]:i=~ord(c)%8*k;j=(ord(c)/8-4)*k;o[i],o[j]=o[j]-m/2,o[i]+m/2;v[i],v[j]=v[j],v[i];k=-k
V=range(20)
o,v,e=[0]*20,V[:],[]
for c in raw_input():i='FBRLUD'.find(c);e+=i<0and e[-1:]*2or[i]
M(o,v,e);n=1
while any(o[i]%(2+i/12)for i in V)or v>V:M(o,v,e);n+=1
print n

```

Input is taken from stdin.

The given sequence of twists is performed repeatedly on a virtual cube until it returns to the solved state. The cube state is stored as an orientation vector and permutation vector, both of length 20.

Orientations are somewhat arbitrarily defined: an edge cubie is oriented correctly if it can be moved into place without invoking an R or L quarter turn. The orientation of the corner cubies is considered relative to the F and B faces.

---

**Sample Usage**

```
$ echo FRBL|python rubiks-cycle.py
315

$ echo RULURFLF|python rubiks-cycle.py
1260

```

Online Demonstration and Test Suite.
> 7 votes

# Answer
# Ruby, 225 bytes

```
->s{n=0
a=[]
b=[]
64.times{|i|a<<j=[(i&48)-16,(i&12)-4,i%4-1];b<<j*1}
d=1
(n+=1
s.reverse.chars{|c|m="UFRDBL".index(c)
m ?(e=m/3*2-1
b.each{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)}
d=1):d=-1})until n>0&&a==b
n}

```

Similar to Anders Kaseorg's answer and inspired by Jan Dvorak's answer to a previous question.

However unlike those answers, I don't need 125 cubies. I use a rubik's cube of 27 cubies, but rectangular dimensions. In the solved state the corners are at `+/-1,+/-4,+/-16`.

I generate an array of 64 cubies, each with a centre chosen from `x=[-1,0,1,2], y=[-4,0,4,8], z=[-16-0,16,32]`. The cubies with coordinates of 2, 8 and 32 are unnecessary, but they do no harm, so they are left in for golfing reasons. The fact that the length, width and depth of the cubies are different: (1,4,16) means it is easy to detect if they are in the right place but with wrong orientation.

Each cubie is tracked as it is moved by the faceturns. If the coordinate of a cubie in the axis corresponding to the face (multiplied by `e=-1` for U,F,R or `e=1` for D,B,L) is positive, then it will be rotated by swapping the coordinates in the other 2 axis and applying an appropriate sign change to one of the coordinates. This is controlled by multiplying by `e*d`.

The input sequence is scanned in reverse order. This makes no difference, so long as the "normal" rotations are performed anticlockwise instead of clockwise. The reason for this is so that if a `'` symbol is found, the value of `d` can be changed from 1 to -1 in order to cause rotation of the following face in the opposite direction.

**Ungolfed in test program**

```
f=->s{n=0                                      #number of repeats=0
  a=[]                                         #empty array for solved position
  b=[]                                         #empty array for current position
  64.times{|i|
    a<<j=[(i&48)-16,(i&12)-4,i%4-1]            #generate 64 cubies and append them to the solved array
    b<<j*1                                     #duplicate them and append to active array
  }
  d=1                                          #default rotation direction anticlockwise (we scan the moves in reverse)
  (                                            #start of UNTIL loop
    n+=1                                       #increment repeat counter
    s.reverse.chars{|c|                        #reverse list of moves and iterate through it
      m="UFRDBL".index(c)                      #assign move letter to m (for ' or any other symbol m is false)
      m ?                                      #if a letter
        (e=m/3*2-1                             #e=-1 for UFR, 1 for DBL
        b.each{|j|                             #for each cubie
          j[m%=3]*e>0&&                        #m%=3 picks an axis. If the cubie is on the moving face of the cube
         (j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)#rotate it: exchange the coordinates in the other 2 axes and invert the sign of one of them according to direction
        }                                      #as per the values of e and d.
        d=1                                    #set d=1 (in case it was -1 at the start of the b.each loop)
      ):
      d=-1                                     #ELSE the input must be a ', so set d=-1 to reverse rotation of next letter
    }
   )until n>0&&a==b                            #end of UNTIL loop. continue until back at start position a==b
n}                                             #return n

p f["FF'"]               #      1
p f["R"]                 #      4
p f["RUR'U'"]            #      6
p f["LLUUFFUURRUU"]      #     12
p f["LUFFRDRBF"]         #     56
p f["LF"]                #    105
p f["UFFR'DBBRL'"]       #    120
p f["FRBL"]              #    315

```
> 7 votes

# Answer
# Cubically, ~~9~~ 6 bytes

```
¶-7)8%

```

Try it online! (Nonworking until Dennis updates the TIO Cubically interpreter)

Explanation:

```
¶-7)8%
¶       read a string, insert into code
 -7     add 1 to notepad (subtracts the 7th face "sum" from notepad, defaulted to -1)
   )8   jump back to start of code if cube unsolved
     %  print notepad

```

This language will dominate all challenges \>:D
> 5 votes

# Answer
## Clojure, 359 bytes

This might be my 2nd longest codegolf. Realizing I could drop trailing zeros from vectors `A` to `F` made me very happy :D

```
#(let[I(clojure.string/replace % #"(.)'""$1$1$1")D(range -2 3)S(for[x D y D z D][x y z])A[0 1]B[0 0 1]C[1]D[-1]E[0 -1]F[0 0 -1]](loop[P S[[n R]& Q](cycle(map{\F[A[B A D]]\B[E[F A C]]\L[D[C B E]]\R[C[C F A]]\U[B[E C B]]\D[F[A D B]]}I))c 0](if(=(> c 0)(= P S))(/ c(count I))(recur(for[p P](if(>(apply +(map * n p))0)(for[r R](apply +(map * r p)))p))Q(inc c)))))

```

Less golfed:

```
(def f #(let [I (clojure.string/replace % #"(.)'""$1$1$1")
              D [-2 -1 0 1 2]
              S (for[x D y D z D][x y z])
              L   {\F [[ 0  1  0][[0  0  1][ 0 1  0][-1  0 0]]]
                   \B [[ 0 -1  0][[0  0 -1][ 0 1  0][ 1  0 0]]]
                   \L [[-1  0  0][[1  0  0][ 0 0  1][ 0 -1 0]]]
                   \R [[ 1  0  0][[1  0  0][ 0 0 -1][ 0  1 0]]]
                   \U [[ 0  0  1][[0 -1  0][ 1 0  0][ 0  0 1]]]
                   \D [[ 0  0 -1][[0  1  0][-1 0  0][ 0  0 1]]]}]
          (loop [P S c 0 [[n R] & Q] (cycle(map L I))]
            (if (and (> c 0) (= P S))
              (/ c (count I))
              (recur (for[p P](if(pos?(apply +(map * n p)))
                                (for[r R](apply +(map * r p)))
                                p))
                     (inc c)
                     Q)))))

```

This simply implements 3D rotations of selected subsets of `5 x 5 x 5` cube. Originally I was going to use `3 x 3 x 3` and it took me a while to realize why I wasn't getting correct results. Good test cases! Some extra bytes for fist encoding `"RUR'U'"` as `"RURRRUUU"`.
> 3 votes

# Answer
# Clean, 255 bytes

Derived separately from the almost-identical Haskell answer as an answer to this question which was closed as a duplicate when it was almost finished, so I posted the answer here.

```
import StdEnv,StdLib
a=[-2..2];b=diag3 a a a
?m=iter(size m*2-1)\p=:(x,y,z)=case m.[0]of'F'|z>0=(y,~x,z);'U'|y>0=(~z,y,x);'R'|x>0=(x,z,~y);'B'|z<0=(~y,x,z);'D'|y<0=(z,y,~x);'L'|x<0=(x,~z,y);_=p
$l=length(takeWhile((<>)b)(tl(iterate(map(sseq(map?l)))b)))+1

```

Try it online!
> 1 votes

---
Tags: code-golf, abstract-algebra, rubiks-cube
---


title: Remove indentation

text:
# Question
Title: Remove indentation
Write a program which removes any common leading spaces from the input string. For example, if the *least* indented line started with 3 spaces, and every other line has `>=` 3 leading spaces, then remove 3 spaces from the beginning of each line.

The indentation consists solely of spaces, and the string will not contain any tabulation. This is the same as the `textwrap.dedent` function in python.

Example (input, output):

### Input

```
       7aeiou
   3b
     555

```

### Output

```
    7aeiou
3b
  555

```

### Input

```
this
 is
  a
   test

```

### Output

```
this
 is
  a
   test

```

### Input

```
    Hello
 world

```

### Output

```
   Hello
world

```

# Answer
# Perl 6, 11 bytes

```
*.indent(*)

```

Try it online!
> 0 votes

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