Finding max value in an array of sub arrays - javascript

function largestOfFour(arr) {
let newArr = [];
let max = 0;
for(let i = 0; i<arr.length;i++){
for(let j = 0; j<arr[i].length; j++){
if(arr[i][j]>max){
max = arr[i][j];
console.log(max);
newArr.push(max);
}
}
}
return newArr;
}
Hello I am writing a code to find the max value in an array of sub arrays and am required to add that max value to a new array. My code is above. The problem is my code is pushing every value greater than the max to the new array. When I just want the true max without using the Math.max function. I believe this is happening because I do not have a way of updating the max when a new max is found. Some guidance would be very helpful

Initialize max in the outer loop (i) with -Infinity (the smallest "number" available"), then compare and update it in the inner loop, but only push it after the inner loop is done:
function largestOfFour(arr) {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
let max = -Infinity;
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
newArr.push(max);
}
return newArr;
}
const result = largestOfFour([[4, 3, 2, 1], [1, 2, 3, 4], [500, 600, 400], [300, 1000, 700]]);
console.log(result);

You could save the first value as start value for max and iterate from the second index.
Later push the max value of the nested array to the result array.
function largestOfFour(arrays) {
const maxValues = [];
for (let [max, ...array] of arrays) {
for (const value of array) if (max < value) max = value;
maxValues.push(max);
}
return maxValues;
}
console.log(largestOfFour([[3, 2, 1, 7], [2, 6, 4, 9], [2, 2, 1, 1], [4, 3, 6, 7]]));

From your description of the problem i can understand that you want the maximum value from the subarrays of the array.
In this situation you do not need to use
newArr.push(max) Inside the IF block. You can use this line after the two nested loop are finished. Then you use newArr.push(max);
And then return newarr.

Related

My nested for loop times out when searching for 2 numbers in an array that add up to a sum value

I'm trying to find a better/faster algorithm that doesn't timeout when I try to find any 2 numbers in an array of numbers that add up to a sum(ex. s). I need to return the pair of numbers that adds up to sum(s) which also have the indices that appear the earliest(there maybe many other pairs). Here is my nested for loop approach.
function sum(ints, s){
let pusher = [];
let count = 1000;
for(let i = 0; i < ints.length; i++){
for(let j = i+1; j < ints.length; j++){
if(ints[i] + ints[j] === s){
if(j < count){
pusher = [ints[i],ints[j]];
count = j;
}
}
}
}
return pusher.length > 0 ? pusher : undefined ;
}
To reduce the computational complexity from O(n ^ 2) to O(n), create a Setinstead. When iterating over a number, check if the set has the value sum - num - if it does, return that pair as the result. Otherwise, put the number into the Set:
Or you could use a Set
function sum(ints, sum) {
const set = new Set();
for (const num of ints) {
const otherNum = sum - num;
if (set.has(otherNum)) {
return [num, otherNum];
} else {
set.add(num);
}
}
}
console.log(sum([3, 4, 99, -2, 55, 66, -3], 1));
console.log(sum([1, 9, 15, 2, 4, 7, 5], 6));

Javascript: How to check if an array item is greater than twice an item in another array

I have two arrays
let arr1 = [1,2,3,4,5]
let arr2 = [6,7,8,9,10]
What I want to do is check if any item in arr2 is greater than or equal to twice any item in arr1. For example, 6 in arr2 is greater than 2*2 in arr1.
My first solution is
for(let i = 0; i < arr2.length; i++) {
for(let j = 0; j < arr1.length; j++) {
if (i >= j * 2) {
return true
}
}
}
Expected result: return true if any item in arr2 is greater than or equal to twice any item in arr1.
But I am in search of a linear solution to this problem.
You could take a miminum value of array1, get the double and check against the minimum of array2.
let array1 = [1, 2, 3, 4, 5],
array2 = [6, 7, 8, 9, 10],
result = Math.min(...array2) > 2 * Math.min(...array1);
console.log(result);
You can first find the absolute minimum at first array and then compare it to the second array.
Reducing it to O(arr1.length + arr2.length)
If twice the minimum is greater than any element in arr2 then none is lower.
This code seems wrong:
if (i >= j * 2)
{
return true
}
should be
if (arr2[i] >= arr1[j] * 2)
{
return true
}
Since you want boolean value result, you can use some with combination of find.
let arr1 = [1,2,3,4,5]
let arr2 = [6,7,8,9,10]
const num = arr2.some(num => arr1.find(x => num >= (x * 2)))
console.log(num);

Find the biggest number in an array by using JavaScript loops

Create a function called biggestNumberInArray().
That takes an array as a parameter and returns the biggest number.
Here is an array
const array = [-1, 0, 3, 100, 99, 2, 99]
What I try in my JavaScript code:
function biggestNumberInArray(arr) {
for (let i = 0; i < array.length; i++) {
for(let j=1;j<array.length;j++){
for(let k =2;k<array.length;k++){
if(array[i]>array[j] && array[i]>array[k]){
console.log(array[i]);
}
}
}
}
}
It returns 3 100 99.
I want to return just 100 because it is the biggest number.
Is there a better way to use loops to get the biggest value?
Using three different JavaScript loops to achieve this (for, forEach, for of, for in).
You can use three of them to accomplish it.
Some ES6 magic for you, using the spread syntax:
function biggestNumberInArray(arr) {
const max = Math.max(...arr);
return max;
}
Actually, a few people have answered this question in a more detailed fashion than I do, but I would like you to read this if you are curious about the performance between the various ways of getting the largest number in an array.
zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:
function biggestNumberInArray (arr) {
// The largest number at first should be the first element or null for empty array
var largest = arr[0] || null;
// Current number, handled by the loop
var number = null;
for (var i = 0; i < arr.length; i++) {
// Update current number
number = arr[i];
// Compares stored largest number with current number, stores the largest one
largest = Math.max(largest, number);
}
return largest;
}
There are multiple ways.
Using Math max function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
Using reduce
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Implement our own function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
function getMaxOutOfAnArray(array) {
let maxNumber = -Infinity;
array.forEach(number => { maxNumber = number > maxNumber ? number : maxNumber; })
console.log(maxNumber);
}
getMaxOutOfAnArray(array);
The simplest way is using Math.max.apply:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
return Math.max.apply(Math, arr);
}
console.log(biggestNumberInArray(array));
If you really want to use a for loop, you can do it using the technique from this answer:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
var m = -Infinity,
i = 0,
n = arr.length;
for (; i != n; ++i) {
if (arr[i] > m) {
m = arr[i];
}
}
return m;
}
console.log(biggestNumberInArray(array));
And you could also use reduce:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(array) {
return array.reduce((m, c) => c > m ? c : m);
}
console.log(biggestNumberInArray(array));
I think you misunderstand how loops are used - there is no need to have three nested loops. You can iterate through the array with a single loop, keeping track of the largest number in a variable, then returning the variable at the end of the loop.
function largest(arr) {
var largest = arr[0]
arr.forEach(function(i) {
if (i > largest){
largest = i
}
}
return largest;
}
Of course you can do this much more simply:
Math.max(...arr)
but the question does ask for a for loop implementation.
This is best suited to some functional programming and using a reduce, for loops are out of favour these days.
const max = array => array && array.length ? array.reduce((max, current) => current > max ? current : max) : undefined;
console.log(max([-1, 0, 3, 100, 99, 2, 99]));
This is 70% more performant than Math.max https://jsperf.com/max-vs-reduce/1
Another visual way is to create a variable called something like maxNumber, then check every value in the array, and if it is greater than the maxNumber, then the maxNumber now = that value.
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
let maxNumber;
for(let i = 0; i < arr.length; i++){
if(!maxNumber){ // protect against an array of values less than 0
maxNumber = arr[i]
}
if(arr[i] > maxNumber){
maxNumber = arr[i];
}
}
return maxNumber
}
console.log(biggestNumberInArray(array));
I hope this helps :)
var list = [12,34,11,10,34,68,5,6,2,2,90];
var length = list.length-1;
for(var i=0; i<length; i++){
for(j=0; j<length; j++){
if(list[j]>list[j+1]){
[ list[j] , list[j+1] ] = [ list[j+1] , list[j] ];
}
}
}
console.log(list[list.length-1]);
You Can try My codes to find the highest number form array using for loop.
function largestNumber(number){
let max = number[0];
for(let i = 0; i < number.length; i++){
let element = number[i];
if(element > max){
max = element;
}
}
return max;
}
let arrayNum= [22,25,40,60,80,100];
let result = largestNumber(arrayNum);
console.log('The Highest Number is: ',result);
let arr = [1,213,31,42,21];
let max = 0;
for(let i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i]
}
}
console.log(max)
There are multiple ways.
way - 1 | without for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 1 | without for loop
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
console.log({ maxValue, maxIndex }); // { maxValue: 100, maxIndex: 3 }
way - 2 | with for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 2 | with for loop
let max = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
console.log(max); // 100
THis is the simple function to find the biggest number in array with for loop.
// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMax(arr));
// Function to find the biggest integer in array
function findMax(arr) {
// size of array
let arraySize = arr.length;
if (arraySize > 0) {
// Initialize variable with first index of array
var MaxNumber = arr[0];
for (var i = 0; i <= arraySize; i++) {
// if new number is greater than previous number
if (arr[i] > MaxNumber) {
// then assign greater number to variable
MaxNumber = arr[i];
}
}
// return biggest number
return MaxNumber;
} else {
return 0;
}
}
You can try this if you want to practice functions
const numbs = [1, 2, 4, 5, 6, 7, 8, 34];
let max = (arr) => {
let max = arr[0];
for (let i of arr) {
if (i > max) {
max = i;
}
}
return max;
};
let highestNumb = max(numbs);
console.log(highestNumb);
const array = [-1, 0, 3, 100, 99, 2, 99]
let longest = Math.max(...array);
what about this
const array = [1, 32, 3, 44, 5, 6]
console.time("method-test")
var largestNum = array[0]
for(var i = 1; i < array.length; i++) {
largestNum = largestNum > array[i] ? largestNum : array[i]
}
console.log(largestNum)
console.timeEnd("method-test")

