How to stop random letter picking from doing duplicate letters [duplicate] - javascript

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?

var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}

The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.
Edit
Here's a brief Knuth Shuffle algorithm example:
void shuffle(vector<int> nums)
{
for (int i = nums.size()-1; i >= 0; i--)
{
// this line is really shorthand, but gets the point across, I hope.
swap(nums[i],nums[rand()%i]);
}
}

Try this once:
//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
shuffle = function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
shuffle(testArr);

This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.
var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
{
r = Math.floor(Math.random()*12); // Get a random index
if (tempArray[r] === undefined) // If the index hasn't been used yet
{
document.write(numberArray[r]); // Display it
tempArray[r] = true; // Flag it as have been used
}
else // Otherwise
{
i--; // Try again
}
}
Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.

If I understand you correctly, you want to shuffle your array.
Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).
You can then print the first nine array elements, which will be in random order and not repeat.

Here is a generic way of getting random numbers between min and max without duplicates:
function inArray(arr, el) {
for(var i = 0 ; i < arr.length; i++)
if(arr[i] == el) return true;
return false;
}
function getRandomIntNoDuplicates(min, max, DuplicateArr) {
var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
if (DuplicateArr.length > (max-min) ) return false; // break endless recursion
if(!inArray(DuplicateArr, RandomInt)) {
DuplicateArr.push(RandomInt);
return RandomInt;
}
return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}
call with:
var duplicates =[];
for (var i = 1; i <= 6 ; i++) {
console.log(getRandomIntNoDuplicates(1,10,duplicates));
}

const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
result = nums[Math.floor(Math.random()*nums.length)];
const index = nums.indexOf(result);
nums.splice(index, 1);
console.log(i+' - '+result);
}

Related

Maximizing efficiency of this while loop

