I'm trying to get the minimum value from an array in Vue3 but I keep getting an infinity value. Can I please get help?
Below is adding value to the 'ranks' array.
const ranks = ref([])
for (let i = 0; i < uni.value.length; i++) {
ranks.value.push(uni.value[i].rank)
}
And here is the finding min code:
const min = Math.min(...ranks.value)
console.log(min) // it returns Infinity
this is how my ranks array looks in the console:
const minValue = (nums) => {
let min = Infinity;
for(let i=0; i< nums.length;i++){
if(min > nums[i]){
min = nums[i];
}
}
return min;
};
Use the below code to find the minimum value.
a = [5,4,1,2,3]
let minVal = Infinity
a.forEach(val => minVal = minVal > val ? val : minVal)
console.log('Minimum value is ' + minVal)
Related
I want to get an output array beginning with min value and ending with max value => [5,6,7,8,9,10].
But I get only min value in new array => [5]. Why does this happen?
function arrayFromRange(min , max){
const newArray = [];
for( let x = min ; x <= max; x++ ){
newArray.push(x);
return newArray;
}
}
const newarray1 = arrayFromRange(5,10);
console.log(newarray1);
You return your newArray inside the for loop, having only added the first item, in this case 5.
Solution is to move the return out of the foor loop, i.e.
function arrayFromRange(min , max){
const newArray = [];
for( let x = min ; x <= max; x++ ){
newArray.push(x);
} // <--swap these
return newArray; // <-- two lines
}
You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.
Example
Candles = [4,4,1,3]
The maximum height of candles is 4 units high. There are 2 of them, so return 2.
So basically the way I'm doing so is by moving from each place of the array comparing each other with two for cycles, the second cycle will count the repeated numbers, some people use Math.max imported function but I didn't know it before started looking for the answer, and I think this way should work, but can't get to the answer, any ideas?
function birthdayCakeCandles(candles) {
let height=1;
let b=0;
for (let i=0; i<candles.length; i++)
{
for (b=0; b<candles.length; b++)
{
if(b!=i && candles[b]===candles[i])
{height++;}
b++;
}
}
return height;
This should be straightforward, iterate through the array find max if max exists again increase count, if some other element greater than max set it to max and reset count to 1
function findTallestCandleCount(candles){
let max = 0, count = 0
for (let candle of candles) {
if (candle > max) {
max = candle
count = 1
} else if (candle === max){
count++
}
}
return count;
}
I solved it this way
function birthdayCakeCandles(candles) {
let height=0;
let max=Math.max(...candles);
for (let i=0; i<candles.length; i++)
{
if (candles[i]==max)
{height++;}
}
return height;
}
well I solved that challenge with this
function birthdayCakeCandles(candles) {
const maxVal = Math.max(...candles)
//use an array to save all the biggest/max number
const newArr = []
for(let val of candles){
if(val === maxVal) {
newArr.push(val)
}
}
return newArr.length
}
But If you don't want to use Math.max() we have to find biggest value first. we can use for of loop to find max/biggest value like this:
function birthdayCakeCandles(candles) {
let maxVal = 0
//use loop to find the biggest number
for(let val of candles) {
if(val > maxVal) {
maxVal = val
}
if(val < maxVal) {
maxVal = maxVal
}
if(val === maxVal) {
maxVal = maxVal
}
}
//use an array to save all the biggest/max number
const newArr = []
for(let val of candles){
if(val === maxVal) {
newArr.push(val)
}
}
return newArr.length
}
You can try this below.
The logic that i used is that first store the values in newArr[] with candles[0] and Highest numbers from candles[] array. It is because the logic used in first for loop that compares max_val = candles[0] with candles[i]. And so when storing max_val to newArr[], it taking candles[0] and its comparing values (equal to or greatern than candles[0]) along with largest numbers in candles[] array.
Now the second for() loop filtering values based on max_val == newArr[j]. The max_val in first for() loop already loaded with largest value, so that after comparison only largest numbers are filtered and stored into resultArr[]. Then return the function with length property.
var max_val = candles[0];
var newArr = [];
var resultArr = [];
var resultMax;
for(var i = 0; i < candles.length; i++)
{
if(max_val <= candles[i])
{
max_val = candles[i];
newArr.push(candles[i]);
}
}
for(var j = 0; j < newArr.length; j++)
{
if(max_val == newArr[j])
{
resultArr.push(newArr[j]);
}
}
var num = resultArr.length;
return num;
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example var arr = [1,3,5,7,9] the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
You could take the first value as start value for sum, min and max value and iterate from the second item. Then add the actual value and check min and max values and take adjustments.
At the end return the delta of sum and max and sum and min.
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
Using ES6:
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
OR
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
The solution is simple, just get the min and max value, sum the array and extract min or max in order to get the max sum or min sum.
As pseudocede:
min_value = find_min_value(arr)
max_value = find_max_value(arr)
max_sum = sum_array(arr) - min_value
min_sum = sum_array(arr) - max_value
:)
Here a function which solves your problem.
const minMaxSum = (arr) => {
const orderedAr = arr.sort((a, b) => a - b);
const min = orderedAr
.slice(0, 4)
.reduce((val, acc) => acc + val, 0);
const max = orderedAr
.slice(-4)
.reduce((val, acc) => acc + val, 0);
return `${min} ${max}`;
};
Here's the full code with more optimized and cleaned with all test cases working-
Using Arrays.sort()
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr)
{
int min=0;
int max=0;
Arrays.sort(arr);
for(int i=0; i<arr.length;i++)
{
if(i>0)
{
max+=arr[i];
}
if(i<4)
{
min+=arr[i];
}
}
System.out.println(min + " " + max);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] arr = new int[5];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < 5; i++)
{
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
miniMaxSum(arr);
scanner.close();
}
}
Have a look at this code.
function miniMaxSum(arr) {
// Write your code here
const MaxValue = Math.max(...arr)
const MinValue = Math.min(...arr)
const MaxSum = arr.reduce((a,b) => a+b) - MinValue
const MinSum = arr.reduce((a,b) => a+b) - MaxValue
return `${MinSum} ${MaxSum}`
}
My approach considering Optimal time/space complexity:
find min/max values from input array with Infinity/-Infinity
calculate totalSum of input array
print out (totalSum - max, totalSum - min)
Time: O(n) where n is # elements in input array
Space: O(1) no extra memory needed
function miniMaxSum(array) {
let min = Infinity; // any number lesser than Infinity becomes min
let max = -Infinity; // any number greater than -Infinity becomes max
let totalSum = 0;
for(let i = 0; i < array.length; i++) {
if(array[i] < min) min = array[i];
if(array[i] > max) max = array[i];
totalSum += array[i];
};
// sum - max gets us MINSUM
// sum - min gets us MAXSUM
console.log(totalSum - max, totalSum - min);
};
New Answer
const arr = [5,5,5,5,7]
const min = (arr) => {
const max = Math.max(...arr)
const min = Math.min(...arr)
let maxIndexValue
let minIndexValue
let maxResult = 0
let minResult = 0
if(arr.reduce((val, c) => val + c) / arr.length === arr[0]){
const arrayFilter = arr.slice(1);
let maxResult = arrayFilter.reduce((val, c) => val + c)
let minResult = arrayFilter.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}else{
for(let i = 0; i < arr.length; i++){
if(arr[i] === max){
maxIndexValue = i
}
if(arr[i] === min){
minIndexValue = i
}
}
const maxArray = arr.filter((element, index, num)=> num[index] !== num[maxIndexValue])
const minArray = arr.filter((element, index, num)=> num[index] !== num[minIndexValue])
const maxResult = maxArray.reduce((val, c) => val + c)
const minResult = minArray.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}
}
min(arr)
I am writing this code to find missing numbers from a given array. This code works fine when i pass 1,4 as arguments but 5,10 it fails to push new items to the array. What am I doing wrong?
function sumAll(arr) {
max = Math.max(...arr);
min = Math.min(...arr);
toFill = max - min;
for (i = min + 1; i <= toFill; i++) {
arr.push(i);
}
return arr.sort().reduce((prev, curr) => prev + curr);
}
sumAll([5, 10]);
You need to say i <= min+toFill
function sumAll(arr) {
max = Math.max(...arr);
min = Math.min(...arr);
toFill = max - min;
for (i = min + 1; i <= min+toFill; i++) { console.log(i);
arr.push(i);
}
return arr.sort().reduce((prev, curr) => prev + curr);
}
What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.
Just loop through the array and look for the lowest number:
var index = 0;
var value = temp[0];
for (var i = 1; i < temp.length; i++) {
if (temp[i] < value) {
value = temp[i];
index = i;
}
}
Now value contains the lowest value, and index contains the lowest index where there is such a value in the array.
One-liner:
alist=[5,6,3,8,2]
idx=alist.indexOf(Math.min.apply(null,alist))
You want to use indexOf
http://www.w3schools.com/jsref/jsref_indexof_array.asp
Using the code that you had before, from the other question:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
Array.min = function( array ){
return Math.min.apply( Math, array );
};
var value = temp.min;
var key = temp.indexOf(value);
Find the smallest value using Math.min and the spread operator:
var minimumValue = Math.min(...temp);
Then find the index using indexOf:
var minimumValueIndex = temp.indexOf(minimumValue);
I personally prefer the spread operator over apply.
See this answer of "find max" version of this question. It is simple and good. You can use the index to get the element afterward.
You could use reduce, and compare against Infinity.
let minIndex = -1;
arr.reduce((acc, curr, index) => {
if (curr < acc) {
minIndex = index;
return curr;
} else {
return acc;
}
}, Infinity);
Here is a solution using simple recursion. The output is an object containing the index position of the min number and the min number itself
const findMinIndex = (arr, min, minIndex, i) => {
if (arr.length === i) return {minIndex, min};
if (arr[i] < min) {
min = arr[i]
minIndex = i;
}
return findMinIndex(arr, min, minIndex, ++i)
}
const arr = [5, 5, 22, 11, 6, 7, 9, 22];
const minIndex = findMinIndex(arr, arr[0], 0, 0)
console.log(minIndex);