Javascript function. What is missing?

Write a program to find count of the most frequent item of an array. Assume that input is array of integers.
Example:
Input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
Ouptut: 5
Most frequent number in example array is -1. It occurs 5 times in input array.
Here is my code:
function mostFrequentItemCount(collection) {
var copy = collection.slice(0);
for (var i = 0; i < collection.length; i++) {
var output = 0;
for (var x = 0; x < copy.length; x++) {
if (collection[i] == copy[x]) {
output++;
}
}
}
return output;
}
It seems to be just counting the reoccurrence of the first number in the array not the one that occurs the most. I can't figure out how to make it count the most occurring one.
If i didn't miss anything, and if you really want to find the count of the most frequent item of an array, i guess one approach would be this one:
function existsInCollection(item, collection) {
for(var i = 0; i < collection.length; i++) {
if(collection[i] === item) {
return true;
}
}
return false;
}
function mostFrequentItemCount(collection) {
var most_frequent_count = 0;
var item_count = 0;
var already_checked = [];
for(var i = 0; i < collection.length; i++) {
// if the item was already checked, passes to the next
if(existsInCollection(collection[i], already_checked)) {
continue;
} else {
// if it doesn't, adds to the already_checked list
already_checked.push(collection[i]);
}
for(var j = 0; j < collection.length; j++)
if(collection[j] === collection[i])
item_count++;
if(item_count > most_frequent_count)
most_frequent_count = item_count;
item_count = 0;
}
return most_frequent_count;
}
var items = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
alert(mostFrequentItemCount(items));
What happens here is:
On each item ('i' loop), it will run another loop ('j') through all items, and count how many are equal to the [i] item. After this second loop, it will be verified if that item count is greater than the most_frequent_count that we already have, and if it is, updates it.
Since we always use the same variable 'item_count' to check each number count, after the verification of each number we reset it to 0.
This may not be the best answer, but it was what occurred me at the moment.
EDIT:
I added a function to check if an item already exists in a list, to avoid the loop from check the same item again.
The problem is that you override the output variable each loop iteration, so after the for loop ends your output variable holds occurrences of the last element of input array.
You should use variables like var best_element = collection[0] and var best_element_count = -1 (initialized like this). After each inner loop you check if algo found any better solution (best_element_count < output) and update best_element.
Edit: following #Alnitak comment you should also reset the output variable after each inner loop iteration.
First you will need to construct a collection (or object) that contains the element and the count of occurances. Second you will need to iterate the result to find the key that has the highest value.
JSFiddle
function mostFrequentItemCount(collection) {
var output = {};
for (var i = 0; i < collection.length; i++) {
var item = collection[i];
if (!(item in output))
output[item] = 0;
output[item]++;
}
var result = [0, 5e-324];
for (var item in output) {
if (output[item] > result[1]) {
result[0] = parseFloat(item);
result[1] = output[item];
}
}
return result;
}
var input = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var result = mostFrequentItemCount(input);
console.log(result);
The snippet above simply creates a new object (output) which contains a property for each of the unique elements in the array. The result is something like.
2:2
3:4
4:1
9:1
-1:5
So now we have an object with the property for the number and the value for the occurances. Next we then interate through each of the properties in the output for(var item in output) and determine which value is the greatest.
Now this returns an array with the value at index 0 being the number and the value at index 1 being the count of the element.
Check this solution.
var store = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}
alert(max);
So this update to your method will return an object with each key and the count for that key in the array. How you format an output to say what key has what count is up to you.
Edit: Updated to include the complete solution to the problem.
function mostFrequentItemCount(collection) {
var copy = collection.slice(0);
var results = {};
for (var i = 0; i < collection.length; i++) {
var count = 0;
for (var x = 0; x < copy.length; x++) {
if (collection[i] == copy[x]) {
count++;
}
}
results[collection[i]] = count;
}
return results;
}
var inputArray = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var occurances = mostFrequentItemCount(inputArray);
var keyWithHighestOccurance = Object.keys(occurances).reduce(function(a, b){ return occurances[a] > occurances[b] ? a : b });
var highestOccurance = occurances[keyWithHighestOccurance];
console.log("Most frequent number in example array is " + keyWithHighestOccurance + ". It occurs " + highestOccurance + " times in the input array.");