I have a while loop that is supposed to randomly plant numberOfTruth true values in a 2 dimensional. I am only to change them if they are not true already, and only do so for numberOfTruths times:
function truthfulArray(maxY, maxX, numberOfTruths, array) {
var x;
var y;
var counter = 0;
while (counter < numberOfTruths) {
x = generateRandomNumber(maxX);
y = generateRandomNumber(maxY);
if (!array[x][y]) {
array[x][y] = true;
counter++;
}
}
return array;
}
I could see the issue with its optimization in relation to the size of 2 dimensional array and as the numberOfTruths approaches the product of maxY and maxX it would waste alot of resources to complete the task. I was wondering what tweaks I can make to the function to make it more efficient. Thanks in advance!
*** generateRandomNumber(max) is a simple function that returns a random number from 0 to the max value entered.
Based on #Bergi's comment, here's one optimization. It assumes the array is empty to begin with (or rather, it doesn't care and just overwrites things).
It's slower when the fill factor (N / (X * Y)) is low (testing with X = Y = 500), but seems to win out over the original implementation at about 40%, and is decisively faster (like 3x) at 80%. (You might want to use that as a heuristic.)
The general idea is that we first fill random rows from the rows' start, then spread out each row using Fisher-Yates shuffle. I've transposed the y and x compared to the original, because that's just how I'm used to dealing with 2D arrays. :D
function shuffle(array) { // h/t https://bost.ocks.org/mike/shuffle/
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function truthfulArrayFillRows(maxY, maxX, numberOfTruths, array) {
var nLeft = numberOfTruths;
var nSeededPerRow = new Array(maxY).fill(0);
// Seed rows randomly with trues starting from the left
while(nLeft > 0) {
var y = generateRandomNumber(maxY);
var x = nSeededPerRow[y];
if(x < maxX) {
array[y][x] = true;
nLeft --;
nSeededPerRow[y] ++;
}
}
// Shuffle the rows we seeded
for(var y = 0; y < maxY; y++) {
if(nSeededPerRow[y] > 0) {
shuffle(array[y]);
}
}
return array;
}
Instead of randomly selecting numberOfTruth many positions of all possible positions, you could randomly select numberOfTruth many of only the valid positions. To do that, you would have to find those positions first.
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
function chunkArray(myArray, chunk_size){
var results = [];
while (myArray.length) {
results.push(myArray.splice(0, chunk_size));
}
return results;
}
function flatten(array) {
var flattened=[];
for (var i=0; i<array.length; ++i) {
var current = array[i];
for (var j=0; j<current.length; ++j)
flattened.push(current[j]);
}
return flattened;
}
function truthfulArray(maxY, maxX, numberOfTruths, array){
var flatArray = flatten(array);
var validPositions = flatArray.map(function(e, i){if(!e) return i});
var randomPositions = shuffle(validPositions).slice(0, numberOfTruths);
randomPositions.forEach(function(i){flatArray[i] = true;});
return chunkArray(flatArray, maxY);
}
var maxX = 20, maxY = 30;
var array = Array(maxX).fill(Array(maxY).fill(false));
truthfulArray(maxY, maxX, 40, array);
If this approach is more efficient depends on your data. If there are many valid positions to choose from, your code should be totally fine and efficient. The more trues there are in the array the less likely it is that your code (randomly) hits them. In that case the approach I described will be more efficient.
I hope you find that helpful.

Getting the prime factors of two arrays

Hello guys I am trying to create an LCM function that takes in two numbers. The findCommonMultiple() function in this piece of code basically returns an array for the prime factors for that number. What I'm trying to do in this function is to check if there are duplicates in both arrays and if there are any that number will be pushed inside a new array. After a number has been pushed the inner loop should break and continue to the next iteration. If both numbers are not equal to each other they both will be pushed. This also goes on even if one of the arrays goes over their index. After all the duplicate factors and unique ones have been pushed I will begin to multiply them and return the LCM of both numbers. I have yet to create a helper function for that but I need to fix this problem first.
function leastCommonMultiple(num1, num2){
var prime1 = findPrimeFactors(num1);
var prime2 = findPrimeFactors(num2);
var primes = [];
var lcm = 1;
for(var i = 0; i < prime1.length; i++){
var factor1 = prime1[i];
for(var j = i; j < prime2.length; j++){
var factor2 = prime2[j];
if(factor1 === factor2){
primes.push(factor1);
break;
} else if(factor1 === undefined && factor2 > 0){
primes.push(factor2);
} else if(factor2 === undefined && factor2 > 0){
primes.push(factor1)
} else {
primes.push(factor1);
primes.push(factor2);
break;
}
}
}
return primes;
}
EDIT:
So I'm adding a test case. So if I have values 26 and 24 passed I would get two arrays. One would be [2, 2, 2, 3] and the other would be [2, 13]. This function will take my duplicates in side the new array and add in all the others that aren't duplicates so: [2] is in first because both arrays have 2 and then [2, 2, 2, 3, 13] the rest of the numbers without duplicates gets added into the array.
If all you need is unique items from both the arrays, I suggest doing it this way,
First concatenate the two arrays and store it in a new array, in this case,
var tempPrimes= prime1.concat(prime2);
Then just write a simple filter to filter out unique values,
var primes = tempPrimes.filter(function(item, pos){
return tempPrimes.indexOf(item)== pos;
});
If you also want to remove 0 values, then just modify it a bit,
var primes = tempPrimes.filter(function(item, pos){
return tempPrimes.indexOf(item)== pos && tempPrimes[pos]!=0;
});
Hope I helped :)
Edit (after further clarification of the question):
var tempPrimes= prime2.filter(function(item) {
return prime1.indexOf(item) < 0;
});
var primes= prime1.concat(tempPrimes);
When your arrays of prime factors are sorted, which I think they are, you can just traverse them simultaneously. If one of the array heads is smaller than the other, advance that head and push it to the result array. If both array heads are equal, push the head value and advance both heads. That way, you don't have nested loops.
The following code does this and creates arrays or the least common multiple and the greatest common divisor at the same time:
var prime1 = findPrimeFactors(num1);
var prime2 = findPrimeFactors(num2);
var lcm = [];
var gcd = [];
let i = 0;
let j = 0;
while (i < prime1.length && j < prime2.length) {
if (prime1[i] < prime2[j]) {
lcm.push(prime1[i++]);
} else if (prime1[i] > prime2[j]) {
lcm.push(prime2[j++]);
} else {
gcd.push(prime1[i]);
lcm.push(prime1[i]);
i++;
j++;
}
}
while (i < prime1.length) lcm.push(prime1[i++]);
while (j < prime2.length) lcm.push(prime2[j++]);
Another way to solve this is to ceate a count dictionary for both numbers. Merge the two dicts by adding the maximum count for each key to the result dict. This method doesn't require sorted prime factor arrays:
var pmax = {}; // result count dict
var pmax2 = {}; // auiliary count dict of primes2
for (let i = 0; i < prime1.length; i++) {
let p = prime1[i];
pmax[p] = (pmax[p] || 0) + 1;
}
for (let i = 0; i < prime2.length; i++) {
let p = prime2[i];
pmax2[p] = (pmax2[p] || 0) + 1;
}
for (let k in pmax2) {
pmax[k] = Math.max((pmax[k] || 0), pmax2[k]);
}
for (let k in pmax) {
let n = pmax[k];
while (n--) lcm.push(k);
}
Finally, the easiest way to calculate the least common multiple might be to calculate the greatest common divisor with Euclid's algorithm and to apply the relation
lcm(a, b) = a * b / gcd(a, b)
(But be careful, because that method might cause overflow for large numbers.)
There was a simpler way to get the lcm of two numbers. My solution was good but it needed more work.
function lcm(num1, num2){
for(var i = 1; i <= num1 * num2; i++){
if(i % num1 === 0 && i % num2 === 0){
return i;
}
}
}

