recursive function with an array as input - javascript

I am trying to create a function that gets chest exercises from an array called chest.
This function needs to be able to pick several exercises at random, which I have done using a random pointer. To stop duplicate exercises I compare the chest exercise picked (i.e chest[pointer]) and compare it against all the values in the final array.
If the new exercise is not already in the final array, the newly picked exercise is returned and then pushed onto the final array. If it is already in the final array, the function is called recursively. The idea being that the function will run recursively until it finds a new exercise which has not already been chosen:
Get Chest:
function getChest(arr){
var pointer = 0;
//random array pointer
pointer = Math.round(Math.random() * (chest.length - 1));
//check for duplicate
for(var i = 0; i < arr.length - 1; i++){
if(arr[i].name === chest[pointer].name){
return getChest(arr);
} else {
return chest[pointer];
}
}
};
The main function uses this method to select exerises randomly. The final array is called 'day'.:
function chooseExercises(){
for(i = 0; i <= 5; i++){
ex = getChest(day);
day.push(ex);
}
}
The problem I am having is that there are still duplicates when I run it. Any idea as to what is going wrong? (I am using angularJS)

Modify your function to this,
function getChest(arr){
var pointer = 0;
//random array pointer
pointer = Math.round(Math.random() * (chest.length - 1));
//check for duplicate
for(var i = 0; i < arr.length; i++){
if(arr[i].name === chest[pointer].name){
return getChest(arr);
}
}
return chest[pointer];
};
Basically, the loop is breaking before the value is checked with its full length.
EDIT: also your loop is running over arr.length-1 times, which actually should be just arr.length.

Related

issue with searching through an array and storing the result on a new array

I am trying to create a coin flip game, however I am trying to do things a bit different than what I have seen others do with their code. Essentially I want to store the possible outcomes of a coinflip in an array called before and then create a function that searches through that array and pushes the value of the result of the coin flip into a new array called after. Here is my code so far, but I am getting an error when I am trying to run it.
var before = ["heads" , "tails"];
var after = []
function coinFlip() {
let repeat = 1
for (let i = 0; i <= repeat; i++) {
after.push(before[Math.floor(Math.random() * before.length)])
}
}
coinFlip() //call function
console.log(after);
var before = ["heads" , "tails"];
var after = []
function coinFlip() {
let repeat = 1
for (let i = 0; i < repeat; i++) {
after.push(before[Math.floor(Math.random() * before.length)])
}
}
coinFlip();
console.log(after);
Two things that you're missing, first is you've defined coinFlip function but forgotten to invoke it. Second is that instead of i <= repeat, it should be i < repeat so that it respect the number of repeats that you've defined in repeat

How do I correctly split an array of strings of is it another issue?

I am trying to access a random element from an array of strings as per other examples here on SO. I am using Raphael.js and regions[j] below returns an array of Raphael objects - hence the .data(id). This seems to be ok, but theCountyNames, as outlined in the comment below returns all of the strings as one long string. I am guessing that this is why randCounty returns a single random letter, but when I try appending a comma in the loop (+",") and using split as per this question, I still get one random single letter. Perhaps I am implementing this incorrectly or maybe it is another issue? Thanks.
function pickRandCounty(){
var theCountyNames = new Array();
for (var j = 0; j < regions.length; j++) {
theCountyNames = regions[j].data('id');
document.write(theCountyNames);//THIS GIVES ME THE COMPLETE LIST OF ITEMS IN THE ARRAY BUT ALL AS ONE STRING
//document.write("<hr>");
}
//var randCounty = theCountyNames[Math.floor(Math.random() * theCountyNames.length)];
//document.write(randCounty);//THIS JUST RETURNS ONE RANDOM LETTER??
}
Using Array.prototype.push to append a new item to an Array.
function pickRandCounty(){
var theCountyNames = [],
j;
for (j = 0; j < regions.length; ++j) {
theCountyNames.push(regions[j].data('id'));
}
j = Math.floor(Math.random() * regions.length);
return theCountyNames[j];
}
However, this is not optimised as you can set the length of the Array in advance and you can even completely skip the loop,
function pickRandCounty(){
var j = Math.floor(Math.random() * regions.length);
return regions[j].data('id');
}
The error seems to be in this part of line.
theCountyNames = regions[j].data('id'); //wrong
theCountyNames.push(regions[j].data('id')); //right
Second mistake
document.write(theCountyNames); //it will keep on appending the string in the DOM
document.write("<br>" + theCountyNames);//right

Javascript indexing array issue

