Skip to content

Instantly share code, notes, and snippets.

@everettcaleb
Created February 23, 2017 06:30
Show Gist options
  • Save everettcaleb/3d96568ab8c489dc5c5eb4b32b8083df to your computer and use it in GitHub Desktop.
Save everettcaleb/3d96568ab8c489dc5c5eb4b32b8083df to your computer and use it in GitHub Desktop.
Prime factor card trick (finds card in unsorted deck using prime factor split sorting)
// basically, you can guess ANY card by splitting the deck into prime factor piles and placing the pile with their
// chosen card on top every time. After you run out of prime factors for the number of cards in the deck, their card
// will be on top of the chosen pile
const PRIMES = [ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 ];
const _ = require('lodash');
const readline = require('readline');
const deckSize = 54;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// initial deck
var cards = [];
for(let i = 0; i < deckSize; i++) {
cards.push(i);
}
function factor(number) {
var rprimes = PRIMES.slice().reverse();
var factors = [];
for(let p of rprimes) {
while(number % p == 0) {
factors.push(p);
number /= p;
}
}
return factors.reverse();
}
function distribute(array, sets) {
var setArrays = [];
for(let i = 0; i < sets; i++) {
setArrays.push([]);
}
for(let i = 0; i < array.length; i++) {
setArrays[i % sets].push(array[i]);
}
return setArrays;
}
function printStacks(stacks) {
for(let i = 0; i < stacks[0].length; i++) {
// for the first one, print a heading
if(i == 0) {
console.log(stacks.map((s,j) => j + 1).join('\t'));
console.log('======================');
}
console.log(stacks.map(s => s[i]).join('\t'));
}
}
function doIteration(cards, remainingFactors) {
var factor = remainingFactors.splice(0, 1);
if(!factor.length) { console.log('Your card must be ' + cards[0]); return process.exit(); }
var stacks = distribute(cards, factor[0]);
printStacks(stacks);
rl.question('Which stack is your card in? ', answer => {
var index = answer - 1;
doIteration(_.flatten(stacks.splice(index, index + 1).concat(stacks)), remainingFactors);
});
}
doIteration(cards, factor(deckSize));
// factor(deckSize).forEach(factor => {
// var stacks = distribute(cards, factor);
// printStacks(stacks);
// var index = _.findIndex(stacks, stack => stack.indexOf(targetCard) >= 0); // or prompt the user.
// cards = _.flatten(stacks.splice(index, index + 1).concat(stacks));
// });
//
// console.log(cards);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment