How would you represent a Rubik's Cube in code?

前端 未结 11 1782
清酒与你
清酒与你 2020-12-07 09:52

If you were developing software to solve a Rubik\'s Cube, how would you represent the cube?

11条回答
  •  时光说笑
    2020-12-07 10:12

    The shortest representation is something like this one: codepen.io/Omelyan/pen/BKmedK

    The cube is unwrapped in 1D array (vector of 54 elements). A few-line rotation function swaps stickers and based on the cube's symmetry. Here's complete working model in C, I made it in 2007 when was a student:

    const byte // symmetry
      M[] = {2,4,3,5},
      I[] = {2,0,4,6};
    
    byte cube[55]; // 0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1, ... need to be filled first
    
    #define m9(f, m) (m6(f, m)*9)
    
    byte m6(byte f, byte m) {return ((f&~1)+M[m+(f&1)*(3-2*m)])%6;}
    
    void swap(byte a, byte b, byte n) {
      while (n--) {byte t=cube[a+n]; cube[a+n]=cube[b+n]; cube[b+n]=t;}
    }
    
    void rotate(byte f, byte a) { // where f is face, and a is number of 90 degree turns
      int c=m9(f, 3), i;
      swap(c, c+8, 1);
      while (a--%4) for (i=2; i>=0; --i)
        swap(m9(f, i) + I[i], m9(f, i+1) + I[i+1], 3),
        swap(f*9+i*2, f*9+i*2+2, 2);
      swap(c, c+8, 1);
    }
    

提交回复
热议问题