Can someone explain how this for loop works? - javascript

This function returns the largest number from an array. I need help on understanding the if part: if (arr[i] > maxNumber) {maxNumber = arr[i]}. Using pseudocode or an explanation how exactly does this work?
function max(arr){
let maxNumber = 0
for (i = 0; i < arr.length; i++) {
if (arr[i] > maxNumber){
maxNumber = arr[i]
}
}
return maxNumber
}
console.log(max([1,2,3,40,5]));

function max(array) {
largest number is equal to 0;
for (i is equal to 0; i is less than the length of array; increment i by 1 each time) {
if (the item at the current index is greater than the previous largest number) {
set the largest number to to the item at the current index;
}
}
return largest number which will be 0 if no larger number is found
}
Worth noting that if all values in the array are negative, it will return 0;
This will work for negative numbers too.
function max(arr){
let maxNumber = -Infinity
for (i = 0; i < arr.length; i++) {
if (arr[i] > maxNumber){
maxNumber = arr[i]
}
}
return maxNumber
}

What this part: if (arr[i] > maxNumber) {maxNumber = arr[i]} doing is checking if the current array member is greater than the current maxNumber and if it is changing the maxNumber value to the current array.
In short, max(whatEverArray) will always return zero or the biggest value of the array. and if it return zero, means all the array values are either zero or less than zero.

Related

Running sum until a negative number

Please how can I use the index 0 in a for-loop when testing an empty array for a drumming sum.
Also, the single negative value returns zero
The sum should stop when a negative number is encountered
let sum = 0;
let lenArr = arr.length;
for (let i = 0; i <= lenArr - 1; i++) {
if (lenArr === 0) {
break;
}
if (arr[i] > 0) {
sum = sum + arr[i];
} else {
break;
}
}
return sum;
}
let input = [];
runningSum(input);
For an empty array the for loop would not be executed and it will return 0.
You can remove the if condition to check length of array inside for loop.

Find the number with the most digits in an array

Here we are. Stuck.
I've decided to create a function that finds the element with the most digits. If two of them have the same length, return the first one. Common sense tells us that it might be the highest number. Here is the code snippet:
function findLongest(array) {
var biggestNum = 0;
for(var i = 0; i < array.length; i++) {
if(array[i] > biggestNum) {
biggestNum = array[i];
}
}
return biggestNum;
}
findLongest([111,1111,5555,10000,1,90000]); //returns 90000 instead of 10000.
However, I can't meet the second condition (if length of two is the same, return the first one).
Any idea?
If you want digit-length comparing, cast the items into string and use length of them.
function findLongest(array) {
var biggestNum = 0;
for(var i = 0; i < array.length; i++) {
if(array[i].toString().length > biggestNum.toString().length) {
biggestNum = array[i];
}
}
return biggestNum;
}
console.log(findLongest([111, 1111, 5555, 10000, 1, 90000]));
You could take the integer value of the logarithm of 10 of the value for checking, because you get the count of digits (minus 1) for comapiring.
function findLongest(array) {
var biggestNum = array[0];
for (var i = 1; i < array.length; i++) {
if (Math.floor(Math.log10(array[i]) || 0) > Math.floor(Math.log10(biggestNum) || 0)) {
biggestNum = array[i];
}
}
return biggestNum;
}
console.log(findLongest([111, 1111, 5555, 10000, 1, 90000, 0]));
The second condition negates the first every time. The "highest number" right?
If you want the highest number why not sort and pop the last element as the returned value?
array[array.sort(function(a,b){return b - a}).length - 1]
Iteration of array is unnecessary

subtracting two integers which have different indexes but the same value

The given function should accept any array with any number of integers.
After it should subtract each two integers from each other beside integers which the same index.
var ArrayFirst = [4, 34, 6, 1,5];
var ArraySecond = [4,34,6,1,4];
function Find(Arg) {
var ResultArray;
var SecondArray = [];
for (var i = 0; i < Arg.length; i++) {
var FirsArray;
for (var j = 0; j < Arg.length; j++) {
if (Arg.indexOf(Arg[i]) != Arg.indexOf(Arg[j])) {
console.log(Arg.indexOf(Arg[i]) + 'AND' + Arg.indexOf(Arg[j]));
FirstArray = Arg[i] - Arg[j];
console.log(FirstArray);
if (FirstArray >= 0) {
SecondArray.push(FirstArray);
}
}
}
//console.log(SecondArray);
}
ResultArray = Math.min.apply(this, SecondArray);
console.log(ResultArray);
return ResultArray;
}
So After debuging I found that function Find works with ArrayFirst but not with ArraySecond
Question : Why function is not working when Array has two integers with the same value ?
UPDATED
Sorry guys that I haven't putted more details
Task: Create a function which as result will give the sum of subtracting two integers from an array, the sum cannot be subtraction of two integers which have the same index, the sum cannot be bellow 0, the sum closest to the 0 will be the proper result.
Example: [4,6,3,56,4]
4-6,4-3...4-4, then 6-4,6-3...6-4 then etc
So result will be 0 because 4-4 sum is 0
Some Hints
Firstly i thought maybe it is something to do with operation on array but then i used apply and call on arguments
if (Array.prototype.indexOf.apply(arguments[0],[arguments[0][i]]) !== Array.prototype.indexOf.apply(arguments[0],[arguments[0][j]])) {
FirstArray = arguments[0][i] - arguments[0][j];
if (FirstArray >= 0) {
SecondArray.push(FirstArray);
}
}
}
But is still not working, I tried the solution with to arguments, doesn't work either.
First and foremost avoid using Array as a variable name because for the most browser it will lead to unexpected behavior.
I think also you need to pass the two arrays in your function as parameters in order compare them.
And you don't need to find the index of element with index i, the i itself is an index.
Array.indexOf(Array[i]) === i
Here is an example of what you might need:
// it is important for the "array" value to start with lower case symbow, because JavaScript is case sensitive language and it already has object called "Array"
var array = [4, 6, 3, 56, 4];
function find(array)
{
// because we are surching for the minimum, the variable that will hold it needs to have the largest possible variable at the begining
var min = Number.MAX_VALUE;
for (var i = 0 ; i < array.length; i++)
{
for (var j=0 ; j < array.length; j++)
{
if (i != j)
{
var sum = array[i] - array[j];
// if it sum is greater than zero and it is the smallest sum so far we will save it in "min"
if (sum >= 0 && min > sum)
{
min = sum;
}
}
}
}
// retun the smallest sum we've encountered
return min;
}
console.log(find(array));

Why is my function not returning accurate count?

Expanding code I've been working on for a supplement tracker but my current function is not returning accurate count of numbers greater than the average 'mean' nor the count of integers below the mean average. I've also commented out two questions within the code because I don't quite understand why the array is set to index[0]. I've learned much from the comments and searching for answers here. So thankful this site exists! Looking to learn a bit more hopefully with this question.
function suppArray() {
var nums = new Array(); //create array
var sum = 0; //variable to hold sum of integers in array
var avg = 0; //variable to hold the average
var i;
var count = 0;
var count2 = 0;
var contents = ''; //variable to hold contents for output
var dataPrompt = prompt("How many numbers do you want to enter?", "");
dataPrompt = parseInt(dataPrompt);
for(i = 0; i <= dataPrompt - 1; i++) { //loop to fill the array with numbers
nums[i] = prompt("Enter a number","");
nums[i] = parseInt(nums[i]);
contents += nums[i] + " "; //variable that will be called to display contents
sum = sum + nums[i];
}
avg = sum / nums.length;
for(i = 0; i < nums.length; i++) { //loop to find the largest number
var biggest = nums[0]; //why does this have to be index 0 and not 'i' ?
if(nums[i] > biggest)
biggest = nums[i]; //largest integer in array
}
for(i = 0; i < nums.length; i++) { //loop to find smallest integer
var smallest = nums[0]; //why does this have to be the index 0 and not 'i' ??
if(nums[i] < smallest)
smallest = nums[i]; //smallest integer in array
}
for(count = 0; count < nums.length; count++) { //count of numbers higher than average
if(nums[i] > avg)
count = nums[i];
}
for(count2 = 0; count2 < nums.length; count2++) { //count of numbers lower than average
if(nums[i] < avg)
count2 = nums[i];
}
}
Your function isn't returning the right values because you are assigning count or count2 inccorectly. If you run through your code at the end count and count2 will be equal to nums.length. This is because you are using them in the for loop. As well in the loops you reference i which is (I believe) also equal to nums.length at this point.
I think you want something like this:
count = 0;
count2 = 0;
for(i = 0; i < nums.length; i++)
{
if(nums[i] > avg)
{
count++; //Increase the count of numbers above the average
}
else if(nums[i] < avg)
{
count2++; //Increase the count of numbers below the average
}
}
You may want to do some reading on scope and the for loop as you seem a little confused on them.
Edit
If you want the biggest and smallest values in the array you can do something like this:
//Assign the values to the first element by default
var biggest = nums[0];
var smallest = nums[0];
for(var i = 1; i < nums.length; i++)
{
//Set biggest to the larger number, either biggest or the current number
biggest = Math.max(biggest, nums[i]);
//Set smallest to the smaller number, either biggest or the current number
smallest = Math.min(smallest, nums[i]);
}
Note: This assumes you have at least 1 value in the array

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