22
\$\begingroup\$

A simple way to scramble a 2x2x2 Rubik's cube is to make a sequence random moves. This is not how official scrambles are done, but can get pretty close to a uniform distribution of all possible scramble states. Due to the way a 2x2 only has two layers, doing one turn on one face is equivalent (without considering the puzzle's orientation in space) to doing the same direction turn on the opposite face. For example, turning the top face clockwise moves all the pieces in relation to each other the same way turning the bottom face clockwise does. So scrambles only need to turn the top (U), right (R), and front (F) faces.

For this challenge, your program must generate a string that represents a sequence of 16 moves. A move is represented by a face, one of the letters U, R, F, followed by a direction: clockwise (empty string or space ), counterclockwise (apostrophe '), or 180 degrees (2). The turn and direction should be chosen uniformly at random, however two consecutive moves cannot turn the same face, For example a scramble cannot contain R' R2. So the first move should have a 1/3 chance for each face, but there should be a 50/50 chance for the chosen face after the first move. Moves are separated by a space.

Example scramble:

U  F' R2 F' R' F  R  F2 U' F  R2 F  U2 F' U2 F2 
\$\endgroup\$
10
  • 1
    \$\begingroup\$ Can we output an array of moves? \$\endgroup\$ – ophact May 13 at 8:02
  • 1
    \$\begingroup\$ @ophact since I tagged it string, I'm gonna say no. \$\endgroup\$ – qwr May 13 at 8:05
  • 1
    \$\begingroup\$ Can we use lowercase instead of uppercase? \$\endgroup\$ – Shaggy May 13 at 8:18
  • 3
    \$\begingroup\$ @Shaggy no. Lower case has a different meaning in cubing notation and doesn't make sense for 2x2 scrambles. \$\endgroup\$ – qwr May 13 at 8:20
  • 3
    \$\begingroup\$ Are we allowed to put the direction before the move, e.g. F 2R 'U 'R? \$\endgroup\$ – Aaron Miller May 13 at 13:56

18 Answers 18

8
\$\begingroup\$

Python 3.8, 84 83 82 bytes

-2 bytes thanks to dingledooper!

import random as R
print(*[(R:=c([*{*"FUR"}-{R}]))+c(" '2")for c in[R.choice]*16])

Try it online!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ interesting. how does the id trick work. edit: oh I see it has nothing to do with the id function itself \$\endgroup\$ – qwr May 13 at 8:47
  • \$\begingroup\$ @qwr Yeah it is just a variable that is predefined and short (and hashable). In this case x=c=choice and using x instead of id would be the same length. \$\endgroup\$ – ovs May 13 at 8:50
  • 1
    \$\begingroup\$ -1 byte \$\endgroup\$ – dingledooper May 13 at 8:59
  • \$\begingroup\$ @dingledooper Very nice, thanks! I had the feeling the eval('...,'*16) was not quite optimal since I haven't seen it on this site before. \$\endgroup\$ – ovs May 13 at 9:04
  • 1
    \$\begingroup\$ I found another nice trick which saves 1 byte. \$\endgroup\$ – dingledooper May 13 at 9:28
6
\$\begingroup\$

05AB1E, 19 bytes

16Fн…FRUsK… '2âΩð«?

Try it online!

16F                  # iterate 16 times:
   н                 # get the first character from the value that was last on stack
    …FRU             # push string "FRU"
        sK           # remove the result from н
          … '2       # push string " '2"
              â      # cartesian product of the strings
               Ω     # choose a random string from the list
                ð«   # append a space
                  ?  # print without a trailing newline

Ô - Connected uniquified a seems like a promising builtin for this challenge, but the best I could do with it is 21 bytes:

…FRUÞ€ΩÔ16£ε… '2Ω«}ðý

Try it online!

…FRUÞ                  # infinite list ["FRU", "FRU", ... 
     €Ω                # select a random character from each string
       Ô               # remove consecutive duplicates
        16£            # take the first 16 characters
           ε      }    # for each of those:
            … '2Ω«     # append a random char from " '2"
                   ðý  # join the resulting list by spaces
\$\endgroup\$
5
\$\begingroup\$

Vyxal, 35 29 25 19 bytes