hackerrank circular array rotation terminated due to timeout in Javascript

I'm stuck on the circular array rotation algorithm on hackerrank with timeout issues and having trouble making it more efficient.
I'm using javascript:
function processData(input) {
var arr = new Array(4);
var arrInt = [];
var n, k, q, index, temp;
arr = input.split(" ", 3); //input is a string, get n,k,q from this
arrInt = input.split("\n");
n = parseInt(arr[0]);
k = parseInt(arr[1]);
q = parseInt(arr[2]);
var arrIntI = new Array(n);
arrIntI = arrInt[1].match(/\d+/g); //read in integer array
arrInt.shift();
arrInt.shift();
for(i = 0; i < k; i++){ //rotate array k times
arrIntI.unshift(arrIntI.pop()); //Timeout on cases: 5, 9, 10, 12, 13, 14; passes all others!!!!!!
//********************** Manual rotation:
//Timeout on cases: 5, 7, 9, 10, 12, 13, 14; Worse that Pop/unshift!!
//temp = arrIntI[n-1];
//for(l = n; l > 0; l--){
// arrIntI[l] = arrIntI[l - 1];
//}
//arrIntI[0] = temp;
//delete arrIntI[n];
//*******************************
}
for(j = 0; j < q; j++){
index = arrInt[j];
console.log(arrIntI[index]);
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
I tried replacing the unshift/pop to rotate the array with a for loop but it didn't help the time out cases.
Thanks in advance!!
You don't need to actually rotate the Array at all, you can compute everything by just playing with the indices.
function int(v){ return v|0 }
function processData(input) {
//parse input string
var rows = input.split("\n");
var values = rows[1].split(" ");
var [n,k,q] = rows[0].split(" ").map( int );
//a minimal validation of the input string
if(values.length !== n || rows.length-2 !== q)
throw new Error("inconsistent imput");
//compute a positive offset
var offset = n - k%n;
//the requested indices start in row 3 (index 2)
return rows.slice(2)
//compute the offset positions, and return the particular values
.map(m => values[ ( int(m) + offset )%n ])
.join("\n")
}
Edit: Sorry, I'm a bit late with explaining this.
First, imagine you have a clock (one of the classic round ones with hands on it), and you get the excersize: "rotate the numbers on the clock 5 hours to the left, and then tell me wich numbers are at positions for 1, 3 and 6 o'clock?"
how do you do that? Would you start dismounting the clock and then, 5 times, moving each number one position to the left?
I bet you'd not touch the numbers at all, but simply say to yourself: "rotate 5 hours to the left, then every position shows the number 5 indices to the right of the asked position", and when asked for the actual numbers at a particular index you go to index 3 for example, add 5 indices, and tell the number you read at that position.
That's how this works. I simply add the asked index and the offset, and return the value at that position.
Is it clear now, how this works?
As far as i know the following is the fastest array rotater. It rotates an array by provided amount (n) and direction (+/-)
Array.prototype.rotate = function(n){
var len = this.length;
if (n % len === 0) return this.slice();
else for (var i = 0, res = Array(this.length); i < len; i++) res[i] = this[(i + (len + n % len)) % len];
return res;
};
function rotation (arrData, position) {
var newArr = arrData.slice();
var arrLen = newArr.length;
var num = (position < 0)
? arrLen-(position%arrLen)
: position%arrLen;
var tempArr = newArr.splice(0, num);
newArr.push.apply(newArr, tempArr);
return newArr;
}
It will rotate according to the input
var a = [11,2,3,4,5];
rotation(a, 42); // [3, 4, 5, 11, 2]
It works pretty well in timeout cases also.
Hope this helps ! Thanks
Working example : http://jsbin.com/rahidox/edit?html,js,console
function circularArrayRotation(a, k, queries) {
let y;
let x=[]
for (let i = 0; i < k; i++) {
y = a.pop()
a.unshift(y) // no timeout issue, might be a bit longer but it works.
}
for(let j = 0; j < queries.length; j++) {
x.push(a[(queries[j])])
}
return x
}

Need to increase performance in function that finds earliest pair that equals a given sum

I have a function that takes an array and a number. It scans the array for the two numbers that appear earliest in the array that add up to the number. I would like to know, performance-wise, what could help this function run faster. It has to process a list of like 10,000,000 items in under 6 seconds. I have refactored it a few times now, but still not getting there.
What is the best array iteration method for speed? I assumed for loops would be the slowest so I chose map. Is there a faster way? every()?
NOTE: the provided array could have duplicate, positive, or negative numbers (let's say up to 1000000...for now).
var low_pair = function (ints, s) {
var lowNum = ints.length, lowMatch, highNum, clone = [], i;
for (i = 0; i < ints.length; i++) {
clone[i] = ints.map(function (n, ind) {
if (ind !== i && ints[i] + n == s) {
i > ind ? highNum = i : highNum = ind;
if (highNum < lowNum) {
lowNum = highNum;
lowMatch = [ints[i], ints[ind]];
}
}
});
}
return lowMatch;
};
We are going to create a function that returns the earliest pair of elements that add up to the needed sum:
function find_pair(l, s) {
var min_indexes = {};
for (var i = 0; i < l.length; i++) {
var a = l[i];
if ((s - a) in min_indexes)
return [s - a, a];
if (!(a in min_indexes))
min_indexes[a] = i;
}
}
For this purpose, for every number we process, we store its minimum index. If we currently process number a, we check if s - a has its minimum index set. If yes, this means we found our wanted sum and we return both elements.
For example:
> var l = [2, 3, 4, 5, 5, 7, 8]
> find_pair(l, 10)
[5, 5]
> find_pair(l, 6)
[2, 4]
> find_pair(l, 5)
[2, 3]
> find_pair(l, 15)
[7, 8]
> find_pair([5, 9, 13, -3], 10)
[13, -3]
What is the best array iteration method for speed?
See What's the fastest way to loop through an array in JavaScript? for that. But notice the answers there might be deprecated, and current engines are better at optimising different things. You should always benchmark yourself, in your own target environment.
However, instead of looking for raw speed and microoptimisations, you should try to improve your algorithm. In your case, you can double the speed of your function by simply starting the inner loop at i so you don't visit all combinations twice. Also, by returning early from the function you can speed up the average case (depending on your data). To find the "earliest pair" you don't have to loop through the entire array and calculate a minimum, you just have to iterate the pairs in the chosen order. If the data is ordered (or at least skewed to some distribution) you could take advantage of that as well.
I'd use
function firstPair(ints, s) {
var len = ints.length;
for (var end = 0; end < len; end++)
for (var i=0, j=end; i<end; i++)
if (i != --j && ints[i]+ints[j] == s)
return [i, j];
for (var start = 0; start < len; start++)
for (var i=start, j=len; i<len; i++)
if (i != --j && ints[i]+ints[j] == s)
return [i, j];
return null;
}
As suggested by the other answers, if the range of the values in your array is limited, you could drastically reduce the complexity of your algorithm by using a lookup table - trading memory for performance. Using a bitmap for already-occured integers, it could look like this:
function firstPair(ints, s) {
var map = []; // or, if domain is known and typed arrays are supported, use
// var map = new Uint16Array(Math.ceil(domainSize / 16));
for (var i=0; i<ints.length; i++) {
var x = ints[i],
r = s - x;
if (map[r >> 4] & (1 << (r & 0xF))) // get
return [r, x];
map[x >> 4] |= 1 << (x & 0xF); // set
}
return null;
}
The main problem is that your current function complexity is O(n^2) which is way too high for a 10000000 element array. The map function iterates through the entire array. So you make 10000000 * 10000000 = 100 trillion "operations". The complexity needs to be decreased. My best guess -> use a hash table within a linear loop. Below is my example code with a worst case test of 10 million elements that runs in around 8 seconds on my old machine. It makes only 10 million runs instead of 100 trillion.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var low_pair = function (ints, s) {
var found = {};
var lowMatch;
for (var i = 0; i < ints.length; i++) {
var num = ints[i];
var prevNum = s-num;
if (found[prevNum] === true){
if (prevNum>num){
lowMatch = [num, prevNum];
} else {
lowMatch = [prevNum, num];
}
break;
} else {
found[num] = true;
}
}
return lowMatch;
};
var test_array_size = 10000000;
var test_array = new Array(test_array_size);
for (var i=0;i<test_array_size;++i){
test_array[i] = test_array_size-i;
}
console.log("Array initialized");
var start = new Date().getTime();
console.log(low_pair(test_array, 12));
var end = new Date().getTime();
console.log("Running time: "+(end-start)+" ms");
</script>
<head>
<body>
</body>
</html>
This function consistently runs a 50,000,000 items array in 0ms:
var low_pair = function (s) {
var ints = [];
for(var i = 0; i < 50000000; i++) {
ints.push(Math.floor(Math.random() * 9));
}
console.time('pair');
var counter = 1;
for (var i = 0; i < ints.length; i++) {
var sum = ints[i] + ints[counter];
if (i !== counter) {
if (sum === s) {
console.timeEnd('pair');
return console.log([ints[i], ints[counter]]);
}
}
if (i == counter) {
counter++;
i = -1;
}
}
console.time('pair');
console.log( undefined);
};

string addition I coderbyte completely stumped

Can anyone explain the solution to me like a 6 year old? I haven't been able to make sense of the solutions. Maybe some code comments?
Thank you.
I've spent the last 2 hours on coderbyte trying to solve this one. Here's the question:
Have the function ArrayAdditionI(arr) take the array of numbers stored
in arr and return the string true if any combination of numbers in the
array can be added up to equal the largest number in the array,
otherwise return the string false. For example: if arr contains [4, 6,
23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 =
23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
I've scoured the internet, read through a bunch of people's solutions from the people's answers on coderbyte itself, but without any comments I'm really struggling to figure out how this is done. I've started over countless times, so I'm not even sure if this last attempt is any better or not.
I understand that I'll need to loop through somehow and test every combination index 5, index 4, index 3, index 2, index 1, AND every combination of less than all of those (ie just index 5 and index 3). I just can't figure out how to do that. If I knew the list would always be an array of 5 numbers, and it required all 5, I would write 5 loops all equally nested inside of one big one, right? However, with the added complexity of not requiring all numbers and not knowing the length of the array for all cases, I am completely stumped. I tried using Math.floor(Math.random() * array.length); to generate a list of numbers... but that didnt work either.
function ArrayAdditionI(arr) {
var longest = arr.sort( function(a,b) { return a-b });
var longest = longest[longest.length - 1];
var sumArr = function (arrb) {
var sum = 0;
for (var z = 0; z < arrb.length; z++){
sum += arrb[z];
}
return sum;
};
for (var i = 0; i > arr.length; i++) {
for (var y = 0; y > arr.length; i++) {
testArr.push(arr[i]);
if (sumArr(testArr) === longest) {
return true;
}
testArr.push(... its 4am and I'm stumped!...)
}}
// code goes here
return false;
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
ArrayAdditionI(readline());
A fairly simple to understand and common solution to the problem is as follows. It basically starts by looping forward through the array (loop i) by adding each subsequent number (loop j). If loop j finishes without a solution, loop k begins and removes each subsequent number. Then i increments and the loops start over.
function ArrayAdditionI(arr) {
arr.sort(function(a,b){return a - b})
var largest = arr.pop(); // Set largest to last (largest) array value
var sum = 0;
for (var i = 0; i < arr.length; i++){ // Start outer loop
sum += arr[i];
for (var j = 0; j < arr.length; j++){ // Start inner to begin sum
if (i != j) { // Ensure we don't add the same array index to itself
sum += arr[j];
console.log(sum);
if (sum == largest) {
return true;
}
}
}
for (var k = 0; k < arr.length; k++) { // If no match, start 2nd loop to re-iterate removing index values
if (i != k) {
sum -= arr[k];
console.log(sum);
if (sum == largest) {
return true;
}
}
}
sum = 0; // Reset sum for outer loop
}
return false;
}
The comment by thefourtheye basically told you the name of the problem and what to search for on google.
Solutions in java code would be the following...
1) find all subsets that sum to a particular value
This is the theory and pseudocode.
2) How to implement the Sum of Subsets problem in Java
Change the code to return what you wish if number of sets > 0 .
3) Modify GetAllSubsetByStack in below code to stop when a set is found:
https://codereview.stackexchange.com/questions/36214/find-all-subsets-of-an-int-array-whose-sums-equal-a-given-target
We did a similar recursion for a "MakeChange" algorithm at a meetup I went to last night. This morning I took a look at this problem with fresh eyes after not looking at it for a few weeks. Here's what I came up with.
Essentially: sort the array to biggest to smallest, shift that one off and declare it "goal", then recursively reduce an array by slicing it smaller and smaller each recurse, when the array reaches 0 length, randomize the original array and begin reducing again.
return true if goal = total (ie the reduce)
return false if ive randomized the array more than 1000 times.
function ArrayAdditionI(arr) {
var originalArr = arr.sort(function(a,b) {return b-a});
var goal = arr.shift();
var counter = 0;
function randomArray(array) {
for (var i = array.length - 1; i > 0; i -= 1){
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function recurse(arr) {
if (arr.length == 0){
counter++
var newArr = randomArray(originalArr);
return recurse(newArr);
} else {
var total = arr.reduce(function(a,b) {return a+b});
if (goal == total){
return true
} else if (counter == 1000) {
return false
} else {
newArr = arr.slice(1);
return recurse(newArr);
}
}
}
// code goes here
return recurse(originalArr);
}

Categories