Skip to content

Commit

Permalink
Merge pull request #43 from torjusti/feat/wide-moves
Browse files Browse the repository at this point in the history
Feat/wide moves
  • Loading branch information
torjusti authored Dec 26, 2019
2 parents 9a42d86 + b5fad09 commit 77e321a
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 14 deletions.
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ This module contains a collection of Rubik's cube solvers implemented in JavaScr

To install, simply run `yarn install cube-solver` or similar, and require the `cube-solver` module. You can also manually add the bundle file to your webpage using [this unpkg link](https://unpkg.com/cube-solver/dist/bundle.js), in which case the solver will be available globally as `cubeSolver`.

## Example
## Examples

```javascript
// Get a new random-state scramble.
Expand All @@ -22,11 +22,23 @@ cubeSolver.scramble('zbll'); // => R B2 R' U' L U' L U' F2 R2 U' B2 U R2 D' F2 U

## Notes

The solver is pretty slow compared to other solvers such as the GWT compiled version of min2phase, but rather aims to be simple and extensible. The Kociemba solver initializes when solving the first cube, which usually takes around 2 seconds. Generating and solving a random cube takes around 100ms on average, but for some cubes this number can be quite high. The optimal EOLine, FB, Cross and XCross solvers initialize pretty quickly, with the exception of the XCross solver.
The full 3x3 solver is pretty slow compared to other solvers such as the GWT compiled version of min2phase - it rather aims to be simple and extensible. Unless explicitly initialized, the Kociemba solver initializes when solving the first cube, which usually takes around 2 seconds. Generating and solving a random cube takes around 100ms on average, but for some cubes this number can be quite high. The optimal EOLine, FB, Cross and XCross solvers initialize pretty quickly, with the exception of the XCross solver which also takes around 2 seconds. *As a consequence, you probably want to use this library in conjunction with web workers.*

## Documentation

The solver exposes three methods. The first,`cubeSolver.scramble(type = '3x3')`, allows for scrambling the cube or different subsets of it, and `cubeSolver.solve(scramble, type = 'kociemba')` allows for solving the cube or different subsets of it. Solvers are initialized on the first solve, but you can manually initialize them by calling `cubeSolver.initialize(solver)`. See below for a list of available solver types.
The solver exposes three main methods.

- `cubeSolver.scramble(type = '3x3')` lets you generate scrambles for the entire cube or subsets of it --- see below for a list of available scramblers.
- `cubeSolver.solve(scramble, type = 'kociemba')` lets you solve either the entire cube or a subset of it for a given scramble. See below for a list of available solvers.
- `cubeSolver.initialize(solver)` lets you initialize solvers so that the first solve is quicker. See below for a list of available solvers. To speed up random-state *scrambles*, the Kociemba solver should be initialized.

In general, the solvers will put the feature being solved for on the *bottom*. For example, using normal orientation, solving for an XCross will yield a yellow cross with the front-left pair solved. To solve other positions, you can apply pre-moves to your scrambles. This example shows how to find a bottom-left yellow XCross:

```javascript
const scramble = `U2 B2 D R' F R2 U2 L D R2 L2 F2 U R2 U' L2 D F2 R2`;
// Find an optimal solution for cross + the back left pair.
cubeSolver.solve(`y ${scramble}`); // => U L2 F' R' F' D L' D
```

### Available scramble types

Expand All @@ -51,4 +63,4 @@ The solver exposes three methods. The first,`cubeSolver.scramble(type = '3x3')`,
| cross | Solve the CFOP cross. |
| eoline | Solve the ZZ EOLine. |
| fb | Solve the Roux first block, on the bottom left. |
| xcross | Solve an extended CFOP cross. |
| xcross | Solve an extended CFOP cross. |
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cube-solver",
"version": "2.2.0",
"version": "2.3.0",
"description": "Solve Rubik's cube using the Kociemba algorithm.",
"author": "Torjus Iveland <torjusti@gmail.com>",
"main": "dist/bundle.js",
Expand Down
25 changes: 22 additions & 3 deletions src/Search.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parseAlgorithm, formatAlgorithm } from './algorithms';
import { parseAlgorithm, formatAlgorithm, invertAlgorithm } from './algorithms';
import PruningTable from './PruningTable';
import { allMoves } from './cube';

Expand Down Expand Up @@ -113,8 +113,14 @@ class Search {

const indexes = this.settings.indexes || [];

let solutionRotation;

if (this.settings.scramble) {
const moves = parseAlgorithm(this.settings.scramble);
const [moves, totalRotation] = parseAlgorithm(this.settings.scramble, true);

if (totalRotation.length > 0) {
solutionRotation = invertAlgorithm(totalRotation.join(' '));
}

for (let i = 0; i < this.moveTables.length; i += 1) {
indexes.push(this.moveTables[i].defaultIndex);
Expand All @@ -131,7 +137,20 @@ class Search {
const solution = this.search(indexes, depth, this.settings.lastMove, []);

if (solution) {
return this.settings.format ? formatAlgorithm(solution.solution) : solution;
if (this.settings.format) {
const formatted = formatAlgorithm(solution.solution);

if (solutionRotation) {
// If we have rotations in the scramble, apply them to the solution
// and then parse again to remove the rotations. This results in a
// solution that can be applied from the result scramble orientation.
return formatAlgorithm(parseAlgorithm(`${solutionRotation} ${formatted}`));
}

return formatted;
}

return solution;
}
}

Expand Down
107 changes: 101 additions & 6 deletions src/algorithms.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/**
* Numeric representation of the different powers of moves.
*/
// Numeric representation of the different powers of moves.
const powers = {
'': 0,
2: 1,
Expand All @@ -10,29 +8,126 @@ const powers = {
/**
* Check whether or not we are able to parse the given algorithm string.
*/
export const validateAlgorithm = algorithm => /^([FRUBLD][2']?\s*)+$/.test(algorithm);
const validateAlgorithm = algorithm => /^([FRUBLDfrubldxyzMSE][2']?\s*)+$/.test(algorithm);

// Map single-power wide moves to a rotation + moves.
const wideMoves = {
f: ['z', 'B'],
r: ['x', 'L'],
u: ['y', 'D'],
b: ["z'", 'F'],
l: ["x'", 'R'],
d: ["y'", 'U'],
M: ["x'", 'R', "L'"],
S: ['z', "F'", 'B'],
E: ["y'", 'U', "D'"],
};

// Specifies the translation of FRUBLD as performed by rotations.
const rotations = {
x: 'DRFULB',
y: 'RBULFD',
z: 'FULBDR',
};

/**
* Strip rotations and wide moves from an algorithm. Returns
* an array of moves as strings.
*/
const normalize = (moves) => {
// Replace wide moves with rotations + moves.
moves = moves.reduce((acc, move) => {
const axis = move.charAt(0);
const pow = move.charAt(1);

if (wideMoves[axis]) {
return acc.concat(wideMoves[axis].map(m => m + pow));
}

return acc.concat(move);
}, []);

let output = [];

// We store all rotations that were encountered, to map the
// solution to the same final rotation as the scramble.
const totalRotation = [];

// Remove rotations by mapping all moves to the right of the rotation.
for (let i = moves.length - 1; i >= 0; i -= 1) {
const axis = moves[i].charAt(0);
const pow = powers[moves[i].charAt(1)];

if ('xyz'.includes(axis)) {
totalRotation.unshift(moves[i]);

for (let j = 0; j <= pow; j += 1) {
output = output.map(outputMove => rotations[axis]['FRUBLD'.indexOf(outputMove[0])] + outputMove.charAt(1));
}
} else {
output.unshift(moves[i]);
}
}

return [output, totalRotation];
};

/**
* Parses a scramble, returning an array of integers describing the moves.
*/
export const parseAlgorithm = (algorithm) => {
export const parseAlgorithm = (algorithm, returnTotalRotation = false) => {
if (!validateAlgorithm(algorithm)) {
throw new Error('Invalid algorithm provided to algorithm parser');
}

const result = [];

const moves = algorithm.match(/[FRUBLD][2']?/g);
const [moves, totalRotation] = normalize(
algorithm.match(/[FRUBLDfrubldxyzMSE][2']?/g),
);

moves.forEach((move) => {
const moveNum = 'FRUBLD'.indexOf(move.charAt(0));
const pow = powers[move.charAt(1)];
result.push(moveNum * 3 + pow);
});

if (returnTotalRotation) {
return [result, totalRotation];
}

return result;
};

/**
* Computes the inverse of a given algorithm. Rotations are supported.
*/
export const invertAlgorithm = (algorithm) => {
if (!validateAlgorithm(algorithm)) {
throw new Error('Invalid algorithm provided to algorithm parser');
}

const moves = algorithm.match(/[FRUBLDfrubldxyzMSE][2']?/g);

const inverted = moves.reverse().map((move) => {
const axis = move.charAt(0);
const pow = powers[move.charAt(1)];
const inv = pow - 2 * (pow % 3) + 2;

if (inv === 1) {
return `${axis}2`;
}

if (inv === 2) {
return `${axis}'`;
}

return axis;
});

return inverted.join(' ');
};

/**
* Convert an array of integers to a human-readable representation.
*/
Expand Down
14 changes: 14 additions & 0 deletions src/tests/__snapshots__/algorithms.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`algorithms should strip rotations from algorithms correctly 1`] = `
Array [
3,
9,
8,
11,
8,
3,
9,
5,
]
`;
19 changes: 19 additions & 0 deletions src/tests/algorithms.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as algorithms from '../algorithms';

describe('algorithms', () => {
it('allow parsing invalid algorithms', () => {
expect(() => {
algorithms.parseAlgorithm("R U R' U' 1337 R' F R F'")
}).toThrowError();
});

it('should correctly invert a given algorithm', () => {
expect(algorithms.invertAlgorithm("r U R' U' r' F R F'"))
.toEqual("F R' F' r U R U' r'");
});

it('should strip rotations from algorithms correctly', () => {
expect(algorithms.parseAlgorithm("x R u R' u' y' z2 R' f R f'"))
.toMatchSnapshot();
});
});

0 comments on commit 77e321a

Please sign in to comment.