Finding max value in array - javascript

I've searched on here and tried a few of the different methods but not getting the desired results. I have an array of 30 elements. I'm trying to loop through a javascript array and find the min and max values. Problem is that i'm only getting the last value of the array. I've tried using Math.max.apply and still get 90 the largest number in the array is 97 but 90 appears 4 times and the last time a the very end of the array also.
Here is the code
var max = 0;
var min = 0;
var len = weather.length;
var temps;
for(i = 0; i < len; i++)
{
temps = weather[i].MaxTemp;
max = Math.max(temps, len);
//max = Math.max(weather[i].MaxTemp, len);
}
console.log(max);

You mean
max = Math.max(temps, max);
You need to compare the current element to the previously found max. If your temps are all negative, you'll have a problem. So you want
var max = -99999;
as well.

Related

Is this the right way to iterate through an array?

Here is the code in question:
var L1 = [];
var Q1 = [];
function populateListOne() {
var limit = prompt("please enter a number you would like to fill L1 to.");
for (i = 2; i <= limit; i++) {
L1[i] = i;
}
for (n = 2; n <= L1.length; n++) {
var count = 2;
if (n == count) {
var index = L1.indexOf(n);
L1.splice(index, 1);
Q1[n] = n;
count = count + 1;
}
for (j = 0; j <= L1.length; j++) {
if (L1[j] % 2 == 0) {
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
}
document.getElementById("demo").innerHTML = "iteration " + "1" + ": " + L1 + " Q1 = " + Q1;
}
I’m currently working on a homework assignment where I have to setup a queue. All is explained in my JSFiddle.
Problem description
Essentially, the part I’m stuck on is iterating through each instance of the array and then taking the value out if the modulus is identical to 0. However, as you can see when I run the program, it doesn’t work out that way. I know the problem is in the second for loop I just don’t see what I’m doing wrong.
The way I read it is, if j is less than the length of the array, increment. Then, if the value of the index of L1[j] modulus 2 is identical to 0, set the value of secondIndex to whatever the index of j is. Then splice it out. So, theoretically, only numbers divisible by two should be removed.
Input
A single number limit, which will be used to fill array L1.
L1 will be initialized with values 2, 3, ... limit.
Process
Get the starting element of array L1 and place it in array Q1.
Using that element, remove all values in array L1 that are divisible by that number.
Repeat until array L1 is empty.
You're going to have issues with looping over an array if you're changing the array within the loop. To help with this, I tend to iterate from back to front (also note: iterate from array.length - 1 as the length element does not exist, arrays are key'd from 0):
for(j = L1.length - 1; j >=0 ; j--)
For your first loop, you miss the elements L1[0] and L1[1], so I would change the first loop to:
L1 = [];
for(i = 2; i <= limit; i++)
{
L1.push(i);
}
In this section:
for(j = 0; j <= L1.length; j++){
if(L1[j] % 2 == 0)
{
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
you should splice with j instead of secondIndex.
Change L1.splice(secondIndex, 1); to L1.splice(j, 1);
Array indices and putting entries
You initial code used an array that was initialized to start at index 2. To avoid confusion, of what index to start at, start with index 0 and iterate until array.length instead of a predefined value limit to ensure that you go through each element.
The following still works but will be more of a headache because you need remember where to start and when you will end.
for (i = 2; i <= limit; i++) {
L1[i] = i; // 'i' will begin at two!
}
Here's a better way:
for (i = 2; i <= limit; i++) {
// 'i' starts at 2 and since L1 is an empty array,
// pushing elements into it will start index at 0!
L1.push(i);
}
Use pop and slice when getting values
When you need to take a peek at what value is at the start of your array, you can do so by using L1[0] if you followed my advice above regarding array keys.
However, when you are sure about needing to remove the starting element of the array, use Array.slice(idx, amt). idx specifies which index to start at, and amt specifies how many elements to remove beginning at that index (inclusive).
// Go to 1st element in L1. Remove (1 element at index 0) from L1.
var current = L1.splice(0, 1);
Use the appropriate loops
To make your life easier, use the appropriate loops when necessary. For loops are used when you know exactly how many times you will iterate. Use while loops when you are expecting an event.
In your case, 'repeat until L1 is empty' directly translates to:
do {
// divisibility checking
} while (L1.length > 0);
JSFiddle
Here's a complete JS fiddle with in-line comments that does exactly what you said.

Javascript loop infinitely up till a certain condition

// Contains a list of items in each set.
var sets[0] = [1,2,3,4,5,6,7,8,9],
sets[1] = [10,11,12,13,14,15,16,17,18],
sets[2] = [19,20,21,22,23,25,26,27]
// Contains the mins associated to each set item.
var setTimes[0] = [15,15,15,15,15,15,15,15,15],
setTimes[1] = [16,12,11,15,13,15,15,15,14],
setTimes[2] = [16,12,11,15,13,12,11,15,13]
I've got a set of arrays as given above. The sets array has a data set of values. This array can have n number of items in it. Ex, sets[n].
Each sets array has an equivalent setTimes array that has minutes stored in it. setTimes[0][0] is 15min and is the number of minutes for sets[0][0].
Given a set item(ex 12), I'd like to:
Find out which set array does the given number belong to? In our case, since 12 was the item, it belongs to sets[1].
Once I have this, I'd like to get the sum of all mins from the setTimes array for the current sets index and also the next index. In our case, that would be the sum of setTimes[1] and setTimes[2].
In the event we reach the end of sets array, I'd like to get the sum of the first set array.
For ex,
- if I pass 12, I'll need to get the sum of setTimes[1] and setTimes[2]
- If I pass 23, I'll need to get the sum of setTimes[2] and setTimes[0]
Here is the loop I've been thinking, would like to know if there is a better way of doing this.
function computeTotalMin(givenItem)
{
// represents how many sets to loop thorough. I need 2.
for (x = 0; x <= 1; x++)
{
for(i = 0; i < sets.length; i++)
{
// checking to see if i value is on the last index of the sets array.
if(i === sets.length - 1)
{
i = 0;
var item = sets[i].indexOf(givenItem);
if(item !== -1)
{
// Loops through all mins from setTimes[i] array
for(j = 0; j < setTimes[i].length; j++)
{
var total = total + setTimes[j];
}
}
}
}
}
}
You don't need two nested loops for continuing at the end. You should have a single loop that iterates the number of sets you're interested in (2), and has an index (starting at the one set you've found). Inside that loop, you'd make a modulo operation on the index; to get back to the start when you've reached the end. By only looping over the count, not the (resettable) index, you won't get into an infinite loop.
You also should divide your program in just those tasks that you've textually described (find this, then do that), instead of munching everything in one huge nested control structure.
function computeTotalMin(givenItem) {
var setIndex = -1;
for (; setIndex < sets.length; setIndex++)
if (sets[setIndex].indexOf(givenItem) > -1)
break;
if (setIndex == sets.length)
return null; // givenItem found in none of the sets
var sum = 0;
for (var count = 0; count < 2; count++) {
for (var i=0; i<setTimes[setIndex].length; i++)
sum += setTimes[setIndex][i];
setIndex++; // go to next set
setIndex %= sets.length; // which might be 0
// alternatively: if (setIndex == sets.length) setIndex = 0;
}
return sum;
}

How do I count the number of items in an array that start with the highest number?

I've got an array that is filled with dates. They each start with the number of the year.
How do I cound the number of items present in the array that start with the highest number?
My array in question:
["12-A*januari", "12-B*februari", "12-C*maart", "12-D*april", "12-E*mei", "12-F*juni", "12-G*juli", "12-H*augustus", "12-I*september", "12-J*oktober", "12-K*november", "12-L*december", "13-A*januari", "13-B*februari", "13-C*maart", "13-D*april", "13-E*mei", "13-F*juni", "13-G*juli", "13-H*augustus", "13-I*september", "13-J*oktober", "13-K*november", "13-L*december", "14-A*januari", "14-B*februari", "14-C*maart", "14-D*april", "14-E*mei", "14-F*juni", "14-G*juli"]
So in this example I want to count the number of items in the array that start with 14, which in this example case would be 7. The numbers are dynamic so in the future the highest number will be different.
How do i return the count for the items that start with the highest number?
If your data is stored in arr:
var numbers = arr.map(function(x){ return parseInt(x); })
var max = Math.max.apply(Math,numbers)
var n = numbers.filter(function(x){ return x==max; }).length
Then your count will be in n.
P.S. in your example array there are 7 elements starting with 14.
you can sort the array, reverse it, then just filter to get the count
var count = ar.sort().reverse().filter(function(v){
return v.split('-')[0] == ar[0].split('-')[0];
}).length;
FIDDLE
First loop through your array, splitting your string and finding the largest element, by looking at the first element of the new array, like this:
var splitString = iteratingString.split("-");
if(Number(splitString[0]) > max){
max = Number(splitString[0]);
}
Then you iterate again, split each string again into a temporary array and increase the counter if the first element of the temp array is equal to max.
Combinations of map/max/filter is elegant, but unless these functions were lazy, it's quite inefficient in theory since you have to loop multiple times over the input for each functionnal operation.
It really doesn't matter in practice, unless your input is very large, but why not something standard like the following?
highestNumberOccurenceFrom(['13a', '12b', '13c']); //2
function highestNumberOccurenceFrom(arr) {
var count = 0, max = 0, i = arr.length, num;
while (i) {
num = parseInt(arr[--i]);
if (num > max) max = num, count = 1;
else if (num === max) ++count;
}
return count;
}
You could try something like this:
var maxCount = 0;
var maxVal = null;
var curVal = null;
for (var ctr=0; ctr< array.length; ctr++){
//TODO: parse the number from the beginning of the string
// You will need to write the function 'parseValFromString'
curVal = parseValFromString(array[ctr]);
if (curVal > maxVal || maxVal === null){
maxVal = curVal;
maxCount = 1;
}
else if (curVal === maxVal){
maxCount++;
}
}
console.log("count=" + maxCount;
Sort the Array first. Let the name of array be list
list.sort();
If you are sure that the array is already sorted, you can omit this step.
Get the max number
var max = list[list.length-1].substr(0,2);
Now filter the Array like this.
var list2 = list.filter(function(a){
return max == a.substr(0,2);
})
Now get number of elements in list2.
var answer = list2.length;

Finding Products within large Digits

I have been working on a way to find products of 5 digits within a large number. For example, I have the number 158293846502992387489496092739449602783 And I want to take the first 5 digits (1,5,8,2,9) and multiply them, then the second, (5,8,2,9,3), multiply then, then the third... And so on. Then I want to find the largest of all of them I find, now I came up with the following code to solve this problem:
// I put the digit into a string so I can modify certain parts.
var digit = "158293846502992387489496092739449602783";
var digitLength = digit.length;
var max = 0;
var tempHolder;
var tempDigit = 0;
var tempArray = [];
for(var i = 0; i<=digitLength; i++){
tempHolder = digit.substring(i, i+5);
tempArray = tempHolder.split("");
for(var j = 0; j < 5; j++){
tempDigit += tempArray[j];
}
if(tempDigit > max){
max = tempDigit;
}
}
console.log(max);
It logs to the console A longer number than what I put into it, along with 10 undefined, no spaces. Can anyone figure out the problem here?

How do I find the min value from randomised set of numbers?

see http://jsfiddle.net/JPxXp/
I understand as to why I keep getting 1 as the minimum ball number; do I create another variable / array that holds the 6 randomised numbers (if so, how - I don't fully understand how to do this).
First, define an array that holds the randomised numbers:
var random_balls = [];
Each time you generate a random number, add it to that array:
// generate, the + is to convert a string like '12' to the number 12, otherwise
// comparing them gives wrong results: '12' < '9' but 12 > 9
var random_ball = +balls[Math.floor(Math.random()*balls.length)];
// if indexOf returns -1, the ball is not present in the array
// (otherwise it returns the index at which the ball is)
while(random_balls.indexOf(random_ball) !== -1) {
// generate again if you already took this ball
random_ball = +balls[Math.floor(Math.random()*balls.length)];
}
// add to array
random_balls.push(random_ball);
// display
document.write(random_ball);
The min checker would iterate the new array with random numbers like this:
for (i=0; i<random_balls.length; i++)
{ if (random_balls[i] < min)
min = random_balls[i];
}
In case you didn't know, you can also use:
var min = Math.min.apply(null, random_balls); // use built in min function, passing array as arguments
http://jsfiddle.net/pimvdb/JPxXp/7/
Define global min variable and change it after selecting random ball:
var min = Number.POSITIVE_INFINITY;
...
for(i=0; i<NUMBER_OF_BALLS; i++) {
var ball = balls[Math.floor(Math.random()*balls.length)];
min = Math.min(ball, min);
document.write(ball);
document.write(" ");
}
fiddle: http://jsfiddle.net/Daess/JPxXp/4/
After the loop min variable will hold min number.
Indeed you need to push the values that you randomly choose into an array, and find the min WRT to that array.
document.write("your balls are ");
NUMBER_OF_BALLS = 6
var i = 0;
var balls = ['1','2','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','31','32','33','34','35','36','37','39','40'];
var chosen = [];
for(i=0; i<NUMBER_OF_BALLS; i++) {
chosen.push(balls[Math.floor(Math.random()*balls.length)]);
document.write(chosen[chosen.length-1]);
document.write(" ");
}
document.write("<br>");
document.write("<br>");
min = Number.POSITIVE_INFINITY;
for (i=0; i<chosen.length; i++) {
if (chosen[i] < min)
min = chosen[i];
}
document.write("The lowest ball was: " + min);
document.write("<br>");
You're taking the minimum from the balls array. All you're doing is printing out six random elements from the array. You'll need to create a new array with 6 elements, copy 6 random ones from the original array into that, then get the minimum. Also mind that you could get the same element twice.
I'm going to go for a different way here:
var arr = [], // acceptable values
randomArray = []; // random array
// Create an array of numbers 0 to 45;
for(var i=1; i <=45 ; i++){
arr.push(i);
}
// From http://stackoverflow.com/q/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
// Randomly sort the array and take 6
randomArray = shuffle(arr).slice(0,6);
document.write("Random array: " + randomArray + "<br>");
document.write("Minimum value: " + Math.min.apply(Math, randomArray));
Example: http://jsfiddle.net/jonathon/85vEA/
At the start, I'm generating my set of numbers from 1-45 (instead of the string array you have). I'm then sorting it randomly using the Fisher-Yates shuffle (see the link to the other question) and, to get my subset of 6 random numbers, I do a slice on the array.
The minimum value can then be found by doing Math.min.apply(Math, randomArray)

Categories

Resources