# Question
Title: Alternatively shift columns and rows of a 2D array
### Objective

Given a 2D array of any size, write a program or function to shift alternatively the columns and rows

### Example

```
a b c d e
f g h i j
k l m n o

```

All elements in the **first** column shift **down** one row, the **second** column shift **up** one row, the **third** shift **down** one row and so on, wrapping when they reach the edge.

```
k g m i o
a l c n e
f b h d j

```

All elements in the **first** row shift to the **right**, the **second** to to the **left**, the **third** to the **right** etc., wrapping when they reach the edge.

```
o k g m i
l c n e a
j f b h d

```

I will follow the tradition of selecting the shortest working code as the best answer

# Answer
> 3 votes
# Husk, 7 bytes

```
‼ozṙİ_T

```

Try it online!

## Explanation

```
‼ozṙİ_T  Implicit input: a list of lists.
‼        Do this twice:
      T   Transpose,
 oz       then zip with
    İ_    the infinite list [-1,1,-1,1,-1,1,..
   ṙ      using rotation. This rotates the rows in alternating directions.

```

# Answer
> 7 votes
# MATL, 13 bytes

```
,!tZy:oEq2&YS

```

**Try it online!**

### Explanation

```
,        % Do twice
  !      %   Transpose. Takes input implicitly the first time
  t      %   Duplicate
  Zy     %   Size. Gives a vector with numbers of rows and of columns
  :      %   Range from 1 to the first entry of the vector (number of rows)
  o      %   Parity: gives 0 or 1 for eacn entry
  Eq     %   Times 2, minus 1: transforms 0 into -1
  2      %   Push 2
  &YS    %   Circularly shift along the second dimension. This shifts the
         %   first row by 1 (that is, to the right), the second by -1 (to
         %   the left), etc.
         % End (implicit). Display (implicit)

```

# Answer
> 6 votes
# , 26, 21 19 bytes

-5 bytes thanks to miles

```
(|."_1~_1^#\)@|:^:2

```

## Explanation:

`^:2` \- repeate twice the following:

`@|:` \- transpose and

`#\` \- find the length ot the prefixes (1, 2, 3 ... rows)

`_1^` \- raise -1 to the above powers, creating a list of alternating -1 1 -1 1...

`|."_1~` \- rotate each row of the input array with offset from the above list

Try it online!

## Original version:

```
(($_1 1"0)@#|."0 1])@|:^:2

```

## How it works

`^:2` \- repeate twice the following:

`|:` \- transpose and

`|."0 1]` \- rotate each row of the input array, offsets in the list:

`@#` \- the number of rows in the array

`($_1 1"0)` \- alternate \_1 1 (3 -\> \_1 1 \_1)

Try it online!

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

```
Nest[MapIndexed[RotateLeft[#,(-1)^#2]&,Thread@#]&,#,2]&

```

Try it online!

# Answer
> 3 votes
# Python 2, 83 bytes

```
x=input()
exec'x=[l[i%2*2-1:]+l[:i%2*2-1]for i,l in enumerate(zip(*x))];'*2
print x

```

Try it online!

# Answer
> 2 votes
# APL+WIN, 30 bytes

Prompts for screen input of a 2d array

```
((↑⍴m)⍴¯1 1)⌽((1↓⍴m)⍴¯1 1)⊖m←⎕

```

# Answer
> 2 votes
# JavaScript (ES6),  ~~116~~  76 bytes

```
m=>(g=m=>m[0].map((_,x)=>m.map(_=>m[y++%h][x],h=m.length,y=x&1||h-1)))(g(m))

```

Try it online!

### Commented

```
m => (                 // m[] = input matrix
  g = m =>             // g is the main helper function taking a matrix m[]
    m[0].map((_, x) => // for each column at position x in m[]:
      m.map(_ =>       //   for each row of m[]:
        m[y++ % h][x], //     yield the x-th value of the row (y mod h) and increment y
        h = m.length,  //     h = number of rows
        y = x & 1      //     start with y = 1 if x is odd,
            || h - 1   //     or h - 1 if x is even
      )                //   end of inner map()
  )                    // end of outer map()
)(g(m))                // invoke g twice on the input matrix

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 26 bytes

```
{(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵}

```

Try it online!

Prefix Dfn.

### How?

```
{(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵}⍝ Main function, prefix. Input matrix is ⍵.
                        ⊖⍵}⍝ Rotate the columns of ⍵ according to the left arg:
            (       ⍉⍵)    ⍝ Transpose ⍵ (makes a 3x5 matrix become 5x3)
                   ≢       ⍝ Tally (yields the number of rows of the matrix)
                  ⍨        ⍝ Swap arguments of the following fn/op
                 ⍴         ⍝ Shape
             ¯1 1          ⍝ This vector. This yields a vector of ¯1 1 with size = number of columns of ⍵.
          ⌽                ⍝ Rotate the rows of ⍵ according to the left arg:
{(¯1 1⍴⍨≢⍵)                ⍝ Does the same as the preceding expression, without transposing ⍵.

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 15 bytes (SBCS)

```
{⍵⌽⍨¯1*⍳≢⍵}∘⍉⍣2

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), ~~94~~ 91 bytes

```
a=>(g=a=>a[0].map((_,i)=>(b=a.map(a=>a[i]),i%2?[...b.slice(1),b[0]]:[b.pop(),...b])))(g(a))

```

There's probably a golfier way to do the rotation...

# Answer
> 2 votes
# Pyth, 15 bytes

```
L.e.>b^_1k.Tbyy

```

Try it online

### Explanation

```
L.e.>b^_1k.Tbyy
L           b      Define a function on a list...
          .T       ... which transposes it...
 .e.>b^_1k         ... and rotates each row alternating left and right.
             yyQ   Apply twice to the (implicit) input array.

```

# Answer
> 2 votes
# q/kdb+, 32 bytes

**Solution:**

```
{rotate'[#:[x+:]#-1 1](+)x}/[2;]

```

**Example:**

```
q)3 5#.Q.a / reshape "a..o" into 3 row, 5 column grid
"abcde"
"fghij"
"klmno"
q){rotate'[#:[(+)x]#-1 1](+)x}/[2;]3 5#.Q.a
"okgmi"
"lcnea"
"jfbhd"

```

**Explanation:**

Flip the grid in order to apply rotation to **columns**, the second iteration flips once again thus the rotation is applied to the **rows** on the second pass.

Rotation is based a the list `-1 1 -1 1..` of the length of the row/column being rotated.

A healthy **9 bytes** have been golfed off from this *easier-to-read* version

```
{rotate'[count[flip x]#-1 1;flip x]}/[2;] / ungolfed solution
{                                  }/[2;] / perform lambda 2 times
 rotate'[                  ;      ]       / perform rotate on each-both
                            flip x        / flip x<->y of grid
                      #-1 1               / take from list -1 1
         count[flip x]                    / the length of the flipped grid

```

# Answer
> 1 votes
# Jelly, 10 bytes

```
ZJ-*ṙ"@Zµ⁺

```

Try it online!

# Answer
> 1 votes
# Clean, 93 bytes

```
import StdEnv,StdLib
k=[0,1:k]
^l=[[[last a:init a],tl a++[hd a]]!!b\\a<-transpose l&b<-k]

```

#

```
^o^

```

As a partial function literal, that happens to look like a face.

Try it online!

# Answer
> 0 votes
# 05AB1E, 14 bytes

```
2FøvyNÉiÀëÁ}})

```

Try it online!

**Explanation**

```
2F               # 2 times do:
  ø              # zip
   vy            # for each row(y), index(N) do:
     NÉiÀ        # if N is odd, rotate left
         ëÁ      # else rotate right
           }}    # end if and inner loop
             )   # wrap in list

```

# Answer
> 0 votes
# APL NARS, 36 bytes, 18 chars

```
c←b∘b←{⍵⌽⍨-×-\⍳≢⍵}∘⍉

```

This {⍵⌽⍨-×-\⍳≢⍵} would rotate each row of the matrix argument follow the vector -1 1 -1 1 etc(that has its vector length the length of the argument matrix rows). Test:

```
  ⎕←a←3 5⍴⎕A
ABCDE
FGHIJ
KLMNO
  ⎕←c a
OKGMI
LCNEA
JFBHD

```

# Answer
> 0 votes
## bash et al, 84

Non-competing shell solution.

This is based around a function that alternates the direction of the rotation of the rows. The same procedure done on the transposed array will rotate the columns. For example `transpose | rotate | transpose | rotate`.

The alternating rotation can be done on single character arrays with `sed` like this:

```
sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/'

```

The transposition can be done with `rs` or `datamash`:

```
rs -g1 -T
datamash -t' ' transpose

