Problem 49

Run Settings
LanguageJavaScript
Language Version
Run Command
function isPrime(number) { if (number == 1) {return false} const threshold = Math.ceil(Math.sqrt(number)) for (let i = 2; i < threshold+ 1; i++) { if ( number % i === 0) { return false; } } return true; } function numberToArray(inputNumber) { return inputNumber.toString().split('').map(x => parseInt(x)); } function arrayToNumber(inputArr) { return [...inputArr].reverse().reduce((a,b,index) => a + b * 10 ** index, 0) } function findAllPrimePermutations(inputNumber) { const inputArr = numberToArray(inputNumber); const findNext = (chosenArr, toChooseArr) => { if (toChooseArr.length === 0) { return [chosenArr]} numArr = [] for (let i = 0; i < toChooseArr.length; i++) { const b = [...toChooseArr]; const c = b.splice(i,1); numArr = [...numArr, ...findNext([...chosenArr, ...c], [...b])] } return numArr; } return findNext([], [...inputArr]).map(arrayToNumber).filter(isPrime).filter(removeIfDuplicate) } function removeIfDuplicate(element, index, array) { for (let i = 0; i < index; i++) { if (array[i] === element) { return false; } } return true; } // console.log(findAllPrimePermutations(1009)) function collectDistances(inputArr) { const workArr = [...inputArr] workArr.sort(); const resultArr = []; for (let i = 0; i < workArr.length; i++) { for (let j = i + 1; j < workArr.length; j++) { resultArr.push([workArr[i], workArr[j], workArr[j] - workArr[i]]); } } return resultArr; } // console.log(collectDistances(findAllPrimePermutations(1487)).sort()) function findSolution() { const resultArr = [] for (let i = 1000; i < 10000; i++) { if (!isPrime(i)) {continue} const workArr = collectDistances(findAllPrimePermutations(i)).sort((a,b) => (b[2]-a[2])) for (let j =1; j < workArr.length; j++) { if (workArr[j][2] === workArr[j-1][2] && ((workArr[j-1][1] == workArr[j][0]) ||(workArr[j-1][1] == workArr[j][0]))) { resultArr.push([workArr[j-1][0], workArr[j-1][1], workArr[j][1]]) } } } return resultArr } console.log(findSolution())
Editor Settings
Theme
Key bindings
Full width
Lines