Sum specific array values depends on list of index value on other array

I have two arrays:
a = [12, 50, 2, 5, 6];
and
b = [0, 1, 3];
I want to sum those arrays value in array A with exact index value as array B so that would be 12+50+5 = 67. Kindly help me to do this in native javascript. I already tried searching but I can't find any luck. I found related article below, but I can't get the logic
indexOf method in an object array?
You can simply do as follows;
var arr = [12, 50, 2, 5, 6],
idx = [0, 1, 3],
sum = idx.map(i => arr[i])
.reduce((p,c) => p + c);
console.log(sum);
sumAIndiciesOfB = function (a, b) {
var runningSum = 0;
for(var i = 0; b.length; i++) {
runningSum += a[b[i]];
}
return runningSum;
};
logic explained:
loop through array b. For each value in b, look it up in array a (a[b[i]]) and then add it to runningSum. After looping through b you will have summed each index of a and the total will be in runningSum.
b contains the indices of a to sum, so loop over b, referencing a:
var sum=0, i;
for (i=0;i<b.length;i++)
{
sum = sum + a[b[i]];
}
// sum now equals your result
You could simply reduce array a and only add values if their index exists in array b.
a.reduce((prev, curr, index) => b.indexOf(index) >= 0 ? prev+curr : prev, 0)
The result is 12+50+5=67.
Like this:
function addByIndexes(numberArray, indexArray){
var n = 0;
for(var i=0,l=indexArray.length; i<l; i++){
n += numberArray[indexArray[i]];
}
return n;
}
console.log(addByIndexes([12, 50, 2, 5, 6], [0, 1, 3]));

Categories

Resources