```

Taken together:

```
r() { sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/'; }
t() { rs -g1 -T; }
<f t | r | t | r

```

Output:

```
o k g m i
l c n e a
j f b h d

```

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


title: Find The Rank Of A Word

text:
# Question
Title: Find The Rank Of A Word
## Definition

The rank of a word is defined as the position of the word when all the possible permutations (or arrangements) of its letters are arranged alphabetically, like in a dictionary, no matter if the words are meaningful or not.

Let us consider these two words - "blue" and "seen". To begin with, we would write all the possible arrangements of the letters of these words in alphabetical order:

```
"blue": "belu","beul","bleu","blue","buel","bule","eblu","ebul","elub","elbu","eubl",
        "eulb","lbeu","lbue","lebu","leub","lube","lueb","ubel","uble","uebl","uelb",
        "ulbe","uleb"
"seen": "eens","eesn","enes","ense","esen","esne","nees","nese","nsee","seen",
        "sene","snee"

```

Now let's look from the left and find the position of the words we need. We see that the word "blue" is at the 4th position and "seen" is at 10th position. So the rank of the word "blue" is 4, and that of "seen" is 10. This is the general way of calculating the rank of a word. Make sure you start counting from 1 only.

## Task

Your task is to write a code to take any word as an input and display its rank. The rank should be the output. Be careful about words containing repeated letters.

## Examples

```
"prime" -> 94

"super" -> 93

"bless" -> 4

"speech" -> 354

"earth" -> 28

"a" -> 1

"abcd" -> 1

"baa" -> 3

```

You can assume the input to be completely in lowercase and the input will only contain **alphabetical characters**. Also if a blank space or an invalid string is entered, you may return anything.

## Scoring

This is , so the shortest code wins!

# Answer
# Gaia, 4 bytes

```
fuȯI

```

Try it online!
> 5 votes

# Answer
# Python 3, 71 bytes

```
lambda s:sum(t<=(*s,)for t in{*permutations(s)})
from itertools import*

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 5 bytes

```
œêsk>

```

Try it online! or as a Test suite

**Explanation**

```
œ       # get permutations of input
 ê      # sort and remove duplicates
  s     # swap input to top of stack
   k    # get index of input in the list
    >   # increment

```
> 6 votes

# Answer
# Pyth, 6 bytes

```
hxS{.p

```

**Test suite.**

## Explanation

```
hxS{.p || Full program.

    .p || All the permutations of the input.
   {   || Deduplicate.
  S    || Sort.
 x     || Index of the input into this list.
h      || Increment.

```
> 4 votes

# Answer
# Jelly, 5 bytes

```
Œ!ṢQi

```

Try it online! or see the **test suite**

## How it works

```
Œ!ṢQi - Main link. Argument: s (string)      e.g. 'baa'
Œ!    - All permutations                          ['baa', 'baa', 'aba', 'aab', 'aba', 'aab']
  Ṣ   - Sort                                      ['aab', 'aab', 'aba', 'aba', 'baa', 'baa']
   Q  - Deduplicate                               ['aab', 'aba', 'baa']
    i - 1-based index of s                        3

```
> 3 votes

# Answer
# Python 2, 78 bytes

```
lambda s:-~sorted(set(permutations(s))).index(tuple(s))
from itertools import*

```

Try it online!

---

# Python 3, 73 bytes

* Thanks to Mr. Xcoder for choosing Python 3; saving five bytes.

```
lambda s:-~sorted({*permutations(s)}).index((*s,))
from itertools import*

```

Try it online!
> 3 votes

# Answer
# Haskell, 56 bytes

```
import Data.List
elemIndex<*>([]:).nub.sort.permutations

```

Try it online!

+6 bytes because of 1-indexing requirement. :(
> 3 votes

# Answer
# CJam, 8 bytes

```
q_e!\a#)

```

Try it online!

+1 byte due to 1-indexed requirement.
> 3 votes

# Answer
# Japt, ~~8~~ 10 bytes

~~0-indexed.~~ Poxy, unnecessary 1-indexing, increasing my byte count by 25%!

```
á â n bU Ä

```

Test it

---

## Explanation

`á` gets all the permutations of the input, `â` removes duplicates, `n` sorts them and `b` gets the index of the first occurrence of the input, `U`.
> 2 votes

# Answer
# Husk, 6 bytes

```
S€(OuP

```

Try it online! I feel like there should be a way to drop `(`.

**Explanation:**

```
 €     -- return index of the input
S (    -- in the list generated by applying the following functions to the input:
     P -- permutations
    u  -- remove duplicates
   O   -- sort

```
> 2 votes

# Answer
# , 28 23 bytes

-5 bytes thanks to FrownyFrog

```
1+/:~@~.@(A.~i.@!@#)i.]

```

## How it works?

```
                      ] - the argument
         (A.~      )    - permutations in the
             i.@!@#     - range 0 to factorial of the arg. length
  /:~@~.@               - remove duplicates and sort
                    i.  - index of arg. in the sorted list
1+                      - add 1 (for 1-based indexing)

```

Try it online!
> 2 votes

# Answer
# Tcl, 196 bytes

```
proc p {a p} {if {$a eq {}} {lappend ::p $p} {while {[incr n]<=[llength $a]} {p [lreplace $a $n-1 $n-1] $p[lindex $a $n-1]}}}
p [split $argv ""] ""
puts [expr [lsearch [lsort -unique $p] $argv]+1]

```

Tcl has no built-in method to compute the next lexicographic permutation, so we have to do it ourselves. But wait... it is *shorter* to do it with a simple recursive function that computes *all* possible permutations in any order.

Ungolfed:

```
# Compute all possible permutations of the argument list
# Puts the result in ::all_permutations
proc generate_all_permutations {xs {prefixes ""}} {
  if {$xs eq {}} {
    lappend ::all_permutations $prefixes
  } else {
    while {[incr n] <= [llength $xs]} {
      generate_all_permutations [lreplace $xs $n-1 $n-1] $prefixes[lindex $xs $n-1]
    }
  }
}

# Get our input as command-line argument, turn it into a list of letters
generate_all_permutations [split $argv ""]

# Sort, remove duplicates, find the original argument, and print its 1-based index
puts [expr [lsearch [lsort -unique $all_permutations] $argv]+1]

```
> 2 votes

# Answer
# K (oK), ~~23~~ 18 bytes

**Solution:**

```
1+*&x~/:?x@prm@<x:

```

Try it online!

**Examples:**

```
1+*&x~/:?x@prm@<x:"seen"
10
1+*&x~/:?x@prm@<x:"blue"
4

```

**Explanation:**

Generate permutations of the indices of the sorted input string, use them to index back into the input string, take the distincts, see where the original string matched, and add one.

```
1+*&x~/:?x@prm@<x: / the solution
                x: / save input string as x
               <   / return indices when sorting x ascending
           prm@    / apply (@) function prm
         x@        / index into x with these permutations
        ?          / distinct (remove duplicates)
    x~/:           / apply match (~) between x and each-right (/:)
   &               / return indexes where true (ie the match)
  *                / take the first one
1+                 / add 1 due to 1-indexing requirement

```
> 2 votes

# Answer
# Java 8, 211 bytes

```
import java.util.*;TreeSet q=new TreeSet();s->{p("",s);return-~q.headSet(s).size();}void p(String p,String s){int l=s.length(),i=0;if(l<1)q.add(p);for(;i<l;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,l)));}

```

**Explanation:**

Try it online.

```
import java.util.*;        // Required import for TreeSet

TreeSet q=new TreeSet();   // Sorted Set on class-level

s->{                       // Method with String parameter and integer return-type
  p("",s);                 //  Save all unique permutations of the String in the sorted set
  return-~q.headSet(s).size();}
                           //  Return the 0-indexed index of the input in the set + 1

void p(String p,String s){ // Separated method with 2 String parameters and no return-type
  int l=s.length(),        //  The length of the String `s`
      i=0;                 //  Index integer, starting at 0
  if(l<1)                  //  If String `s` is empty
    q.add(p);              //   Add `p` to the set
  for(;i<l;                //  Loop from 0 to `l` (exclusive)
    p(                     //   Do a recursive call with:
      p+s.charAt(i),       //    `p` + the character at the current index of `s` as new `p`
      s.substring(0,i)+s.substring(++i,l)));}
                           //    And `s` minus this character as new `s`

```
> 2 votes

# Answer
# Python 3, ~~183~~ 182 bytes

The first answer that run in polynomial time!

```
a=[*map(ord,input())]
f=lambda x:x and x*f(x-1)or 1
c=[0]*98
for C in a:c[C]+=1
l=len(a)
F=f(l)
for i in c:F//=f(i)
r=1
for x in a:F//=l;l-=1;r+=sum(c[:x])*F;F*=c[x];c[x]-=1
print(r)

```

Try it online!

Require the input to be all upper-case, because... it saves a byte.

Full program, takes input from `stdin` and output to `stdout`.

---

Variable names: (sort of ungolfed code)

```
a : permu
f : factorial
c : count_num
C : char
l : n_num_left
F : factor
r : result

```

Unfortunately, `from math import factorial as f` takes exactly 1 more byte.

---

(Unrelated note: I checked the `Combinatorica`` package of Mathematica, nothing useful, including `RankPermutation`)
> 2 votes

# Answer
# Python 3, ~~105~~ ~~104~~ 103 bytes

```
f=lambda s:s==s*2or f(s[1:])+sum(f(sorted(s[:s.index(c)]+s[s.index(c)+1:])[::-1])for c in{*s}if c<s[0])

```

Try it online!
> 1 votes

# Answer
# C++, 230 bytes

```
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;void R(string s){int n=1;auto p=s;sort(begin(p),end(p));do if(p==s)cout<<n;while(++n,next_permutation(begin(p),end(p)));}int main(int n,char**a){R(a[1]);}

```

As per my asking, the code definitely need to be executable as-is. The function-only clause is basically rubbish. :-@

Thank you to those who kindly answered the question of what can be cut out for me. In the interest of *valid* code, I’ve avoided the popular GCC-ism of including \<bits/stdc++.h\>, which I have always considered a bad loophole cheat.

What follows is what remains of my original posting:

---

I am always unsure when using C and C++ what counts towards the byte total. According to Program, Function, or Snippet? the answer is still vague (as long as it isn’t a snippet, I guess). So I am going with the shortest of the two possibilities.

Here it is ungolfed *with necessary headers, etc:*

```
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

void R( string s )
{
  int n = 1;
  auto p = s;
  sort( begin(p), end(p) );
  do if (p == s) cout << n;
  while (++n, next_permutation( begin(p), end(p) ));
}

int main( int n, char** a )
{
  R( a[1] );
}

```

That golfs down to 230 bytes, a third of that standard boilerplate required by *every* C++ program. (So, I don’t feel too bad not counting it, but as I haven’t ever seen a firm complaint either way, OP will have to tell me which he prefers to satisfy “write a code to take any word as an input and display its rank.”)

I am also unsure if this satisfies “the rank should be output.”
> 1 votes

# Answer
# Clean, ~~113~~ 111 bytes

```
import StdEnv,StdLib
?s=elemIndex s[[]:removeDup(foldr(\a b=sort[insertAt i a x\\x<-b,i<-[0..length x]])[[]]s)]

```

Try it online!

+3 bytes to handle 1-indexing :/
> 1 votes

# Answer
# APL (Dyalog Unicode), 33 bytes (SBCS)

```
⎕CY'dfns'
{∪⊃∘(⍵[⍋⍵])¨¨↓pmat≢⍵}⍳⊂

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), ~~106~~ 100 bytes

```
w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]

```

### Test cases

```
let f =

w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]

console.log(f("prime"))  // 94
console.log(f("super"))  // 93
console.log(f("bless"))  // 4
console.log(f("speech")) // 354
console.log(f("earth"))  // 28
console.log(f("a"))      // 1
console.log(f("abcd"))   // 1
console.log(f("baa"))    // 3
```

### How?

**P()** is our recursive permutation function. But the encompassing object of **P** is also used to store the ranks of the permutations.

```
P = (a, s) =>               // given an array of letters a[] and a string s
  a[0] ?                    // if a[] is not empty:
    a.map((_, i) =>         //   for each entry at position i in a[]:
      P(                    //     do a recursive call to P() with:
        b = [...a],         //       a copy b[] of a[], with a[i] removed
        s + b.splice(i, 1)  //       the extracted letter appended to s
      )                     //     end of recursive call
    )                       //   end of map()
  :                         // else:
    P[s] = P[s] || ++k      //   if P[s] is not already defined, set it to ++k

```

The wrapping code now reads as:

```
w =>                        // given the input word w
  P[                        // return the permutation rank for w
    P(                      //   initial call to P() with:
      [...w].sort(),        //     the lexicographically sorted letters of w
      k = ''                //     s = k = '' (k is then coerced to a number)
    ),                      //   end of call
    w                       //   actual index used to read P[]
  ]                         // end of access to P[]

```
> 1 votes

# Answer
# Ruby, 49 bytes

```
->w{c=w.chars
1+c.sort.permutation.uniq.index(c)}

```

Try it online!
> 1 votes

# Answer
# Perl 5, 98 + 3 (`-pF`) = 101 bytes

```
$"=',';@a=grep{++$k{$_}<=1&&"@F"eq join$",sort/./g}sort glob"{@F}"x(@F=sort@F);1while!/$a[$\++]/}{

```

Try it online!
> 0 votes

# Answer
# Octave, 43 bytes

```
@(s)find(all(unique(perms(s),'rows')==s,2))

```

**Try it online!**
> 0 votes

# Answer
# Perl 6, 53 bytes

```
{1+first :k,$_,.comb.permutations».join.unique.sort}

```

Try it online!
> 0 votes

# Answer
# PowerShell, 275 bytes

```
param($s)function n($a){if($a-eq1){return}0..($a-1)|%{n($a-1);if($a-eq2){$b.ToString()}$p=($j-$a);[char]$t=$b[$p];for($z=($p+1);$z-lt$j;$z++){$b[($z-1)]=$b[$z]}$b[($z-1)]=$t}}if($s.length-eq1){1;exit}$b=New-Object Text.StringBuilder $s;(n($j=$s.length)|sort -u).indexOf($s)+1

```

Try it online!

So, this is a bloody mess.

*PowerShell doesn't have any permutations built-in, so this code uses the algorithm from here (golfed heavily), which is available under the Microsoft Limited Public License (Exhibit B on this licensing page).*

The program takes input `$s` as a string, then the actual program starts with `$b=New-Object ...`. We're constructing a new StringBuilder object, which is (essentially) a mutable string of characters. This will allow us to handle the permutations more easily. We then call the function `n` (setting `$j` along the way to be the length of the input string), `sort` with the `-u`nique flag the output, take the `.indexOf()` to find the input string, and add `1` because PowerShell is zero-indexed.

The function is the main part of the program. It takes as input a number, and will each iteration count down until we reach `1` (i.e., a single letter). The rest of the function essentially recursively calls the function as well as takes the current letter and iterates it through every position.

There's a single bit of additional logic `if($s.length-eq1){1;exit}` to account for input strings of length `1` due to how the permutations function works.
> 0 votes

# Answer
# Pyt, 5 bytes

```
ĐᒆỤ≥Ʃ

```

Explanation:

```
            Implicit input
Đ           Duplicate input
 ᒆ         Get list of all permutations of input
  Ụ         Get unique permutations
   ≥        Does each permutation come before or is equal to the input?
    Ʃ       Sum of result of previous step (converts booleans to ints)

```

~~Try it online!~~
> 0 votes

---
Tags: code-golf, string, combinatorics, sorting, permutations
---


title: Tell my browser

text:
# Question
Title: Tell my browser
# Background

Many people visit webpages, which require special browsers because of lack of compatibility. So you have to write a script (client sided or server sided), which just prints the name of the browser. Because not everyone has fast internet, the script has to be as short as possible. (This is a joke xD)

# Rules

1. You have to print the name of the browser loading the page without any version number etc. to STDOUT or equivalent. Leading or trailing spaces are allowed.
2. You can assume the browser is Firefox, Chrome, Edge, Safari or Opera, so only those browsers will be tested. Don't print "Chromium", this does NOT count.
3. The script may be server sided with CGI (in any language), ruby on rails, jsp and similar. (Given server will be apache 2 on debian) Client sided scripts may be written in JavaScript, TypeScript, and any other versions of ECMAScript, it just has to run in all five browsers.
4. If your language has no offline interpreter for CGI, assume it's saved in /usr/bin/i, the shebang at the beginning does not add bytes to the count.
5. This is a , so the shortest answer wins!
6. Http requests are put through stdin.

# Answer
# Japt, ~~55~~ 52 bytes

*-3 bytes thanks to Shaggy*

```
Ox`nàÀÓ&.ÔÀAgt`
`SafÂÈOpÀCËTFifoxnEdge`qn f!øU o

```

Try it!
> 0 votes

---
Tags: code-golf, internet, browser
---


title: Same Name, Lame!

text:
# Question
Title: Same Name, Lame!
Write a function or program that, when given a list of names, outputs or returns a list where duplicates of given names have a unique shortened version of their surname.

### Input:

A list of names, where a name is defined by a given name and a last name separated by a space. Names are non-empty strings containing only uppercase and lowercase letters. The list can be an array of strings, or the names separated by a constant non-alpha, non-space character, but the output must be in the same format as the input.

### Output:

A list of the inputted names in the same order and format as the input that have been modified by these rules:

* For unique given names, output just the given name
* For names that share the same given name:
    + As well as their given name, add the shortest unique version of their surname that that is not shared by another name, followed by a period. For instance: `John Clancy, John Smith` becomes `John C.,John S.` and `James Brown, James Bratte` becomes `James Bro.,James Bra.`
    + If one surname is a subset of another, such as `Julian King,Julian Kingsley`, return the full surname of the smaller one without a period. The example would become `Julian King,Julian King.`
* Basically a period represents the regex `.+`, where *only* one name should match it.
* You may assume that no-one will share both the same given name and the same surname
* Names are case-sensitive

### Test Cases:

* `John Clancy,Julie Walker,John Walker,Julie Clancy` -\> `John C.,Julie W.,John W.,Julie C.`
* `Julian King,Jack Johnson,Julian Kingsley` \> `Julian King,Jack,Julian King.`
* `Jack Brown,Jack Black,Jack Blue` \> `Jack Br.,Jack Bla.,Jack Blu.`
* `John Storm,Jon Snow,Johnny Storm` \> `John,Jon,Johnny`
* `Jill DeSoma,Jill Desmond` \> `Jill DeS.,Jill Des.`
* `XxXnO sCOppeXxX,XxXNO MERCYXxX` \> `XxXnO,XxXNO`

This is , so the lowest byte count for each language wins.

# Answer
# Jelly,  ~~34 33 32~~  30 bytes

```
;\ċÐf⁶t€⁶;€JṖḊ$$¦”.µ€ċ@ÐṂ€Ẏ$Ḣ€

```

A monadic link taking a list of lists of characters (i.e. a list of "strings") and returning the abbreviations in the same format and relative order.

**Try it online!** (a full program test suite)

### How?

```
;\ċÐf⁶t€⁶;€JṖḊ$$¦”.µ€ċ@ÐṂ€Ẏ$Ḣ€ - Link: list of lists    e.g. ["Sam Ng","Sam Li","Sue Ng"]
                   µ€          - monadically for €ach:  e.g. "Sue Ng"
 \                             -   cumulative reduce with:
;                              -     concatenation           ["S","Su","Sue","Sue ","Sue N","Sue Ng"]
     ⁶                         -   literal space character   ' '
   Ðf                          -   filter keep if:
  ċ                            -     count (spaces)          ["Sue ","Sue N","Sue Ng"]
        ⁶                      -   literal space character   ' '
      t€                       -   trim from €ach            ["Sue","Sue N","Sue Ng"]
                 ”.            -   literal period character  '.'
                ¦              -   sparse application...
         ;€                    -   ...of: concatenate €ach (with a period)
                               -   ...only for these indexes:
               $               -     last two links as a monad:
           J                   -       range of length       [1,2,3]
              $                -       last two links as a monad:
            Ṗ                  -         pop                 [1,2]
             Ḋ                 -         dequeue             [2]  (i.e. 2,3,...,length-1)
                               -   ...i.e.:                  ["Sue","Sue N.","Sue Ng"]
                               -                   yielding: [["Sam","Sam N.","Sam Ng"],["Sam","Sam L.","Sam Li"],["Sue","Sue N.","Sue Ng"]]
                           $   - last two links as a monad:
                          Ẏ    -   tighten                   ["Sam","Sam N.","Sam Ng","Sam","Sam L.","Sam Li","Sue","Sue N.","Sue Ng"]
                       ÐṂ€     -   filter keep minimals for €ach:
                     ċ@        -     count (sw@ping args)    [["Sam N.","Sam Ng"],["Sam L.","Sam Li"],["Sue","Sue N.","Sue Ng"]]
                            Ḣ€ - head €ach                   ["Sam N.","Sam L.","Sue"]

```
> 3 votes

# Answer
# Python 2, 130 bytes

```
def f(a):n=[[x[:i]+'.'*(' 'in x[:i]<x)for i in range(x.find(' '),len(x)+1)]for x in a];print[min(x,key=sum(n,[]).count)for x in n]

```

Try it online!

First generates all the nicknames, as follows:

```
n == [
    ['John', 'John .', 'John C.', 'John Cl.', 'John Cla.', 'John Clan.', 'John Clanc.', 'John Clancy'],
    ['Julie', 'Julie .', 'Julie W.', 'Julie Wa.', 'Julie Wal.', 'Julie Walk.', 'Julie Walke.', 'Julie Walker'],
    ['John', 'John .', 'John W.', 'John Wa.', 'John Wal.', 'John Walk.', 'John Walke.', 'John Walker'],
    ['Julie', 'Julie .', 'Julie C.', 'Julie Cl.', 'Julie Cla.', 'Julie Clan.', 'Julie Clanc.', 'Julie Clancy'],
    ['Jill', 'Jill .', 'Jill D.', 'Jill De.', 'Jill Des.', 'Jill Desm.', 'Jill Desmo.', 'Jill Desmon.', 'Jill Desmond']
]

```

Then picks the first\* one from each list that is *least frequent* in `sum(n,[])`. This will always be the first unique nickname.

Note that `n` includes the erroneous nicknames `'John .'` etc., but they will never be picked.

(\*CPython 2.7’s `min` does so, anyway. This code may not be portable!)
> 3 votes

# Answer
# Ruby ~~165 162 161~~ 160 bytes

Includes 1 trailing space if only the given name is returned, eg. `"John "`

```
->a,n=0,s=0{a.group_by{|i|i[n]}.values.flat_map{|i|j=i[0];k=j.index' ';i.size<2?j.size>n ?j[0,[n+1,k].max-(s>1?0:1)]+(n>k ??.:''):j:f[i,n+=1,i.count{|l|l[n]}]}}

```

Try it online!

163 bytes if you don't want the trailing space

```
->a,n=0,s=0{a.group_by{|i|i[n]}.values.flat_map{|i|j=i[0];k=j.index' ';i.size<2?j.size>n ?j[0..[n,k-1].max-(s>1?0:1)]+(n>k ??.: ''):j:f[i,n+1,i.count{|l|l[n+1]}]}}

```

Try it online!
> 2 votes

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


title: Remapping ASCII

text:
# Question
Title: Remapping ASCII
### Challenge

Write a program that reorders the ASCII characters!

It should output a single string containing all of the printable ASCII characters exactly once. The first character of this string is assigned the value 1, the second character the value 2, and so on.

If two characters are normally next to each other (the difference between their character codes is 1), they may not appear next to each other in the output.

### Scoring

Your score will be the sum of the values for all of the characters in your source code, as dictated by your program's output.

Please see the **Verification** section to calculate your score.

Lowest score wins!

### Rules

* "Printable ASCII" is defined to mean character codes 32 - 126, inclusive.
* You may write a full program or a function.
* Your code may only contain printable ASCII characters and newlines.
* Your program may not take any input.
* Newlines will always have the value 1. Your program's output should not include a newline.

### Verification

Use this stack snippet to verify that your code's output is valid, and to calculate your code's score!

```
var result = document.getElementById("result");document.getElementById("submit").onclick = function() {var code = document.getElementById("code").value;var output = document.getElementById("output").value;var values = [];for (var i = 0; i < output.length; i++) {var c = output[i];var v = c.charCodeAt();if (v < 32 || v > 126) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + v + ") is out of range.";return;}if (values.indexOf(c) >= 0) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + v + ") was repeated.";return;}if (i > 0) {var d = output[i - 1];var w = d.charCodeAt();if (Math.abs(v - w) == 1) {result.innerHTML = "Invalid output! Reason: `" + d + "` and `" + c + "` (codes " + w + " and " + v + ") cannot appear next to each other in the output.";return;}}values.push(c);}for (var j = 32; j <= 126; j++) {var c = String.fromCharCode(j);if (values.indexOf(c) < 0) {result.innerHTML = "Invalid output! Reason: `" + c + "` (code " + j + ") was missing.";return;}}var score = 0;for (var k = 0; k < code.length; k++) {var s = values.indexOf(code[k]) + 1;if (s <= 0) s = 1;score += s}result.innerHTML = "Your score is " + score + "!";}
```

```
<textarea id="code" rows=10 cols=50>Enter your code here.</textarea><br/><textarea id="output" rows=1 cols=50>Enter your code's output here.</textarea><br/><button id="submit">Submit</button><br/><p id="result"></p>
```

### Leaderboard

*Thanks to this post for the leaderboard code!*

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

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

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

# Answer
> 22 votes
# CJam, ~~356~~ ~~186~~ ~~168~~ ~~131~~ ~~126~~ ~~111~~ ~~99~~ ~~96~~ 94

```
"_|`'~,Y/G>z`|"_~

```

Try it online in the CJam interpreter.

### Output

```
"_|`'~,Y/G>z[ \$&(*.02468:<@BDFHJLNPRTVXZ^bdfhjlnprtvx!#%)+-13579;=?ACEIKMOQSUW]acegikmoqsuwy{}

```

### Idea

Using a variation of a technique common in CJam quines, we sort the printable ASCII characters by whether they appear in the source code, and the non-appearing ones – with two exceptions – by their code points' parity bits.

With the proper source layout, we also manage to sort the source code characters – with one exception – by their frequencies.

Special care has to be taken that two adjacent characters do not appear one after the other for the first time in the source code, as this would invalidate the answer.

### Code

```
"             "_~  Push a string, duplicate it and evaluate the copy.
 _|                Perform the set union of the original string with itself.
                   This is just an "excuse" to introduce the underscore.
   `               Inspect the string (surrounds it with double quotes).
    '~,            Push the string of Unicode characters before the tilde.
       Y/          Divide it into pairs.
         G>        Discard the first 16 pairs (control characters).
           z       Zip. This interleaves the pairs, ordering the characters
                   by their code points' parities.
            `      Inspect the array, i.e., push its string representation.
             |     Perform set union with the string of source code characters.

```

# Answer
> 14 votes
## Brainfuck, ~~1692~~ ~~826~~ 765

(Still) Unoptimized, I know. I'm working on it (leave opts in the comments).

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

```

Output:

```
+->.<[] "$&(*,02468:@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~{}ywusqomkigeca_YWUSQOMKIGECA?=;97531/)'%#!

```

I'm already utilizing overflow on 8bit cells to some extent, but I guess you could still optimize it. Though that would decrease the use of cheap chars :).

# Answer
> 12 votes
# Pyth, ~~173~~ 170

### Code

```
-so%CN2rd\~p"p~\dr2NC%os-

```

### Output

```
p~\dr2NC%os- "$&(*,.0468:<>@BDFHJLPRTVXZ^`bfhjlntvxz|!#')+/13579;=?AEGIKMOQSUWY[]_acegikmquwy{}

```

Hardcoding a quine-like string. Conveniently, the `"` character is very near the start of the generated string. Prints even then odd characters after the "quine".

Much thanks to Dennis for saving 3 points, and making the code a palindome!

Try it here

# Answer
> 10 votes
# Java, ~~3518 3189~~ 2692

A simple loop that prints even characters, then odds. I tried a few things to optimize earlier ASCIIs, but most ended up making it longer overall, and ended up with a higher score.

```
void A(){for(char A=31;A!=126;System.out.print(A+=2))A=A==125?30:A;}

```

Output is:

```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

```

**Edit:** Misunderstood the scoring at first. After flipping it to odd first, *then* even, it scores a lot better.

# Answer
> 10 votes
# Octave, 628

Code

```
["" 32:2:126 33:2:125]

```

Output:

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

Two ranges implicitly converted to string. Not sure if returning as Ans is acceptable, also gives a warning about the implicit conversion. Tried some other range vectors, but could not find anything more efficient.

# Answer
> 8 votes
# C,42 bytes, score 1539

```
main(i){for(;i-191;i+=2)putchar(32+i%95);}

!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

```

# C,39 bytes, score 1687

```
main(i){for(;i-96;)i=putchar(32+i%95);}

!Aa"Bb#Cc$Dd%Ee&Ff'Gg(Hh)Ii*Jj+Kk,Ll-Mm.Nn/Oo0Pp1Qq2Rr3Ss4Tt5Uu6Vv7Ww8Xx9Yy:Zz;[{<\|=]}>^~?_ @`

```

In both cases, `i` is initialised to the number of strings on the commandline (as no arguments are given, this is 1.)

The first version does things the obvious way, incrementing by 2, taking modulo 95 and thefore printing all the odds then all the evens.

The second version takes advantage of the fact that putchar returns the character printed. As 32 is coprime to 95, we can cycle through the characters. As C contains a lot of lowercase characters I hoped that this, besides being shorter, would have a lower score but unfortunately this is not the case.

# Answer
> 8 votes
# Befunge-93, ~~801~~ ~~797~~ ~~724~~ ~~699~~ ~~627~~ 612

Code:

```
"!  "     ^
v     _@#$<
>:,2+:"~"`|
^         <

```

Output:

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

You can try it here if you want.

It works by outputting 32-126 evens, and then 33-125 odds. If anyone wants an explanation, I'd be willing to.

I golfed it until I got it better than brainf\***, which I deemed to be the lowest I could go. As far as golfing strategies, I generated the ascii characters and then tried to replace costly characters with cheaper ones (like 1 with 2). I found out since `g` was so expensive, it was better to compute 126 every iteration. I also wrapped around the top since `^` was cheaper than `v`.

**801 -\> 797**: Recent change was removing extra spaces that was a relic from using `g`.

**797 -\> 724**: I changed calculating 126 every time to just reading tilde using `"~"`. this also allowed for cutting away whitespace (And i'm beating one of the BF answers again)

**724 -\> 699**: Similar to the last change, " " is an extremely cheap (4 points) way of obtaining 32

**699 -\> 627**: Since I only go through the 2nd row pass once, I just changed it to setting 33 instead of maintaining another value on the stack and adding one.

**627 -\> 612**: Moved as much as I could to string input. I'm pretty sure the design would need to change drastically to golf it any further.

This is probably the final iteration, unless one of the non-golfing languages gets a lower solution.

# Answer
> 7 votes
# Haskell, 830

```
['!','#'..'}']++[' ','\"'..'~']

```

Evaluates to the string:

```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

```

Inspired by @Jørgen's answer and completely different from my own.

# Answer
> 7 votes
# Brainfuck, score ~~576~~ 667

Thinking about it, 576 seemed to good to be true: I did a little estimation and worked out my score to be around 95\*6 + 45\*2 = 660. Something must have gone wrong the first time I ran the validator. The correct score is closer to my estimate. It's still not a bad score.

```
+++++++++++++++++++++++++++++++++++++++++++++.--.+++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.---.++.----.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.---.--.--.--.--.--.--.+++.--.++++.++.++.

```

Keep it simple.

Basically just walks up and down the ASCII set, printing characters. The three characters used in the program are printed first. Turning round at either end was a little bit tricky.

```
-+.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~{}ywusqomkigeca_][YWUSQOMKIGECA?=;97531/,*(&$" #!%')

```

# Answer
> 6 votes
# Ruby 2.2, 1157

```
eval s='srand 1;([*s.bytes].shuffle|[*33..0x7e].shuffle).map{|c|putc c}'

```

Output:

```
f.p|cahu]xens7*0{)3tbmdy[}l1; r(o@&gN/MjzSVv~>D4I`L\KB92=i%PHE?5TQw,W-#6U'^Y!$R"XkO_q+CAGZF<8:J

```

This is a pretty dumb solution (and I'm not sure srand shouldn't be a standard loophole especially since it drastically reduces portability). Shuffles (most of) the bytes in its own source code and shuffles the rest, then uniques and concatenates the arrays. Uses a random seed picked so that the output is legal (the fact that it's a single digit is pure luck).

# Answer
> 5 votes
# gawk, ~~2782~~ ~~1988~~ 1821

```
END{for(rrf=rrr="rf(3)+=;1\"$?:~ptoin[<-EN% ^.|P";fr++<333;$fr=(ff=sprintf("%c",fr))~"[[(]"?f:ff);for(;r++<33+13+1;rrf=f)printf(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}

```

### Output

```
rf(3)+=;1"$?:~ptoin[<-EN% ^.|P}{&yw*u,sq02m4k68gec>a@_B]DFYHWJULSQORMTKVIXGZ\CA`bd9h7j5l/vx'z#!

```

### Usage

Copy and paste the following to your console
(mawk won't work, because it's ~~too sctrict~~ stricter with printf)

```
awk 'END{for(rrf=rrr="rf(3)+=;1\"$?:~ptoin[<-EN% ^.|P";fr++<333;$fr=(ff=sprintf("%c",fr))~"[[(]"?f:ff);for(;r++<33+13+1;rrf=f)printf(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}' < /dev/null

```

The `< /dev/null` at the end signals the end of input, so the END block will be executed.

I basically interweaved the characters coming from the bottom and coming from the top. Then I analysed, which characters were used the most in the program and printed them first, in order of frequency. Then I had to make sure that no character is printed more than one time. The weaving in opposite directions made it more probable that an already used character wouldn't lead to printing neighbours. But they met in the middle at `P`, so I had to print that in the beginning too. Then there were some problems with characters which are used in regexps... Then I renamed the variables cheaply and did the whole thing over again. Then I found some characters I could replace in my program, and did the whole thing over again. And so on.. I finally tweaked the string with the preferred characters a little by testing.

I think I'm done `:D`

During the process I never executed the program from the command line, but constructed a string I executed from inside a script, which would analyse the output for correctness and give me the score and stuff. That score output helped a lot. Of course I rechecked here (you never know) but it got me the same result.

There the program looks like this

```
p=sprintf("END{"\
"for(rrf=rrr=%c%s%c;fr++<333;$fr=(ff=sprintf(%c%cc%c,fr))~%c[[(]%c?f:ff);"\
"for(;r++<33+13+1;rrf=f)printf"\
"(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}"\
,34,s=sprintf("rf(3)+=;1%c%c$?:~ptoin[<-EN%c ^.|P",92,34,37),34,34,37,34,34,34)

```

# Answer
> 5 votes
# CBM BASIC V2, 2553

```
1FORI=0TO47:PRINTCHR$(32+I*2);:NEXT
2FORI=0TO47:PRINTCHR$(33+I*2);:NEXT

```

the output (converted in ASCII by a python script on pc):

```
<blank>"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

# Answer
> 5 votes
# Matlab, 763

Of course, it's quite impossible to beat the Octave solution in MATLAB, since it doesn't have `"` which is 'early' in the ASCII-range. However, I decided to get a bit creative and figured to abuse `randperm`. I admit that it's a bit hacky and some could consider it cheating, but I guess it's a nice touch. First, the program and output:

```
rng(1194663);['' randperm(95)+31]

```

Ouput:

```
p2)[]913r~jZe:'Xf +b(Atd@LHT*7&xmN>6!?CJgwsaSh|/McO4_EkK=$5VP-%D<"Gz#Yq08n};WB`{.l\Quy^vR,IFoiU

```

For calculating an appropriate seed, I used the following program, which I ran until seed=4648029 (i.e., until the dishes were done)

```
minscore=Inf;
for(seed=1:1e9)
    rng(seed)
    p=randperm(95)+31;
    if(any(abs(diff(p))==1))
        continue
    end
    codestring=sprintf('rng(%d);['''' randperm(95)+31]',seed);
    score=0;
    for(i=1:length(codestring))
        score=score + find(codestring(i)==p,1);
    end
    if(score<minscore)
        minscore=score;
        bestseed=seed;
    end
end

```

Perhaps one way to improve the program is to try out floating point seeds as well, e.g., 2.3e4 increase the number of seeds without having a longer seed length. If anyone feels like making a program to calculate all n-character numbers representable by Matlab.... ;)

# Answer
> 4 votes
# Haskell, ~~1660~~ 1376

```
""!_="O"
(a:b)!(c:d)=a:c:b!d
a=[' '..'N']!['P'..]

```

Defines the function `a` which returns the string:

```
 P!Q"R#S$T%U&V'W(X)Y*Z+[,\-].^/_0`1a2b3c4d5e6f7g8h9i:j;k<l=m>n?o@pAqBrCsDtEuFvGwHxIyJzK{L|M}N~O

```

# Answer
> 4 votes
# Java, 15470

```
class A{public static void main(String[]I) throws Exception{java.lang.reflect.Field C=Character.class.getDeclaredClasses()[0].getDeclaredField("cache");C.setAccessible(true);Character[]E=(Character[])C.get(C);for(char A=31,G=31;A!=126;E[G++]=new Character(A+=2))A=A==125?30:A;for(char A=31;A!=126;A++)System.out.printf("%c", A);}}

```

Not really optimal at all, but it *actually* remaps the chars (rather than just printing out a set of modified chars).

Ungolfed:

```
public class Main {
    public static void main(String[] args) throws Exception {
        java.lang.reflect.Field feild = Character.class.getDeclaredClasses()[0].getDeclaredField("cache");
        feild.setAccessible(true);
        Character[] array = (Character[]) feild.get(args); //Since it's a static field, we can supply whatever we want here, and args is cheaper than null.

        char i = 31;
        for (char c = 31; c != 126; array[i++] = new Character(c += 2)) {
            c = c == 125 ? 30 : c;
        }

        for (char c = 31; c < 126; c++) {
            System.out.printf("%c", c);
        }
    }
}

```

## Output

```
!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

```

It orders the chars using the same method as Geobits' answer, and does something similar to this answer to change the chars.

# Answer
> 3 votes
# JavaScript, ~~3169~~ ~~2548~~ ~~2144~~ ~~2104~~ ~~2071~~ ~~1885~~ ~~1876~~ 1872

### Code

```
t=''
i=S=95
while(i--)t+=String.fromCharCode(i*2291%S-
-32)
alert(t)

```

### Output

```
ti^SH=2'{peZOD9.#wlaVK@5*~sh]RG<1&zodYNC8-"vk`UJ?4)}rg\QF;0%yncXMB7,!uj_TI>3(|qf[PE:/$xmbWLA6+

```

# Answer
> 3 votes
# Python 2, ~~72 bytes (3188)~~ 116 bytes ~~(1383)~~ ~~(1306)~~ (1303)

thanks @FryAmTheEggman for the join trick ;)

thanks @nim (Did I misread the text? :P)

thanks @Mathias Ettinger

```
n='nr i(a)2:]o[c=fh1+t"3egj,p.7'
a=[chr(r)for r in range(32,127)if not chr(r)in n]
print n+"".join(a[::2]+a[1::2])

```

output:

```
 nr<blank>i(a)2:]o[c=fh1+t"3egj,p.7!$&*/469<?ACEGIKMOQSUWY\_bkmsvxz|~#%'-058;>@BDFHJLNPRTVXZ^`dlquwy{}

```

# Answer
> 3 votes
# BBC BASIC, 2554

## Code

```
n=32
s$=""
REPEAT
  s$+=CHR$(n)
  n+=2
  IFn=128THENn=33
UNTILn=127
PRINTs$

```

## Output

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

# Answer
> 3 votes
# Fortran 90, ~~1523~~ ~~1519~~ 1171

This is a nested output loop, similar to other answers. Not too confident that much improvement is possible...

```
PRINT*,((CHAR(J),J=L,126,2),L=32,33)
END

```

Output:

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

**Edit:** Forgot that Fortran 90 is necessary for this code, 77 requires code to start in the 7th column. On the other hand, the language is case insensitive, allowing an easy improvement. The loop counters are `J` and `L` because these are the first two letters in the output string implicitly declared as integers by Fortran.

# Answer
> 3 votes
# Perl, ~~1089~~ 922

It turns out that printing the ASCII values in steps of ~~42~~ **58** gives the lowest score with this approach:

```
print chr$_*58%95+32for 0..94

```

### Output:

```
 Z5oJ%_:tO*d?yT/iD~Y4nI$^9sN)c>xS.hC}X3mH#]8rM(b=wR-gB|W2lG"\7qL'a<vQ,fA{V1kF![6pK&`;uP+e@zU0jE

```

# Answer
> 3 votes
# PHP, 1217 1081

The code:

```
for(;$T!=T;$T=($T+52)%95)echo chr(32+$T);

```

Because the variables are not initialized, it needs to suppress the notices on running (PHP complains but continues execution and uses a default value that is appropriate in the context; `0` in this case):

```
$ php -d error_reporting=0 remapping-ascii.php

```

Its output:

```
 T)]2f;oDxM"V+_4h=qFzO$X-a6j?sH|Q&Z/c8lAuJ~S(\1e:nCwL!U*^3g<pEyN#W,`5i>rG{P%Y.b7k@tI}R'[0d9mBvK

```

Remarks:

* the output starts with a white space (`chr(32)`);
* the code prints the white space then each 52th character, wrapping around the range;
* the magic number `52` was "discovered" by searching the entire range (1..94) of possible offsets; 1 produces the list of printable chars in the ascending order of their ASCII codes, 94 produces the list in the reverse order, both are bad; the multiples of 5 and 19 (the divisors of 95) produce short cycles and don't cover the entire range of values (also bad);
* `52` seems to be magic; it is the best offset for this code; but it is also the best for some variations of the code (that produce slightly bigger scores); the variations I tried: use `while()` instead of `for()`, use `$f++`, `$f--` or `--$f` instead of `++$f`, swap the operands around the `<` and `+` operators; squeeze the modification of `$T` into `32+$T`;
* the names of the variables (`$T` and `$f`) are the first letters from the output;
* I tried to initialize `$T` with `4` or `11` but the scores were worse; starting with `4` makes `$` the first character in the output; it is the most used character in a PHP source code; `11` brings `+` in front; `$` and `+` are the most used characters in this code.

The code, tests, incremental changes I tried until I reached this solution and the script that tested all possible step values (the authoritative provider for `52` as the best step) can be found on github.

# Answer
> 2 votes
# Fourier, 1236

Basically a conversion of my BBCB program

```
32~N127(Na^^~N{128}{33~N}N)

```

## Output

```
 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

```

# Answer
> 0 votes
# AWK, 49 bytes, Score: 1755

```
BEGIN{for(f=82;++f<178;)printf"%c",(2*f-1)%95+32}

```

Try it online!

Simply prints every other character then starts over filling in the blanks. First character printed is an `f`. I attempted printing in reverse order, but that greatly increased the score. Other patterns are possible by simply changing the multiplier and the loop criteria.

# Answer
> 0 votes
# Perl 5, 1069

```
print chr$_*2%95+32for 0..94

```

Try it online!

---
Tags: code-challenge, printable-ascii
---


# Question
Title: Of Dumps and Cubes, and Structured Nonsense
Your challenge is to translate a Cubically cube-dump to the format specified in this challenge.

## Input

The input will represent a Rubik's Cube, formatted how Cubically prints its memory cube at the end of every program.

This is a solved cube:

```
   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555

```

This is a cube scrambled with `L2D2L2D2B2R2F2L2D2U2F2UF2U'R2UB2U'L2UB2U'LU'L2U'D'B2U'RBUBF'D'` (Singmaster's notation):

```
   201
   501
   331
132505224540
512324533442
404513210411
   350
   254
   003

```

## Output

**If you already understand this format, hit page down a few times to skip lots of explanation.**

The output will represent a Rubik's Cube, formatted how solutions to this challenge take input.

> The first 12 values are the edge cubies, and the next eight are the corners. The faces are U(p), D(own), R(ight), L(eft), F(ront), and B(ack). First the cubie that's in the UF position is given, by the color (in UFRDBL notation) that's on top first, and then the other color next, and so on.

This format is a bit confusing, so here's a way to visualize it. This is the solved cube:

That renders the output `UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR`.

If we were to swap, for example, the red-white edge and the red-blue edge, the visualization would look like this (with no changes to the hidden faces):

That renders the output `UR UF UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR` (which, btw, is an impossible cube state). Note that the order of the letters in cubies matter:

```
Above: UR UF UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR
Below: RU FU UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR

```

The cube scrambled with `L2D2L2D2B2R2F2L2D2U2F2UF2U'R2UB2U'L2UB2U'LU'L2U'D'B2U'RBUBF'D'` creates this cube (only the top, front, and right faces are shown):

```
Solved:    UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR
Scrambled: RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU

```

As you can see in the comparison above and in the visualizations, the blue-red `RU` edge of the mixed cube is in the place of the red-white `UF` edge of the solved cube. The green-white `LF` edge is in the place of the red-blue `UR` edge, etc.

## Rules

* I/O will be done via any allowed means.
* The output cubies must be delimited by any whitespace character you choose.
* The input will be formatted exactly how it is shown in the challenge, including whitespace.
* Your program may do whatever you like if the inputted cube is unsolvable.

## Test cases

* Input -\> output: `RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU`
* Input -\> output: `UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR`
* Input -\> output: `FU DL LB BU RU BR RF DR BD DF LF LU FUL FLD URB BLU RUF DBR BDL RFD`

Here's a reference program using parts of Cubically's rubiks.c.

## Winner

As this is , the shortest answer in bytes wins!

# Answer
# Jelly, ~~87~~ ~~73~~ ~~62~~ ~~61~~ 60 bytes

```
fØDO“¬ụƘȷ$OkḌ×c¿?oƥ¤_Ọ6;ȤṚUȷ!8⁺⁻:ĠŻ’Œ?¤ịs24Ṗs"2,3ị“LFRBDU”ẎK

```

Try it online!
> 2 votes

# Answer
# Clean, ~~150~~ ~~145~~ 143 bytes

Contains *many* non-printable characters.

```
import StdEnv
$d=map(\c=['ULFRBD ']!!(digitToInt(['96':d]!!(toInt c))))['!B5J8P;H2)*\'&-,/$ "C76A43O1<Q:9']

```

Try it online!

Defines the function `$`, taking `[Char]`, and giving `[Char]`.

This works by mapping each character position in the input to another character position in the output (using the character codes in a string), taking advantage of the swapped 'cubies' in the output being paralleled by swapped colors in the corresponding position in the input.

Output is separated by spaces.
> 2 votes

# Answer
# Ruby, 115 bytes

```
->s{"29&,<&$?&*6&`S&hV&nY&fP&GH&ED&KJ&MB&3:;&%=>&#@5&178&aUT&_RQ&mOZ&oXW".bytes{|i|$><<"   ULFRBD"[s[i-32].ord%9]}}

```

Try it online!

A function taking the input as an argument and printing to stdout.

Iterate through the long string. Each byte(minus 32) represents the index of the next character to be transcribed.

To transcribe, take the ascii code of the character in the input (`012345` or newline) and find the value modulo 9. This gives a number in the range 3 to 8, which is treated as an index in the string `" ULFRBD"` to transcribe. Thus the ascii code for `0` is 48, 48%9 is 3, which is the index of `U` in the string above.

The `&` signs in the long string point to the first newline in the input (character `#10`.) This is taken modulo 9 to give the value 1, which is looked up in `" ULFRBD"` and transcribed as a space.

The indices in the input are looked up as follows (extra spaces added for clarity)

```
    #$%
    *+,
    123
567 89: ;<= >?@
BCD EFG HIJ KLM
OPQ RST UVW XYZ
    _`a
    fgh
    mno

```
> 2 votes

---
Tags: code-golf, parsing, rubiks-cube, cubically
---


title: Simulate a Rubik's cube

text:
# Question
Title: Simulate a Rubik's cube
A Rubik's cube has 6 colors: red, orange, yellow, white, blue, and green. Red and orange, yellow and white, and blue and green faces are on opposite sides.

Net of a solved Rubik's cube looks like this:

```
 Y
BRGO
 W

```

And the tiles look like this:

```
      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

```

# Challenge

Given rotations, reversed rotations, or double rotations output what a solved cube will transform to, as ASCII art or as an image (whitespaces aren't necessary, may or may not exist, trailing whitespaces are allowed.).

Input will be rotation (and optional modifier). Rotation notation goes like: `U`(p), `L`(eft), `F`(ront), `R`(ight), `B`(ack), `D`(own); `2` (double), `'` or `i` (inverse).

All normal rotations will be 90° clockwise, inverse ones will be counterclockwise.

**Explanation about clockwiseness**: Imagine the cube as you're looking at the red face, and the yellow face is at the top. Then rotate the cube so that the face that the program will rotate will face you. This is the way clockwiseness will work. (Except back face, you will rotate the cube horizontally in that case.)

## Input

Input will be a list of moves.

## Output

An ASCII art that represents the cube or an image of the net of the cube.

## Examples

**Input**:  (empty)

**Output**:

```
      Y Y Y
      Y Y Y
      Y Y Y
B B B R R R G G G O O O
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

```

**Input**: `U` (up)

**Output**:

```
      Y Y Y
      Y Y Y
      Y Y Y
R R R G G G O O O B B B
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

```

**Input**: `U'` or `Ui` (inverse up)

**Output**:

```
      Y Y Y
      Y Y Y
      Y Y Y
O O O B B B R R R G G G
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

```

**Input**: `U2` (double up)

**Output**:

```
      Y Y Y
      Y Y Y
      Y Y Y
G G G O O O B B B R R R
B B B R R R G G G O O O
B B B R R R G G G O O O
      W W W
      W W W
      W W W

```

**Input**: `L'` (inversed left)

**Output**:

```
      R Y Y
      R Y Y
      R Y Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
B B B W R R G G G O O Y
      O W W
      O W W
      O W W

```

**Input**: `R` (right)

**Output**:

```
      Y Y R
      Y Y R
      Y Y R
B B B R R W G G G Y O O
B B B R R W G G G Y O O
B B B R R W G G G Y O O
      W W O
      W W O
      W W O

```

**Input**: `U2 L' D` (double up, inverse left, down)

**Output**:

```
      O Y Y
      R Y Y
      R Y Y
G B B W O O B B B R R Y
G B B W R R G G G O O Y
O O Y G B B W R R G G G
      R O O
      W W W
      W W W

```

# Rules

* No loopholes allowed.
* This is , so shortest code in bytes solving the problem wins.

# Answer
# Ruby, ~~370 339~~ 305 bytes

Latest edit: a few bytes saved by rearrangement of the plotting formulas and removal of unnecessary brackets. A massive saving by rewriting the generation of the cube - I never knew Ruby had a builtin for Cartesian Products!

```
->s{q=[-66,0,71].product [-87,0,89],[-79,0,82]
s.map{|c|m="LDBRUF".index c[0];e=m/3*2-1
c.sub(/[i']/,"33").chars{q.map{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)}}}
t=[" "*12]*9*$/
q.map{|r|a,b,c=r.map{|i|i<=>0}
3.times{|i|r[i]!=0&&t[56+[a*3-a*c-d=b*13,a-d*3+d*c,3-d-c*3+c*a][i]]=r[i].abs.chr}}
t}

```

Anonymous function.

Accepts an array of strings, each representing one face turn (a single string with spaces between each face turn is an additional 6 bytes.)

Returns a 9x12 rectangular string.

**Brief explanation**

This is closely based on a concept from my answer to this question, which in turn was based on a similar concept by Jan Dvorak.

The first line generates a 27 element array, representing the 27 cubies. Each cubie is represented by a 3 dimensional vector in which the sign represents its current position and the magnitude of each coordinate represents the ascii code for the colour of the sticker.

Example move: for R, for each cubie check if the x coordinate is \>0 and if so rotate 90 degrees by swapping the y and z coordinates and swapping the sign of one of them.

Take a 9x12 array of spaces and plot the cube into it. For each cubie and axis we check if the sticker exists (coordinate in that axis nonzero), and work out where it is to go. Then we take the coordinate and perform `.abs.chr` to change the number into the required character and plot it.

**Ungolfed in test program** (per 339 byte edit)

```
f=->s{

  q=(0..26).map{|i|                         #Build an array of 27 cubies
    [[-66,0,71][i%3],                       #x coordinate B.G
     [-87,0,89][i/3%3],                     #y coordinate Y.W
     [-79,0,82][i/9]]                       #z coordinate O.R
  }

  s.map{|c|                                 #For each move in the input array
    m="LDBRUF".index(c[0]);e=m/3*2-1        #m=face to move. e=-1 for LDB, +1 for RUF.
    c.sub(/[i']/,"33").chars{               #Substitute "i" and "'" for "33" so chars in string = clockwise 1/4 turns required. For each char...
      q.map{|j|j[m%=3]*e>0&&                #...and each cubie, m%3 tells the relevant axis. if coordinate*e>1 rotate the cubie 1/4 turn.
        (j[m-2],j[m-1]=j[m-1]*e,-j[m-2]*e)} #Swap other two axes and change sign of one. e performs sign change if necessary for LDB.
    }
  }

  t=[" "*12]*9*$/                           #Make an array of 9 strings of 12 spaces, then make a single string by joining them with newlines
  q.map{|r|                                 #For each cubie
    a,b,c=r.map{|i|i<=>0}                   #make a normalised (-1,0,1) copy of each coordinate.
    d=b*13                                  #13 chars per line, d will be useful for plotting to the correct line of the output.
    3.times{|i|                             #For each of the 3 coordinates of the cubie
      r[i]!=0&&                             #if zero, sticker doesn't exist (edges and centres have <3 stickers.) If not zero plot the sticker.
      t[[56-d+a*3-a*c,                      #Calculate position on plot for x (L/R faces),
         56-d*3+d*c+a,                      #Calculate position on plot for y (D/U faces),
         59-d-c*3+c*a][i]]=                 #Calculate position on plot for z (B/F faces). Select the correct axis.
      r[i].abs.chr                          #Convert the coordinate to a character and assign to the correct space on the output plot.
    }
  }
t}                                          #Return the output string.

puts f[gets.chomp.split]

```

**Output**

```
Checkerboard
U2 D2 F2 B2 L2 R2
   YWY
   WYW
   YWY
BGBRORGBGORO
GBGOROBGBROR
BGBRORGBGORO
   WYW
   YWY
   WYW

6-spot
U D' R L' F B' U D'
   RRR
   RYR
   RRR
WWWGGGYYYBBB
WBWGRGYGYBOB
WWWGGGYYYBBB
   OOO
   OWO
   OOO

Testcase
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW

```
> 14 votes

# Answer
# C, ~~1715~~ ~~1709~~ ~~1686~~ ~~1336~~ 1328 bytes

*25 bytes saved thanks to @KevinCruijssen!*

No answers so far, so I decided to put my own solution.

```
#define m(a,b,c,d)t[c][d]=r[a][b];
#define n(a)m(a,0,a,2)m(a,1,a,5)m(a,2,a,8)m(a,3,a,1)m(a,5,a,7)m(a,6,a,0)m(a,7,a,3)m(a,8,a,6)
#define y memcpy
typedef char R[6][9];R t;F(R r){y(t,r,54);n(0)m(4,6,1,0)m(4,7,1,3)m(4,8,1,6)m(1,0,5,0)m(1,3,5,1)m(1,6,5,2)m(5,0,3,2)m(5,1,3,5)m(5,2,3,8)m(3,2,4,6)m(3,5,4,7)m(3,8,4,8)y(r,t,54);}B(R r){y(t,r,54);n(2)m(1,2,4,0)m(1,5,4,1)m(1,8,4,2)m(3,0,5,6)m(3,3,5,7)m(3,6,5,8)m(4,0,3,6)m(4,1,3,3)m(4,2,3,0)m(5,6,1,8)m(5,7,1,5)m(5,8,1,2)y(r,t,54);}L(R r){y(t,r,54);n(3)m(0,0,5,0)m(0,3,5,3)m(0,6,5,6)m(2,2,4,6)m(2,5,4,3)m(2,8,4,0)m(4,0,0,0)m(4,3,0,3)m(4,6,0,6)m(5,0,2,8)m(5,3,2,5)m(5,6,2,2)y(r,t,54);}E(R r){y(t,r,54);n(1)m(0,2,4,2)m(0,5,4,5)m(0,8,4,8)m(5,2,0,2)m(5,5,0,5)m(5,8,0,8)m(4,2,2,6)m(4,5,2,3)m(4,8,2,0)m(2,0,5,8)m(2,3,5,5)m(2,6,5,2)y(r,t,54);}U(R r){y(t,r,54);n(4)m(0,0,3,0)m(0,1,3,1)m(0,2,3,2)m(1,0,0,0)m(1,1,0,1)m(1,2,0,2)m(2,0,1,0)m(2,1,1,1)m(2,2,1,2)m(3,0,2,0)m(3,1,2,1)m(3,2,2,2)y(r,t,54);}D(R r){y(t,r,54);n(5)m(0,6,1,6)m(0,7,1,7)m(0,8,1,8)m(1,6,2,6)m(1,7,2,7)m(1,8,2,8)m(2,6,3,6)m(2,7,3,7)m(2,8,3,8)m(3,6,0,6)m(3,7,0,7)m(3,8,0,8)y(r,t,54);}a,b,c,d,e,o,p,l;f(char*z,R s){char c[6]="RGOBYW";for(;b<7;b++)for(a=0;a<10;)s[b][a++]=c[b];for(l=strlen(z);l-->0;){d=*z++;if(d-32){e=*z++;if(*z++-32)*z++;o=e-50?e-39?1:3:2;for(p=0;p++<o;)d-70?d-66?d-76?d-82?d-85?D(s):U(s):E(s):L(s):B(s):F(s);}}}

```

Try it online!

Ungolfed old version:

```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>

typedef char Tile;
typedef Tile Face[10];
typedef Face Rubik[7];

void main_loop(Rubik);
void rubik_init(Rubik);
void rubik_print(Rubik);
void rotate(Rubik, char, char);
void print_tile(Rubik, int, int);

void F(Rubik);
void B(Rubik);
void L(Rubik);
void R(Rubik);
void U(Rubik);
void D(Rubik);

#define move(a, b, c, d) \
      temp[c][d] = rubik[a][b]

#define move_f(a) \
    move(a, 1, a, 3); \
    move(a, 2, a, 6); \
    move(a, 3, a, 9); \
    move(a, 4, a, 2); \
    move(a, 6, a, 8); \
    move(a, 7, a, 1); \
    move(a, 8, a, 4); \
    move(a, 9, a, 7)

void F(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(1);
    move(5, 7, 2, 1);
    move(5, 8, 2, 4);
    move(5, 9, 2, 7);
    move(2, 1, 6, 1);
    move(2, 4, 6, 2);
    move(2, 7, 6, 3);
    move(6, 1, 4, 3);
    move(6, 2, 4, 6);
    move(6, 3, 4, 9);
    move(4, 3, 5, 7);
    move(4, 6, 5, 8);
    move(4, 9, 5, 9);
    memcpy(rubik, temp, sizeof(Rubik));
}

void B(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(3);
    move(2, 3, 5, 1);
    move(2, 6, 5, 2);
    move(2, 9, 5, 3);
    move(4, 1, 6, 7);
    move(4, 4, 6, 8);
    move(4, 7, 6, 9);
    move(5, 1, 4, 7);
    move(5, 2, 4, 4);
    move(5, 3, 4, 1);
    move(6, 7, 2, 9);
    move(6, 8, 2, 6);
    move(6, 9, 2, 3);
    memcpy(rubik, temp, sizeof(Rubik));
}

void L(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(4);
    move(1, 1, 6, 1);
    move(1, 4, 6, 4);
    move(1, 7, 6, 7);
    move(3, 3, 5, 7);
    move(3, 6, 5, 4);
    move(3, 9, 5, 1);
    move(5, 1, 1, 1);
    move(5, 4, 1, 4);
    move(5, 7, 1, 7);
    move(6, 1, 3, 9);
    move(6, 4, 3, 6);
    move(6, 7, 3, 3);
    memcpy(rubik, temp, sizeof(Rubik));
}

void R(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(2);
    move(1, 3, 5, 3);
    move(1, 6, 5, 6);
    move(1, 9, 5, 9);
    move(6, 3, 1, 3);
    move(6, 6, 1, 6);
    move(6, 9, 1, 9);
    move(5, 3, 3, 7);
    move(5, 6, 3, 4);
    move(5, 9, 3, 1);
    move(3, 1, 6, 9);
    move(3, 4, 6, 6);
    move(3, 7, 6, 3);
    memcpy(rubik, temp, sizeof(Rubik));
}

void U(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(5);
    move(1, 1, 4, 1);
    move(1, 2, 4, 2);
    move(1, 3, 4, 3);
    move(2, 1, 1, 1);
    move(2, 2, 1, 2);
    move(2, 3, 1, 3);
    move(3, 1, 2, 1);
    move(3, 2, 2, 2);
    move(3, 3, 2, 3);
    move(4, 1, 3, 1);
    move(4, 2, 3, 2);
    move(4, 3, 3, 3);
    memcpy(rubik, temp, sizeof(Rubik));
}

void D(Rubik rubik) {
    Rubik temp;
    memcpy(temp, rubik, sizeof(Rubik));
    move_f(6);
    move(1, 7, 2, 7);
    move(1, 8, 2, 8);
    move(1, 9, 2, 9);
    move(2, 7, 3, 7);
    move(2, 8, 3, 8);
    move(2, 9, 3, 9);
    move(3, 7, 4, 7);
    move(3, 8, 4, 8);
    move(3, 9, 4, 9);
    move(4, 7, 1, 7);
    move(4, 8, 1, 8);
    move(4, 9, 1, 9);
    memcpy(rubik, temp, sizeof(Rubik));
}

int main(int argc, char *argv[]) {
    Rubik rubik;
    rubik_init(rubik);
    main_loop(rubik);
    return 0;
}

void main_loop(Rubik rubik) {
    char a, b;
    for (;;) {
        a=toupper(getchar());
        if (a == 'Q') break;
        if (a != 10) {
            b=toupper(getchar());
            if (b != 10) getchar();
            rotate(rubik, a, b);
        }
        rubik_print(rubik);
    }
}

void rubik_init(Rubik rubik) {
    int i,n;
    char c[7] = " RGOBYW";

    for (n=1; n<=7; n++)
        for (i=1; i<=10; i++)
            rubik[n][i] = c[n];
}

void rotate(Rubik rubik, char a, char b){
    int i = b == '2' ? 2 : b == '\'' || b == toupper('i') ? 3 : 1;
    int j;
    for (j=0; j<i; j++)
        if (a == 'F') F(rubik);
        else if (a == 'B') B(rubik);
        else if (a == 'L') L(rubik);
        else if (a == 'R') R(rubik);
        else if (a == 'U') U(rubik);
        else if (a == 'D') D(rubik);
        else;
}

void rubik_print(Rubik rubik) {
    int i,j,k;

    for (i=1; i<=9; i++)
        if (i%3==0) {
            print_tile(rubik,5,i);
            printf("\n");
        }
        else if (i%3==1) {
            printf("    ");
            print_tile(rubik,5,i);
        }
        else
            print_tile(rubik,5,i);

    printf("\n");

    for (k=1; k<=3; k++) {
        for (i=3; i<=6; i++) {
            for (j=k*3-2; j<=k*3; j++)
                print_tile(rubik, i%4+1, j);
            printf(" ");
        }
        printf("\n");
    }

    printf("\n");

    for (i=1; i<=9; i++)
        if (i%3==0) {
            print_tile(rubik, 6, i);
            printf("\n");
        }
        else if (i%3==1) {
            printf("    ");
            print_tile(rubik, 6, i);
        }
        else
            print_tile(rubik, 6, i);

}

void print_tile(Rubik rubik, int a, int b) {
    switch (rubik[a][b]) {
      case 'R':
        printf("R");
        break;
      case 'O':
        printf("O");
        break;
      case 'B':
        printf("B");
        break;
      case 'G':
        printf("G");
        break;
      case 'Y':
        printf("Y");
        break;
      case 'W':
        printf("W");
        break;
      default:
        exit(1);
    }
}

```
> 11 votes

# Answer
# Javascript (ES5), 1615 bytes

```
function m(a){b=[];b[0]=a[6];b[2]=a[0];b[8]=a[2];b[6]=a[8];b[1]=a[3];b[5]=a[1];b[7]=a[5];b[3]=a[7];b[4]=a[4];return b}function q(a,b){c=[];c[0]=b[0];c[1]=b[1];c[2]=a[2];c[3]=b[3];c[4]=b[4];c[5]=a[5];c[6]=b[6];c[7]=b[7];c[8]=a[8];return c}function r(a){var b=[];b[0]=m(a[0]);b[1]=q(a[2],a[1]);b[4]=q(a[1],a[4]);b[3]=q(a[4],a[3]);b[2]=q(a[3],a[2]);b[5]=a[5];return b}function x(a){var b=[];b[0]=m(a[0]);b[1]=a[2];b[2]=a[3];b[3]=a[4];b[4]=a[1];b[5]=m(m(m(a[5])));return b}function y(a){var b=[];b[0]=a[4];b[1]=m(a[1]);b[2]=a[0];b[3]=m(m(m(a[3])));b[4]=a[5];b[5]=a[2];return b}function s(a){a=a.replace(/F2/,"F F");a=a.replace(/R2/,"R R");a=a.replace(/U2/,"U U");a=a.replace(/D2/,"D D");a=a.replace(/B2/,"B B");a=a.replace(/L2/,"L L");a=a.replace(/F'/,"F F F");a=a.replace(/R'/,"R R R");a=a.replace(/U'/,"U U U");a=a.replace(/D'/,"D D D");a=a.replace(/B'/,"B B B");a=a.replace(/L'/,"L L L");a=a.replace(/F/,"y y y R y");a=a.replace(/L/,"y y R y y");a=a.replace(/U/,"x y R y y y x x x");a=a.replace(/B/,"y R y y y");a=a.replace(/D/,"x y y y R y x x x");a=a.split(" ");for(b=["RRRRRRRRR".split(""),"WWWWWWWWW".split(""),"GGGGGGGGG".split(""),"YYYYYYYYY".split(""),"BBBBBBBBB".split(""),"OOOOOOOOO".split("")],c=0;c<a.length;++c)"x"==a[c]?b=x(b):"y"==a[c]?b=y(b):"R"==a[c]&&(b=r(b));return p(b)}function p(a){for(var b="",c=0;3>c;++c)b+="\n   "+a[1][3*c+0]+a[1][3*c+1]+a[1][3*c+2];for(c=0;3>c;++c)b+="\n"+a[5][3*c+0]+a[5][3*c+1]+a[5][3*c+2]+a[2][3*c+0]+a[2][3*c+1]+a[2][3*c+2]+a[0][3*c+0]+a[0][3*c+1]+a[0][3*c+2]+a[4][3*c+0]+a[4][3*c+1]+a[4][3*c+2];for(c=0;3>c;++c)b+="\n   "+a[3][3*c+0]+a[3][3*c+1]+a[3][3*c+2];return b}

```

Ungolfed:

```
function m(fac){ //Turn a face
    //0 1 2
    //3 4 5
    //6 7 8

    var fac2=[];
    fac2[0]=fac[6];
    fac2[2]=fac[0];
    fac2[8]=fac[2];
    fac2[6]=fac[8];

    fac2[1]=fac[3];
    fac2[5]=fac[1];
    fac2[7]=fac[5];
    fac2[3]=fac[7];

    fac2[4]=fac[4];

    return fac2;
}

function q(face1,face3){ //Swap right third of two faces
    var face2=[];
    face2[0]=face3[0];
    face2[1]=face3[1];
    face2[2]=face1[2];
    face2[3]=face3[3];
    face2[4]=face3[4];
    face2[5]=face1[5];
    face2[6]=face3[6];
    face2[7]=face3[7];
    face2[8]=face1[8];
    return face2;
}

function r(state){ //Apply a R move
    var state2=[];
    state2[0]=m(state[0]);
    //Swap right set of Front, Up, Back, Down (2,1,4,3);

    state2[1]=q(state[2],state[1]);
    state2[4]=q(state[1],state[4]);
    state2[3]=q(state[4],state[3]);
    state2[2]=q(state[3],state[2]);
    state2[5]=state[5];
    return state2;
}

function x(staten){ //Apply a x move
    var state2=[];
    state2[0]=m(staten[0]);
    state2[1]=staten[2];
    state2[2]=staten[3];
    state2[3]=staten[4];
    state2[4]=staten[1];
    state2[5]=m(m(m(staten[5])));
    return state2;
}

function y(state){ //Apply a y move
    var state2=[];
    state2[0]=state[4];
    state2[1]=m(state[1]);
    state2[2]=state[0];
    state2[3]=m(m(m(state[3])));
    state2[4]=state[5];
    state2[5]=state[2];
    return state2;
}

function s(algo){ //Solve a cube, representing every move with x, y and R
    algo=algo.replace(/F2/,"F F");
    algo=algo.replace(/R2/,"R R");
    algo=algo.replace(/U2/,"U U");
    algo=algo.replace(/D2/,"D D");
    algo=algo.replace(/B2/,"B B");
    algo=algo.replace(/L2/,"L L");

    algo=algo.replace(/F'/,"F F F");
    algo=algo.replace(/R'/,"R R R");
    algo=algo.replace(/U'/,"U U U");
    algo=algo.replace(/D'/,"D D D");
    algo=algo.replace(/B'/,"B B B");
    algo=algo.replace(/L'/,"L L L");

    algo=algo.replace(/F/,"y y y R y");
    algo=algo.replace(/L/,"y y R y y");
    algo=algo.replace(/U/,"x y R y y y x x x");
    algo=algo.replace(/B/,"y R y y y");
    algo=algo.replace(/D/,"x y y y R y x x x");

    algo=algo.split(" ");

    var cstate=[["R","R","R","R","R","R","R","R","R"],["W","W","W","W","W","W","W","W","W"],["G","G","G","G","G","G","G","G","G"],["Y","Y","Y","Y","Y","Y","Y","Y","Y"],["B","B","B","B","B","B","B","B","B"],["O","O","O","O","O","O","O","O","O"]];

    for(var i=0;i<algo.length;++i){
        if(algo[i]=="x"){
            cstate=x(cstate);
        }else if(algo[i]=="y"){
            cstate=y(cstate);
        }else if(algo[i]=="R"){
            cstate=r(cstate);
        }
    }

    return p(cstate);
}

function p(cstate){ //Print
    var out="";
    var leftspace="\n   ";
    for(var i=0;i<3;++i){
        out+=leftspace+cstate[1][3*i+0]+cstate[1][3*i+1]+cstate[1][3*i+2]
    }
    for(var i=0;i<3;++i){
        out+="\n"+cstate[5][3*i+0]+cstate[5][3*i+1]+cstate[5][3*i+2]+cstate[2][3*i+0]+cstate[2][3*i+1]+cstate[2][3*i+2]+cstate[0][3*i+0]+cstate[0][3*i+1]+cstate[0][3*i+2]+cstate[4][3*i+0]+cstate[4][3*i+1]+cstate[4][3*i+2]
    }
    for(var i=0;i<3;++i){
        out+=leftspace+cstate[3][3*i+0]+cstate[3][3*i+1]+cstate[3][3*i+2]
    }
    return out;
}

```

This was a very difficult challenge.

# Explanation

Take the example call `s("R U' F")`.

The program can only execute x, y and R moves.

`U'` is equal to `U U U`, so replace that.

`F` is equal to `y y y R y`, so replace that.

`R U' F'` is therefore equal to `R U U U y y y R y`, which the program can run.

cstate is defined with a solved cube. A cube is represented by an array containing 6 arrays containing the 9 stickers. The first array is for R, second for U, third for F, D, B, last array is for L. When an y needs to be executed, the program swaps the four arrays of the front, left, back and right face. For an x, it swaps front, down, back and top. Every rotation also rotates the other faces, that were not swapped. A R move rotates the right face and swaps the right part of the front, up, back, down face.

This could be modified to be able to solve problems with all types of moves, by defining them with x, y and R.
> 11 votes

# Answer
# Python 3, 528 bytes

-7 bytes thanks to my colleague rhsmits (really nice `d,*c` form & removal of redundant parentheses)

This is a full program.

```
import re
d,*c=[[f]*9for f in' YBRGOW']
r=lambda f:[f[int(v)]for v in'630741852']
U=lambda c:[r(c[0])]+[c[j%4+1][:3]+c[j][3:]for j in(1,2,3,4)]+[c[5]]
y=lambda c:[r(c[0])]+c[2:5]+[c[1],r(r(r(c[5])))]
z=lambda c:[c[2],r(r(r(c[1]))),c[5],r(c[3]),c[0][::-1],c[4][::-1]]
exec("c="+"(c);c=".join("".join("zzzUz U zzUzz yyyzUzzzy zUzzz yzUzzzyyy".split()[ord(t)%11%7]*(ord(n or'a')%6)for t,n in re.findall("([B-U])(['2i]?)",input())))+"(c)")
k=' '.join
for q in[d,c[0]],c[1:5],[d,c[5]]:
 for w in 0,3,6:print(k(k(f[w:w+3])for f in q))

```

Superflip and all tests are available at **ideone** or **Try it online!**

The program:

* creates the six faces `YBRGOW` of stickers.
* creates a function, `r`, which *only* rotates the stickers on a face, clockwise a quarter-turn
* creates a function, `U`, which rotates the `U` face clockwise a quarter-turn by applying `r` and rotating the stickers on the top-band of `LFRB` clockwise a quarter-turn
* creates a function, `y`, which performs `r` on the `U` and `D` faces and slices `LFRB`
\- this performs a rotation of the whole cube in the `y` axis (which runs through `U` and `D`)
\- the rotation is clockwise if looking from above
* creates a function `z`, which performs a rotation of the whole cube in the `z` axis clockwise a quarter turn looking at `R` (the axis runs through `R` and `L`) - this time because the way the faces are oriented in our net (same as given in the OP) we have to flip the `B` and `U` faces over (they switch from the horizontal to vertical parts of the net and vice-versa)
* Performs a regex on the input, `input()`, (the moves to be performed) matching a character from `BUDLRF` (actually `B-U`) possibly followed by a character `'i2`
* Performs a mapping from the `'i2` to the number of clockwise turns (the ordinals of these mod `6` does the job, with a dummy `a` to yield `1` when none is present)
* Performs a lookup to map each of these single clockwise turn instructions to a setup of calls to `y` and `z`, a quarter-turn of `U` (which will now be the face instructed), and then the calls to inverse the sequence of the setup performed. Taking the ordinal of the face character modulo by `11` then by `7` maps `B:0 U:1 D:2 L:3 F:4 R:5`, allowing a simple indexing into a string of the function name sequences split by spaces.
* executes the string to actually perform the manoeuvre
* creates a dummy face `d` to shorten the printing
* prints the result by stepping through the rows in the net and the faces in the row (including a dummy face to the left of each of `U` and `D`

Here is the superflip:

```
D:\Python Scripts>python rubiksAscii.py
U R2 F B R B2 R U2 L B2 R U' D' R2 F R' L B2 U2 F2
      Y O Y
      B Y G
      Y R Y
B Y B R Y R G Y G O Y O
O B R B R G R G O G O B
B W B R W R G W G O W O
      W R W
      B W G
      W O W

```
> 9 votes

# Answer
**Python ~~760~~ ~~750~~ 649 Bytes**

shamelessly stole the idea of using only 3 rotations from @Paul Schmitz :D

new version:

```
from numpy import*
c=kron([[32,89,32,32],[66,82,71,79],[32,87,32,32]],ones([3,3])).astype(int)
def x():t=copy(c);c[:3,3:6],c[3:6,3:6],c[6:,3:6],c[3:6,9:],c[3:6,:3],c[3:6,6:9]=t[3:6,3:6],t[6:,3:6],rot90(t[3:6,9:],2),rot90(t[:3,3:6],2),rot90(t[3:6,:3]),rot90(t[3:6,6:9],3)
def y():c[3:6],c[:3,3:6],c[6:,3:6]=roll(c[3:6],3,1),rot90(c[:3,3:6]),rot90(c[6:,3:6],3)
def F():c[2:7,2:7]=rot90(c[2:7,2:7],3)
s=raw_input()
for p in"':i,Fi:FFF,F2:FF,Bi:BBB,B2:BB,Ri:RRR,R2:RR,Li:LLL,L2:LL,Ui:UUU,U2:UU,Di:DDD,D2:DD,B:xxFxx,R:yyyFy,L:yFyyy,U:xxxFx,D:xFxxx".split(','):s=s.replace(*p.split(':'))
for S in s:eval(S+'()')
for r in c:print(''.join(chr(x)for x in r))

```

I mostly just did lots of numpy list slicing and used its built in rotate and roll functions. Input is handled by calling the functions directly with `eval()`

```
from numpy import*
l=[0];c=kron([[32,89,32,32],[66,82,71,79],[32,87,32,32]],ones([3,3])).astype(int)
def i():l[0]();l[0]()
def d():l[0]()
def U():c[:3,3:6]=rot90(c[:3,3:6],3);c[3]=roll(c[3],9);l[0]=U
def D():c[6:,3:6]=rot90(c[6:,3:6],3);c[5]=roll(c[5],3);l[0]=D
def F():c[2:7,2:7]=rot90(c[2:7,2:7],3);l[0]=F
def B():c[3:6,9:]=rot90(c[3:6,9:],3);t=copy(c);c[:,:9],c[1:-1,1:8]=rot90(t[:,:9]),t[1:-1,1:8];l[0]=B
def R():c[3:6,6:9]=rot90(c[3:6,6:9],3);t=copy(c);c[:6,5],c[3:6,9],c[6:,5]=t[3:,5],t[2::-1,5],t[5:2:-1,9];l[0]=R
def L():c[3:6,:3]=rot90(c[3:6,:3],3);t=copy(c);c[3:,3],c[3:6,-1],c[:3,3]=t[:6,3],t[:5:-1,3],t[5:2:-1,-1];l[0]=L
for s in raw_input().replace("'",'i').replace('2','d').replace(' ',''):eval(s+'()')
for r in c:print(''.join(chr(x)for x in r))

```

ungolfed..

```
import numpy as np
last = [0] #store last move to repeat for inverse or double
           #list is shorter syntax than global var

cube = np.array([
[' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '],
[' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '],
[' ',' ',' ','Y','Y','Y',' ',' ',' ',' ',' ',' '],
['B','B','B','R','R','R','G','G','G','O','O','O'],
['B','B','B','R','R','R','G','G','G','O','O','O'],
['B','B','B','R','R','R','G','G','G','O','O','O'],
[' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' '],
[' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' '],
[' ',' ',' ','W','W','W',' ',' ',' ',' ',' ',' ']
]) #ascii ascii codes in golfed version

def i(): #triple move (inverse)
    last[0]()
    last[0]()

def d(): #double move
    last[0]()

def U(): #clockwise upface (yellow)
    cube[:3,3:6] = np.rot90(cube[:3,3:6],3)
    cube[3] = np.roll(cube[3],9)
    last[0] = U

def D(): #clockwise downface (white)
    cube[6:,3:6] = np.rot90(cube[6:,3:6],3)
    cube[5] = np.roll(cube[5],3)
    last[0] = D

def F(): #clockwise frontface (red)
    cube[2:7,2:7] = np.rot90(cube[2:7,2:7],3)
    last[0] = F

def B(): #clockwise backface (orange)
    cube[3:6,9:] = np.rot90(cube[3:6,9:],3)
    tempCube = np.copy(cube)
    cube[:,:9],cube[1:-1,1:8] = np.rot90(tempCube[:,:9]),tempCube[1:-1,1:8]
    last[0] = B

def R(): #clockwise rightface (green)
    cube[3:6,6:9] = np.rot90(cube[3:6,6:9],3)
    tempCube = np.copy(cube)
    cube[:6,5],cube[3:6,9],cube[6:,5] = tempCube[3:,5],tempCube[2::-1,5],tempCube[5:2:-1,9]
    last[0] = R

def L(): #clockwise leftface (blue)
    cube[3:6,:3] = np.rot90(cube[3:6,:3],3)
    tempCube = np.copy(cube)
    cube[3:,3],cube[3:6,-1],cube[:3,3] = tempCube[:6,3],tempCube[:5:-1,3],tempCube[5:2:-1,-1]
    last[0] = L

for character in raw_input('type a move sequence: ').replace("'",'i').replace('2','d').replace(' ',''):
    eval(character+'()')

print("-"*12)

for row in cube:
    print(''.join(character for character in row)) #uses ascii codes in golfed version

```

test input:

```
>>> runfile('C:~/rubiks cube.py', wdir='C:~/python/golf')
U2 L' D
   OYY
   RYY
   RYY
GBBWOOBBBRRY
GBBWRRGGGOOY
OOYGBBWRRGGG
   ROO
   WWW
   WWW

```

Comments or suggestions are greatly appreciated :)
> 8 votes

# Answer
# C, 839 bytes

```
#include <stdio.h>
#define b(c) c,c+1,c+2,c+15,c+28,c+27,c+26,c+13
char a[]="   YYY      \n   YYY      \n   YYY      \nBBBRRRGGGOOO\nBBBRRRGGGOOO\nBBBRRRGGGOOO\n   WWW      \n   WWW      \n   WWW      \n",k;int d[][8]={b(3),b(39),b(42),b(45),b(48),b(81)},e[][12]={50,49,48,47,46,45,44,43,42,41,40,39,3,16,29,42,55,68,81,94,107,76,63,50,29,30,31,45,58,71,83,82,81,67,54,41,109,96,83,70,57,44,31,18,5,48,61,74,39,52,65,107,108,109,73,60,47,5,4,3,65,66,67,68,69,70,71,72,73,74,75,76},i,*j,r,p,q,s;f(int*g,int h){i=h<0?-1:1;for(j=g;j!=g+h;j+=i){k=a[j[3*h]];for(r=3;r--;)a[j[r*h+h]]=a[j[r*h]];a[*j]=k;}}l(int g,int m){f(d[g+m]-m,m?-2:2);f(e[g+m]-m,m?-3:3);}void n(char*o){while(*o){*o-'U'||(p=0);*o-'L'||(p=1);*o-'F'||(p=2);*o-'R'||(p=3);*o-'B'||(p=4);*o-'D'||(p=5);s=*++o=='\''||*o=='i';q=*o=='2';(s||q)&&o++;l(p,s);q&&l(p,0);}printf("%s",a);}

```

As this is not a full program (function with input from a string argument and output to the console), you need to call it like this:

```
int main() {
//  n("U2D2R2L2F2B2");    //checker cube
    n("UDiRL'FBiUD'");    //spotted cube
}

```

Use only one call at a time as the function uses and modifies global variables.

Ungolfed:

```
#include <stdio.h>

char cube[] = "   YYY      \n"
              "   YYY      \n"
              "   YYY      \n"
              "BBBRRRGGGOOO\n"
              "BBBRRRGGGOOO\n"
              "BBBRRRGGGOOO\n"
              "   WWW      \n"
              "   WWW      \n"
              "   WWW      \n";

#define faceMove(offset) offset,offset+1,offset+2,offset+15,offset+28,offset+27,offset+26,offset+13
int faceMoves[6][8] = {
    faceMove(3),    //Up
    faceMove(39),   //Left
    faceMove(42),   //Front
    faceMove(45),   //Right
    faceMove(48),   //Back
    faceMove(81)    //Down
}, lineMoves[6][12] = {
    50,49,48,47,46,45,44,43,42,41,40,39,    //Up
    3,16,29,42,55,68,81,94,107,76,63,50,    //Left
    29,30,31,45,58,71,83,82,81,67,54,41,    //Front
    109,96,83,70,57,44,31,18,5,48,61,74,    //Right
    39,52,65,107,108,109,73,60,47,5,4,3,    //Back
    65,66,67,68,69,70,71,72,73,74,75,76 //Down
};

int rotate(int*move,int rotation){
    int sign=rotation<0?-1:1;
    for(int*submove=move;submove!=move+rotation;submove+=sign){
        char takeout=cube[submove[3*rotation]];
        for(int j=3;j--;)cube[submove[j*rotation+rotation]]=cube[submove[j*rotation]];
        cube[*submove]=takeout;
    }
}

int move(int move,int inverted){
    rotate(faceMoves[move+inverted]-inverted,inverted?-2:2);
    rotate(lineMoves[move+inverted]-inverted,inverted?-3:3);
}

void performMoves(char*instructions){
    while(*instructions){
        int moveIndex;
        *instructions-'U'||(moveIndex=0);
        *instructions-'L'||(moveIndex=1);
        *instructions-'F'||(moveIndex=2);
        *instructions-'R'||(moveIndex=3);
        *instructions-'B'||(moveIndex=4);
        *instructions-'D'||(moveIndex=5);
        int inverted=*++instructions=='\''||*instructions=='i', twice=*instructions=='2';
        (inverted||twice)&&instructions++;
        move(moveIndex,inverted);
        twice&&move(moveIndex,0);
    }
    printf("%s",cube);
}

int main() {
//  performMoves("U2D2R2L2F2B2");    //checker cube
    performMoves("UDiRL'FBiUD'");    //spotted cube
}

```

As you can see, the main idea is to use a fully data-driven approach: The different rotations are expressed as lists of indices that have to be permuted. The permutation code can thus be very short and generic.
> 7 votes

# Answer
# Cubically, 2 bytes

```
¶■

```

Try it online!

Explanation:

```
¶   read a line from stdin, evaluate
 ■  print the cube to stdout

```

---

If extraneous output is allowed, this is an alternative. **1 byte:**

Try it online!

Cubically automatically dumps its memory cube to `STDERR` when the program ends. However, it also prints the notepad beforehand.
> 7 votes

# Answer
# JavaScript (ES6), 820

A porting of the buggy answer by @Paul Schmitz. It's still not completely golfed, but it has the added value that it works.

The main problem in the original answer is that a single function Q is not enough for all the movements involved in a rotation. I had to add 2 other functions O and N. All of them are just called in the right rotation function R.

```
(a,M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]],Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]],N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]],O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]],R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]],X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))],Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]],F=c=>Array(9).fill(c[0]),r='replace',b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`],J=(p,l)=>p.join``[r](/.../g,l))=>(a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx")[r](/\w/g,c=>b=(c<'a'?R:c<'y'?X:Y)(b)),o=J(b[1],`
   $&`),J(b[5],(c,p)=>o+=`
`+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)),o+J(b[3],`
   $&`))

```

*More readable* maybe

```
(
  a,
  // local variables as default parameters
  r='replace',
  F=c=>Array(9).fill(c[0]), // function to fill a 3x3 square
  b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`], // cube status
  // aux functions to perform basic moves
  M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]],
  Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]],
  N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]],
  O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]],
  // R : right side rotation
  R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]],
  // X,Y: to put other sides in place of right side
  X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))],
  Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]],
  // aux function for output
  J=(p,l)=>p.join``[r](/.../g,l),
) => (
  // convert common moves to basic moves
  a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx")
  // then execute each
  [r](/\w/g,c=>b=c<'a'?R(b):c<'y'?X(b):Y(b)),
  // built output in o
  o=J(b[1],'\n   $&'),
  J(b[5],(c,p)=>o+='\n'+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)),
  o+J(b[3],'\n   $&') // returned output
)

```

```
S=
(a,M=a=>[a[6],a[3],a[0],a[7],a[4],a[1],a[8],a[5],a[2]],Q=(a,b)=>[b[0],b[1],a[2],b[3],b[4],a[5],b[6],b[7],a[8]],N=(a,b)=>[b[0],b[1],a[6],b[3],b[4],a[3],b[6],b[7],a[0]],O=(a,b)=>[b[8],a[1],a[2],b[5],a[4],a[5],b[2],a[7],a[8]],R=a=>[M(a[0]),Q(a[2],a[1]),Q(a[3],a[2]),N(a[4],a[3]),O(a[4],a[1]),a[5]],X=a=>[M(a[0]),a[2],a[3],M(M(a[4])),M(M(a[1])),M(M(M(a[5])))],Y=a=>[a[4],M(a[1]),a[0],M(M(M(a[3]))),a[5],a[2]],F=c=>Array(9).fill(c[0]),r='replace',b=[F`G`,F`Y`,F`R`,F`W`,F`O`,F`B`],J=(p,l)=>p.join``[r](/.../g,l))=>(a[r](/(.)2/g,"$1$1")[r](/(.)['i]/g,"$1$1$1")[r](/F/g,"yyyRy")[r](/L/g,"yyRyy")[r](/B/g,"yRyyy")[r](/U/g,"xyRyyyxxx")[r](/D/g,"xyyyRyxxx")[r](/\w/g,c=>b=(c<'a'?R:c<'y'?X:Y)(b)),o=J(b[1],`
   $&`),J(b[5],(c,p)=>o+=`
`+c+b[2].join``.substr(p,3)+b[0].join``.substr(p,3)+b[4].join``.substr(p,3)),o+J(b[3],`
   $&`))

function update() { O.textContent=S(I.value) }

update()
```

```
<input id=I value='U2 Li D' oninput='update()'><pre id=O></pre>
```
> 4 votes

---
Tags: code-golf, ascii-art, graphical-output, rubiks-cube
---