Question

I am currently making a rubik's cube in CSS

Testarea: http://codepen.io/pixelass/pen/lkhIt

Everything works as desired. I can turn all sides (with a helper div)

now I need to store positions after a turn

the cube has a lot of divs with data-attributes which define the position in the 3d grid.
e.g. <a href="#" data-x="1" data-y="1" data-z="1" class="part red blue yellow"> </a>

I basically have an array for each dimension

Here's one level sorted when a rotation of 90deg (one turn) is made on the x axis of the outermost side (see codepen example and click "TRIGGER X 1" once)

The array needs to be modified. Of course there is some kind of pattern but I'm having difficulties figuring it out. Obviously this is the "easiest side-turn". The others will probably be a little more difficult.

When I store the cube I just switch the data-attribute valuesand turn the part in the same direction on the same axis. This part is pretty well thought though and works

So what I need is an algorithm to perform the sorting: (The other levels of that axis will just use the same pattern since only the first value changes (1,2,3))

from

[{
  "x": 1,
  "y": 1,
  "z": 1
}, {
  "x": 1,
  "y": 1,
  "z": 2
}, {
  "x": 1,
  "y": 1,
  "z": 3
}, {
  "x": 1,
  "y": 2,
  "z": 1
}, {
  "x": 1,
  "y": 2,
  "z": 2
}, {
  "x": 1,
  "y": 2,
  "z": 3
}, {
  "x": 1,
  "y": 3,
  "z": 1
}, {
  "x": 1,
  "y": 3,
  "z": 2
}, {
  "x": 1,
  "y": 3,
  "z": 3
}]

to

[{
  "x": 1,
  "y": 3,
  "z": 1
}, {
  "x": 1,
  "y": 2,
  "z": 1
}, {
  "x": 1,
  "y": 1,
  "z": 1
}, {
  "x": 1,
  "y": 3,
  "z": 2
}, {
  "x": 1,
  "y": 2,
  "z": 2
}, {
  "x": 1,
  "y": 1,
  "z": 2
}, {
  "x": 1,
  "y": 3,
  "z": 3
}, {
  "x": 1,
  "y": 2,
  "z": 3
}, {
  "x": 1,
  "y": 1,
  "z": 3
}]
Was it helpful?

Solution

Maybe this will help: you can use the sort method on arrays:

myArr.sort(function(a, b) {
    if (a.z > b.z) {
        return 1;
    } else if (a.z < b.z) {
        return -1;
    } else {
        if (a.y > b.y) {
            return -1;
        } else {
            return 1;
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top