I've finished this challenge from Coderbyte, but inelegantly:
Have the function PrimeChecker(num) take num and return 1 if any arrangement of num comes out to be a prime number, otherwise return 0. For example: if num is 910, the output should be 1 because 910 can be arranged into 109 or 019, both of which are primes.
My solution works by producing an array of all possible permutations of the digits in the num argument, then scanning it for primes:
function PrimeChecker(num) {
// Accounting for 1 not being a prime number by definition
if (num == 1) {
return 0;
}
// Defining an empty array into which all permutations of num will be put
var resultsArray = [];
// Breaking num into an array of single-character strings
var unchangedArray = num.toString().split('');
// Function to push all permutations of num into resultsArray using recursion
function getAllCombos (array, count) {
if (count === num.toString().length) {
return;
}
else {
for (var i = 0; i < array.length; i++) {
var temp = array[count];
array[count] = array[i];
array[i] = temp;
resultsArray.push(array.join(''));
}
return getAllCombos(array, count+1) || getAllCombos(unchangedArray, count+1);
}
}
getAllCombos(unchangedArray, 0);
// Converting the results from strings to numbers and checking for primes
var numArr = [];
resultsArray.forEach(function(val, indx) {
return numArr[indx] = Number(val);
});
for (var i = 0; i < numArr.length; i++) {
var prime = 1;
for (var j = 2; j < numArr[i]; j++) {
if (numArr[i] % j == 0) {
prime = 0;
}
}
if (prime == 1) {
return prime;
}
}
return 0;
}
The problem is that the array of permutations of the num argument which I'm producing is full of duplicates.. I feel like this can be done more efficiently.
For example, running PrimeChecker(123) results in a permutations array of 20 entries, when there only need be 6.
Does anyone have an idea of how to do this more efficiently?