Hi I have an array that hold the following numbers, however when I loop though the eachNode function(which iterates 13 times) it repeats all the list elements 13 times. I tested everything but it still produces an error, I'm I executing the for loop correctly?
list[61,67,78]
var len = list.length;
fd.graph.eachNode(function (node) { // loops thru all node id's in graph (13)
for (var i = 0; i < len; ++i) {
if (i in list) {
var nody = list[i]; // I put the number in a variable
var nodess = fd.graph.getNode(nody); //this takes the number and matches it with a node id, it "odjectify" it
if (node.id != nodess.id) { // if the list nodes are not the same
node.setData('alpha', 0); //
node.eachAdjacency(function (adj) { // this make the unmatched nodes disappear
adj.setData('alpha', 0, 'end');
});
}
}
}
});
This line is unneeded:
if (i in list)
The in keyword returns true if its right operand contains the property specified by its left operand. When using this with arrays, it returns unexpected results. The behavior of this keyword is insignificant in this context, so you should simply take it out.
Moreover, you need to create the list array like this:
var list = [61, 67, 78];
...however, when I loop though eachNode (which iterates 13 times) it repeats all the list elements 13 times
It doesn't, it in fact iterates over eachNode 13 times. You also made a for loop which will traverse the list array by its length.
Now that you've given me more detail as to what you want, here is the updated code. I hope it works for you:
fd.graph.eachNode(function (node) {
var flag = false;
for (var i = 0; i < len; ++i)
{
var nody = list[i];
var nodess = fd.graph.getNode(nody);
if (node.id == nodess.id) {
flag = true; break;
}
}
if (flag)
{
node.setData('alpha', 0);
node.eachAdjacency(function (adj) {
adj.setData('alpha', 0, 'end');
});
}
});
This is the behavior by design:
You loop over the graph (13 times as you say), then inside each iteration you loop over your array (3 items).
If you only want to loop once over your array, just move it out of the outer loop

array passed as parameter issue

I've got 2dim array set as global variable populated with numbers on row - 0 and strings on row-1.
But when I passed it as a parameter to a function most of its values modifies into undefined but in one strangely value is kept!?!
function formElements(howMany){
elArr = [];
var w; var surface;
for(var j=0; j<howMany; j++){
w = randomNumber(1,200);
surface = w*randomNumber(1,100);
elArr[0] =[j];
elArr[1] =[j];
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....); //in this function I receive array with these undefined values I mentioned above!!!
}
function randomNumber(x,y) {
return Math.floor((Math.abs(y - x) + 1) * Math.random()) + Math.min(x, y);
}
Could somebody tell me what's wrong?
10x and BR
The references to j make it look like this is inside a loop. In which case, I don't think this is doing what you want:
elArry[0] = [j];
This sets the value of elArray[0] to an array with a single element, j. If you're doing that inside your loop then you're overwriting the arrays every time with a new one with a single element.
EDIT:
And now that you've posted the full loop that's verified. You probably want something like:
function formElements(howMany){
elArr = [[],[]];
for(var j=0; j<howMany; j++){
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....);
}

how to create a loop in a function with another function?

I'm new to Java and I'm doing a uni course. I've been asked to design three functions.I have to find the difference between each adjacent numbers in an array, another to total the array and the last one to calculate the difference using the other functions then write a programme. I'm totally lost on the last function and my tutor has gone away on hols. Here is the code I have done so far. I don't want people doing the code for me but if anyone can advice me what I need to do I would appreciate your advice. I'm not sure how to loop the difference function into the array and store it into the new array I have made. If anyone could explain where I am going wrong I would love to hear from you!
var numberArray = [10,9,3,12];
// function difference will find the highest value of the two numbers,find the difference between them and return the value.
function difference(firstNumber, secondNumber)
{
if (firstNumber > secondNumber)
{
return (firstNumber - secondNumber);
}
else
{
return (secondNumber - firstNumber);
}
}
// function sum will add the total numbers in the array and return the sum of numbers.
function sum(numberArray)
{
numberTotal = 0
for (var total = 0; total < numberArray.length; total = total + 1)
{
numberTotal = numberTotal + numberArray[total]
}
{
return numberTotal
}
/*code the process that calculates a new array containing the differences between all the pairs
of adjacent numbers, using the difference() function you have already written.
This function should be named calculateDifferences() and should accept an array numberArray.
The function should first create a new empty array of the same size as numberArray
It should then calculate the differences between the pairs of adjacent numbers,
using the difference() function, and store them in the new array. Finally, the function should return the new array.
The calculation of the differences should be done in a loop, at each step finding the difference between each
array element and the next one along in the array, all except for the last difference,
which must be dealt with as a special case, because after the last element we have to wrap round to the start again.
So the final difference is between the last and first elements in the array.*/
function calculateDifferences()
var createArray = new Array (numberArray.length);
{
createArray = 0;
for (var c = 0; c < numberArray.length; c = c + 1)
{
createArray = difference(numberArray[c]);
}
{
return createArray
}
}
your implementation of function "calculateDifferences" is not correct.
this function should look like this:
function calculateDifferences()
{
var createArray = new Array (numberArray.length);
for (var c = 0; c < numberArray.length - 1 ; c = c + 1)
{
/*
because of the function "difference" has two parameters (firstNumber, secondNumber) in its declaration, we should give two arguments. (that are adjacent elements in array)
*/
createArray[c] = difference(numberArray[c],numberArray[c+1]);
}
/ *
calculating difference of first and last element of array and
assign it to returning array's last element.
*/
createArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
return createArray;
}
You should index createArray the same way you already do with numberArray[c].

Categories

Resources