16(h‛⊍Ṁ⇧$-` '2`Ẋ℅¨…

Try it Online!

Thanks to Lyxal for -6 bytes.

16(                 # Repeat 16 times (Automatically closed)
   h                # Take first of previous
    ‛⊍Ṁ⇧            # Push `fru`, uppercased
        $           # Swap top two elements on stack
         -          # Remove (So fru loses the first of previous iteration)
          ` '2`     # Push ` '2`
               Ẋ    # Cartesian product
                ℅   # Random choice
                 ¨… # No idea (Can't find any docs)

My old version, 25 bytes

16(‛Ŀ¦⇧'¥≠;℅:£`'2 `℅+⅛)¾Ṅ

Try it Online!

16(                   )   # 16 times
   ‛Ŀ¦⇧                   # Push compressed string `fur`, to uppercase
       '  ;               # Filter by...
        ¥≠                # is not equal to register
           ℅              # Random choice
            :£            # Duplicate and push to register
              `'2 `℅      # Random of `'2 `
                    +     # Concatentated
                     ⅛    # Push to global array
                       ¾  # Push global array to stack
                        Ṅ # Join by space

I know this is a mess. Also this seems to be the only one that compresses even one of the strings.

\$\endgroup\$
2
  • \$\begingroup\$ Try it Online! for 21 bytes (by stealing the 05ab1e answers method) \$\endgroup\$ – lyxal May 13 at 11:45
  • \$\begingroup\$ 19 bytes \$\endgroup\$ – lyxal May 13 at 12:21
3
\$\begingroup\$

Charcoal, 18 bytes

F¹⁶«≔‽⁻FRUωωω‽ 2'→

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

F¹⁶«

Repeat 16 times.

≔‽⁻FRUωω

Choose a random turn that wasn't just used.

ω

Output that turn.

‽ 2'

Output a random direction.

Except for the last move, leave a space for the next move.

\$\endgroup\$
3
\$\begingroup\$

Retina, 50 bytes

$
¶FRU¶ 2'
(([FRU])¶.¶.*)\2
$1
16}%@L`.
¶

|' L`..

Try it online! Explanation:

$
¶FRU¶ 2'

Append the possible turns and directions.

(([FRU])¶.¶.*)\2
$1

Remove the turn that was made the last time.

%@L`.

Pick a random turn and direction from those left.

16}`

Repeat the above 16 times.

Join everything together.

|' L`..

Add spaces between the moves.

\$\endgroup\$
3
\$\begingroup\$

Factor, 83 bytes

[ [ "UFR"""16 [ over remove random dup , "2 '"random , 32 , ] times ] ""make 2nip ]

Try it online!

One of the odd times make is shorter than sequence words (or smart combinators like append-outputs). Mainly because turning code points into strings is verbose in Factor, but make, despite being verbose itself, can do that with ease. Plus, , is much shorter than suffix or append.

Explanation:

It's a quotation (anonymous function) that takes no input and leaves a string on the data stack as output.

  • [ ... ] ""make Make a string. Inside the quotation, , appends elements to a sequence. The "" is an exemplar that tells make the result should be a string.
  • "UFR""" Place two strings on the stack. The first, "UFR", indicates which possible faces we can choose. The second, "", is the last face we chose, so we don't choose it twice in a row.
  • 16 [ ... ] times Call a quotation 16 times.
  • over remove random Pick a random face that we didn't pick last time.
  • dup , Append it to our sequence without destroying it (since we need to know our last move again).
  • "2 '" random , Append a random direction/move to the face.
  • 32 , Append a space.
  • 2nip Once make is done building the string, we still have some junk on the data stack to remove.
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6),  82 81  79 bytes

f=i=>i>>10?"":"FRU"[(i=~~i-Math.random()*~-~!i)%3|0]+" '2"[i*3%3|0]+" "+f(i+64)

Try it online!

Or run a consistency check on 500,000 calls

How?

We start with \$i=0\$. [1]

At each iteration, we add to \$i\$ a random float in \$\left[0,3\right[\$ if \$i=0\$ (3 possible choices) or in \$\left[0,2\right[\$ if \$i\neq 0\$ (only 2 possible choices).

We use \$\lfloor i\bmod 3 \rfloor\$ as the index of the face character and \$\lfloor (3\times i)\bmod 3 \rfloor\$ as the index of the direction character.

After each iteration[1], we update \$i\$ to \$\lfloor i+64 \rfloor\$ in order to:

  • get rid of the decimal part whose only purpose was to to choose a direction character
  • make sure that we won't pick the same face character twice in a row (because \$64 \bmod3=1\$)
  • be able to know that we've processed 16 iterations by testing if \$i\$ is greater than or equal to \$1024\$, because we add at least \$16\times64=1024\$ to \$i\$ (and at most \$16\times65+1=1041\$)

[1] in order to save a few bytes, we actually start with \$i\$ undefined, coerce it to a number at the very beginning of an iteration, and add \$64\$ at the end.

\$\endgroup\$
2
\$\begingroup\$

GolfScript, 41 bytes

16,{;'FRU'[a]-.,rand=:a" '2"3rand=32}%""+

Try It Online!

Explanation

16,{;'FRU'[a]-.,rand=:a" 'r"3rand=32}%""+
16,                                        // push the list [0..15]
   {                                       // begin code block
    ;                                      // remove the element already in the list
     'FRU'[a]-                             // remove the previous value of a from the possible choices
                                              (initially, [a] evaluates to an empty list as a is undefined)
              .,rand=                      // push the length of the string, and index the string to a 
                                              random integer in this range
                     :a                    // set a to this value for the next iteration
                       " 'r"               // push " 'r"
                            3rand=         // index the string to a random position
                                  32}      // push the ASCII value for ' ', and end the block
                                     %     // map the block over the list [0..15]
                                      ""+  // convert the resulting list of ASCII values into a string
                                           // the string is output implicitly
\$\endgroup\$
1
\$\begingroup\$

Haskell, 114 bytes

(' '?16!!)<$>randomRIO(0,9*6^15-1)
_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]
import System.Random

Try it online! (times out for obvious reasons, you can test it out here with 8 moves).

The relevant "function" is (' '?16!!)<$>randomRIO(0,9*6^15-1), an IO String object "containing" a random sequence of moves.

As always, solving challenges in Haskell is a great idea.

How?

_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]

(?) is a pure function taking a character c and an integer n as input and returning the list of all valid sequences of moves of length n such that the first move is not c.


(' '?16!!)<$>randomRIO(0,9*6^15-1)

randomRIO(0,9*6^15-1) generates a random integer in the range (0,9*6^15-1); incidentally, 9*6^15 is exactly the number of valid sequences of length 16. Then with (' '?16!!)<$> we use this random integer to index into ' '?16, which is the list of valid sequences of length 16.

\$\endgroup\$
1
\$\begingroup\$

Japt -S, 20 19 bytes

Would be 17 if we could output the pairs reversed and in lowercase.

GÆ="RUF"kU ï" '2" ö

Test it or run it 100 times
or verify that the same move isn't used twice in a row over 100 runs

GÆ="RUF"kU ï" '2" ö
G                        :16
 Æ                       :Map the range [0,G)
  =                      :  Assign to variable U (initially 0)
   "RUF"                 :  String literal
        kU               :  Remove characters in U
           ï" '2"        :  Cartesian product with " '2"
                  ö      :  Random element of resulting array
                         :Implicit output joined with spaces
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 63 61 bytes

"$(1..16|%{($l='R','U','F'-ne$l|random)+("'",' ',2|random)})"

Try it online!

Technically, a 60-byte solution works by using an empty string rather than a space to the second random selection; however, an error is thrown each time the empty element is selected.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ nice previous check \$\endgroup\$ – mazzy May 13 at 18:37
1
\$\begingroup\$

J, 46 bytes

3 :0
,'URF 2'''{~3(,3,~?@3-3:)@|+/\1+?3,15$2
)

Try it online!

Surprisingly verbose.

The only part of this I liked was the code to pick the random faces:

3|+/\1+?3,15$2

Here we create the 16 element list:

3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

Then "roll" ? for each element (so pick randomly among 0 1 2 for the first element, and among 0 1 for the second), then scan sum the result +/\, then mod by 3 3|.

tacit version, also 46

[:,'URF 2'''{~3(,3,~?@3-3:)@|?@3+/\@,1+15?@$2:

But I think the explicit version is easier to read, since if you discount the boilerplate 3 :0 and ) it is effectively fewer bytes.

\$\endgroup\$
1
\$\begingroup\$

Raku, 54 bytes

(<F R U>.roll(*).squish Z~"2' ".comb.roll(*))[^16].put

Try it online!

  • Uses squish to get rid of consecutive face repeats
  • Z~ metaoperator zips the two lists, then concatenates the resulting pairs
  • comb makes light work of the literal space requirement

While golfing I found other interesting Raku features that are worth highlighting:

Alternative, 86 bytes

((<F R U>.roll,{{:F<R U>,:R<F U>,:U<F R>}{$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put

Try it online!

  • Compact pair literal syntax within sequence generator to determine valid next cube face

Alternative, 94 bytes

my@m=<F R U>;((@m.roll,{%(@m.map:{$_=>(@m∖$_)}){$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put

Try it online!

  • Uses set difference operator to exclude key from @m when creating key-value pairs
\$\endgroup\$
3
  • \$\begingroup\$ can you use $_ in place of $^a? \$\endgroup\$ – Razetime May 15 at 15:13
  • \$\begingroup\$ also, you can use '' instead of ' ' for -1 \$\endgroup\$ – Razetime May 15 at 15:14
  • \$\begingroup\$ $_ is indeed equivalent \$\endgroup\$ – Zaid May 15 at 22:09
0
\$\begingroup\$

JavaScript (Node.js), 83 bytes

f=(p='',g=s=>s[0][Math.random()*3|0],a=g`URF`)=>p[47]?p:f(p[0]==a?p:a+g` '2`+' '+p)

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ An IIFE saves a byte: tio.run/… \$\endgroup\$ – Shaggy May 13 at 10:42
  • \$\begingroup\$ Or call f with backticks instead of parentheses to save 4 more: tio.run/##Dcq7DoIwFIDhV@lGa5HgJTEBD2xuLiZOTZMeLsUapCctcfLdK8ufb/… Although, I don't know if we have a consensus on whether or not that's allowed. \$\endgroup\$ – Shaggy May 13 at 10:43
  • \$\begingroup\$ And you can ditch the assignment to b completely and just call g in the recursive call to f. \$\endgroup\$ – Shaggy May 13 at 10:45
  • \$\begingroup\$ @Shaggy Thanks for point out removing b would save some bytes. But I'm not sure if invoke f with backticks is allowed since it seems taking extra parameters. \$\endgroup\$ – tsh May 13 at 10:58
  • \$\begingroup\$ @Shaggy And IIFE seems a expression, which is neighter a function nor full program. \$\endgroup\$ – tsh May 13 at 11:06
0
\$\begingroup\$

JavaScript, 101 99 91 bytes

f=(i=s=17,m=Math.random)=>--i?'URF'[s=(s>3?m()*3:s+1+m()*2)%3|0]+" '2"[m()*3|0]+' '+f(i):''

Try it online.

Explanation

We start with i and s both set to 17, then each iteration, if subtracting one from i yields a positive integer, we get the face character using a simple ternary and add a random direction character and then add a recursive call to f with the newly decremented i, and otherwise we simply return an empty string.

\$\endgroup\$
2
  • \$\begingroup\$ doesn't make a difference for length but you should use capital letters per the spec. \$\endgroup\$ – qwr May 13 at 8:11
  • \$\begingroup\$ @qwr oops, sorry \$\endgroup\$ – ophact May 13 at 8:13
0
\$\begingroup\$

Java, 157 bytes

$->{for(char i=16,c=0,j=3;i-->0;j=2)System.out.format("%c%c ",c="URF".replace(c+"","").charAt((int)(Math.random()*j))," '2".charAt((int)(Math.random()*3)));}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Jelly, 23 bytes

“FUR“ '2”Wẋ⁴ŻṖḟ@"X€ɗ\ḊK

Try it online!

A full program that prints a 16-long scramble.

Explanation

“FUR“ '2”               | ["FUR"," '2"]
         W              | Wrap in a further list
          ẋ⁴            | Repeat 16 times
            Ż           | Prepend a zero
                   ɗ\   | Reduce using the following as a dyad, keeping intermediate values:
             Ṗ          | - Remove last item
              ḟ@"       | - Filter out this from the next incoming copy of the list (but because of the Ṗ and ", this will only affect the FUR part)
                 X€     | - Randomly pick a value for each
                     Ḋ  | Remove the first value (the zero)
                      K | Separate with spaces
                        | (Implicitly) print
\$\endgroup\$
0
\$\begingroup\$

Python 3.8 (pre-release), 107 106116 bytes

Basic randoms

-1 bytes to @qwr's space

-1 bytes to @razetime's space

+11 bytes to randomize starting n

from random import*;n=randint(0,2);print(' '.join(['RFU'[(n:=(n+randint(1,2))%3)]+choice("' 2")for i in range(16)]))

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ if you do %3 you can get rid of the -3 right \$\endgroup\$ – qwr May 13 at 8:07
  • \$\begingroup\$ and the space before for \$\endgroup\$ – qwr May 13 at 8:08
  • \$\begingroup\$ @qwr At the time of you commenting, I also came up with same thought, lol \$\endgroup\$ – okie May 13 at 8:09
  • \$\begingroup\$ can the program output a scramble starting with R? it must be able to uniformly pick any of the three moves for the first move. \$\endgroup\$ – qwr May 13 at 8:09
  • 2
    \$\begingroup\$ from random import*; for -1 \$\endgroup\$ – Razetime May 13 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.