/*
* Rachel Riley Mode: reach the target with the numbers using +, −, × and ÷.
*
* Each step combines two numbers into one, so there's no order of operations.
* Results must be whole numbers above zero, and not every number has to be
* used. Finds the solution with the fewest steps, or the closest number,
* preferring steps that carry on from the previous result, then +, −, × and
* ÷ in that order.
*
* The search runs in short slices so the page stays responsive (and the code
* bin's loop protection, which stops loops running for a second, isn't hit).
*/
const targetInput = document.getElementById( 'target' );
const numberInputs = [ ...document.querySelectorAll( '.rr-numbers input' ) ];
const solveButton = document.getElementById( 'solve' );
const resetButton = document.getElementById( 'reset' );
const stepsList = document.getElementById( 'steps' );
const statusText = document.getElementById( 'status' );
const STEP_DELAY = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches ? 0 : 800;
// The numbers as entered, restored by Reset.
let entered = null;
// Preferred operations: solutions using cheaper ones are chosen.
const OP_COST = { '+': 0, '−': 1, '×': 2, '÷': 3 };
/**
* Compare two lists of operation costs, step by step.
*
* @return {number} Negative if `a` uses preferred operations earlier, positive if `b` does, 0 if the same.
*/
function compareOps( a, b ) {
for ( let i = 0; i < Math.min( a.length, b.length ); i++ ) {
if ( a[ i ] !== b[ i ] ) {
return a[ i ] - b[ i ];
}
}
return a.length - b.length;
}
/**
* The moves possible from a set of tiles.
*
* A tile is a number and the input it's shown in. The result goes in the
* first of the two inputs. Moves that can't help are skipped: × or ÷ by 1,
* and − or ÷ giving one of the numbers back.
*
* Moves using the previous step's result come first, so the search finds
* chains of steps, like a running total, first. In those, + and × are written
* with the running total first, eg `11 × 3`.
*
* @param {Array} tiles Tiles.
* @param {Object|null} last The tile holding the previous step's result.
*/
function* moves( tiles, last ) {
const chained = [];
const others = [];
for ( let i = 0; i < tiles.length; i++ ) {
for ( let j = i + 1; j < tiles.length; j++ ) {
const [ big, small ] = tiles[ i ].value >= tiles[ j ].value ? [ tiles[ i ], tiles[ j ] ] : [ tiles[ j ], tiles[ i ] ];
const slot = Math.min( tiles[ i ].slot, tiles[ j ].slot );
const rest = tiles.filter( ( tile, index ) => index !== i && index !== j );
const usesLast = last !== null && ( tiles[ i ] === last || tiles[ j ] === last );
// In order of preference, see OP_COST.
const options = [ [ '+', big.value + small.value ] ];
if ( big.value - small.value > 0 && big.value - small.value !== small.value ) {
options.push( [ '−', big.value - small.value ] );
}
if ( small.value !== 1 ) {
options.push( [ '×', big.value * small.value ] );
}
if ( small.value !== 1 && big.value % small.value === 0 && big.value / small.value !== small.value ) {
options.push( [ '÷', big.value / small.value ] );
}
for ( const [ op, result ] of options ) {
const runningTotalFirst = usesLast && ( op === '+' || op === '×' ) && small === last;
const tile = { value: result, slot };
( usesLast ? chained : others ).push( {
step: { a: runningTotalFirst ? small : big, b: runningTotalFirst ? big : small, op, result, slot },
tiles: [ ...rest, tile ],
tile,
usesLast,
} );
}
}
}
yield* chained;
yield* others;
}
/**
* Search for the target, trying one step, then two, and so on, so the first
* solutions found have the fewest steps. Yields regularly so it can be sliced.
*
* Of the solutions with the fewest steps, the one with the most steps using
* the previous step's result is chosen, then the one using the preferred
* operations (see OP_COST): the lowest total, then the one using preferred
* operations earlier. The search stops early when every step uses the
* previous result and only adds.
*/
function* search( tiles, target, best ) {
let count = 0;
const visited = new Map();
function* tryFrom( current, steps, remaining, last, chain, ops ) {
for ( const move of moves( current, last ) ) {
if ( ++count % 2000 === 0 ) {
yield;
}
const diff = Math.abs( target - move.step.result );
const length = steps.length + 1;
const nextChain = chain + ( move.usesLast ? 1 : 0 );
const nextOps = [ ...ops, OP_COST[ move.step.op ] ];
const nextCost = nextOps.reduce( ( sum, value ) => sum + value, 0 );
const tied = diff === best.diff && length === best.steps.length && nextChain === best.chain;
const better =
diff < best.diff ||
( diff === best.diff && length < best.steps.length ) ||
( diff === best.diff && length === best.steps.length && nextChain > best.chain ) ||
( tied && nextCost < best.cost ) ||
( tied && nextCost === best.cost && compareOps( nextOps, best.ops ) < 0 );
if ( better ) {
best.diff = diff;
best.value = move.step.result;
best.steps = [ ...steps, move.step ];
best.chain = nextChain;
best.cost = nextCost;
best.ops = nextOps;
}
if ( diff === 0 ) {
// Every step uses the previous result and adds: it can't get better.
if ( nextChain === length - 1 && nextCost === 0 ) {
best.perfect = true;
return;
}
// Further steps from here would only be longer.
continue;
}
if ( remaining > 1 && move.tiles.length > 1 ) {
/*
* The same numbers, previous result and chain so far reach the
* same results: skip them if already tried with operations as
* good or better.
*/
const key = [
move.tiles.map( ( tile ) => tile.value ).sort( ( x, y ) => x - y ).join( ',' ),
move.tile.value,
nextChain,
].join( '|' );
const seen = visited.get( key );
if (
seen &&
seen.remaining >= remaining - 1 &&
( seen.cost < nextCost || ( seen.cost === nextCost && compareOps( seen.ops, nextOps ) <= 0 ) )
) {
continue;
}
visited.set( key, { remaining: remaining - 1, cost: nextCost, ops: nextOps } );
yield* tryFrom( move.tiles, [ ...steps, move.step ], remaining - 1, move.tile, nextChain, nextOps );
if ( best.perfect ) {
return;
}
}
}
}
// Stop after the first length with a solution: longer ones aren't wanted.
for ( let depth = 1; depth < tiles.length && best.diff !== 0; depth++ ) {
visited.clear();
yield* tryFrom( tiles, [], depth, null, 0, [] );
}
}
/**
* Run a generator in slices of about 30ms.
*/
function runInSlices( generator ) {
return new Promise( ( resolve ) => {
function slice() {
const end = performance.now() + 30;
let next;
do {
next = generator.next();
} while ( ! next.done && performance.now() < end );
if ( next.done ) {
resolve();
} else {
setTimeout( slice, 0 );
}
}
slice();
} );
}
function wait( ms ) {
return new Promise( ( resolve ) => setTimeout( resolve, ms ) );
}
function readWholeNumber( input ) {
const value = Number( input.value );
return input.value.trim() !== '' && Number.isInteger( value ) && value > 0 ? value : null;
}
function setStatus( text ) {
statusText.textContent = text;
}
function setBusy( busy ) {
solveButton.disabled = busy;
resetButton.disabled = busy;
solveButton.textContent = busy ? 'Rachel is thinking…' : 'Rachel Riley Mode';
}
/**
* Put the entered numbers back, ready to edit or solve again.
*/
function restore() {
if ( entered ) {
targetInput.value = entered.target;
numberInputs.forEach( ( input, index ) => {
input.value = entered.numbers[ index ];
} );
}
entered = null;
for ( const input of [ targetInput, ...numberInputs ] ) {
input.readOnly = false;
input.classList.remove( 'is-picked', 'is-used', 'is-hit' );
}
stepsList.replaceChildren();
}
/**
* Show the steps one at a time, putting each result in place of its inputs.
*/
async function showSteps( steps ) {
for ( const { a, b, op, result, slot } of steps ) {
const inputs = [ numberInputs[ a.slot ], numberInputs[ b.slot ] ];
inputs.forEach( ( input ) => input.classList.add( 'is-picked' ) );
await wait( STEP_DELAY / 2 );
const item = document.createElement( 'li' );
item.textContent = `${ a.value } ${ op } ${ b.value } = ${ result }`;
stepsList.append( item );
inputs.forEach( ( input ) => {
input.classList.remove( 'is-picked' );
if ( input !== numberInputs[ slot ] ) {
input.value = '';
input.classList.add( 'is-used' );
}
} );
numberInputs[ slot ].value = result;
await wait( STEP_DELAY / 2 );
}
}
async function solve() {
restore();
const target = readWholeNumber( targetInput );
if ( target === null ) {
setStatus( 'The target needs to be a whole number above zero.' );
targetInput.focus();
return;
}
const tiles = [];
for ( const [ slot, input ] of numberInputs.entries() ) {
if ( input.value.trim() === '' ) {
continue;
}
const value = readWholeNumber( input );
if ( value === null ) {
setStatus( 'The numbers need to be whole numbers above zero.' );
input.focus();
return;
}
tiles.push( { value, slot } );
}
if ( tiles.length === 0 ) {
setStatus( 'Enter some numbers first.' );
return;
}
entered = {
target: targetInput.value,
numbers: numberInputs.map( ( input ) => input.value ),
};
for ( const input of [ targetInput, ...numberInputs ] ) {
input.readOnly = true;
}
// A number that's already the target needs no working out.
const already = tiles.find( ( tile ) => tile.value === target );
if ( already ) {
numberInputs[ already.slot ].classList.add( 'is-hit' );
setStatus( `${ target } is already there. Too easy.` );
return;
}
const best = { diff: Infinity, value: null, steps: [], chain: 0, cost: 0, ops: [], perfect: false };
for ( const tile of tiles ) {
const diff = Math.abs( target - tile.value );
if ( diff < best.diff ) {
Object.assign( best, { diff, value: tile.value, steps: [] } );
}
}
setBusy( true );
setStatus( 'Rachel is thinking…' );
await runInSlices( search( tiles, target, best ) );
setStatus( 'Here’s how…' );
await showSteps( best.steps );
setBusy( false );
const last = best.steps.at( -1 );
if ( last && last.result === best.value ) {
numberInputs[ last.slot ].classList.add( 'is-hit' );
}
const stepCount = `${ best.steps.length } ${ best.steps.length === 1 ? 'step' : 'steps' }`;
setStatus(
best.diff === 0
? `Solved in ${ stepCount }.`
: `There’s no exact answer. The closest is ${ best.value }, ${ best.diff } away, in ${ stepCount }.`
);
}
solveButton.addEventListener( 'click', solve );
resetButton.addEventListener( 'click', () => {
restore();
setStatus( 'Enter the target and numbers, then call in Rachel.' );
targetInput.focus();
} );