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);
}
Related
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)
This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 11 months ago.
I am solving the mini-max task on hackerrank.
https://www.hackerrank.com/challenges/mini-max-sum/problem?isFullScreen=true
For that i have the following code where i use recursion until i hit the array length
let arr = [1,2,3,4,5];
let sumsArr = [];
function sumMiniMax(arr, length) {
let sum = 0;
for(let i = 0;i < arr.length;i++) {
if(i != length) {
sum += arr[i];
}
}
sumsArr.push(sum);
length = length + 1;
if(length == arr.length) {
let result = findMinAndMax(sumsArr);
console.log('result local', result);
return result
} else {
sumMiniMax(arr, length)
}
}
function findMinAndMax(sumsArr) {
return Math.min(...sumsArr) + '\n' + Math.max(...sumsArr)
}
let res = sumMiniMax(arr, 0);
console.log('res', res);
in the result local i am getting the expected output 10 and 14 but after the recursion is done i want to return the result from findMinAndMax to the original caller which is sumMiniMax
In that case i am getting only undefined but before i return the value we can see that the correct output in the local scope in found 10 and 14. Why is that ?
Not all of your code paths return a value. You need to propagate your result up the call stack. In your case the
return sumMiniMax(arr, length);
is missing in the else branch of your function sumMiniMax().
You could take a single loop approach by having a sum of the three non min and non max values and keep min and max value for adding later.
function getMinMax(array) {
let min = array[0] < array[1] ? array[0] : array[1],
max = array[0] > array[1] ? array[0] : array[1],
sum = 0;
for (let i = 2; i < array.length; i++) {
const value = array[i];
if (min > value) {
sum += min;
min = value;
continue;
}
if (max < value) {
sum += max;
max = value;
continue;
}
sum += value;
}
return [min + sum, max + sum].join(' ');
}
console.log(getMinMax([1, 2, 3, 4, 5]));
I think recursion in this case is kind of over-engineering. The task has a straightforward approach:
function miniMaxSum(arr) {
const sumWithout = (el) => {
const elIndex = arr.indexOf(el);
const arrWithout = arr.filter((_, i) => i !== elIndex);
return arrWithout.reduce((sum, num) => sum + num);
};
const maxEl = Math.max(...arr);
const minEl = Math.min(...arr);
console.log(sumWithout(maxEl), sumWithout(minEl));
};
miniMaxSum([1,2,3,4,5]);
.as-console-wrapper{min-height: 100%!important; top: 0}
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'm looking for the Max, Min, Avg to this code with an expected output of [10,-2,3.5]
function MaxMinAvg (arr){
var max = arr[0]
var min = arr[0]
var sum = arr[0]
for (var i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i]
}
if (arr[i] < min){
min = arr[i];
}
sum = sum + arr[i];
var avg = arr[i] / arr.length;
var arr2 = [max, min, avg];
}
return arr2;
}
[10,-2,3.5]
Your code is almost correct, but you need to move avg calculation and final array creation outside the for loop. Also, the average would be the sum divided by total units.
const maxMinAvg = arr => {
let max = arr[0];
let min = arr[0];
let sum = arr[0];
for (var i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i]
}
if (arr[i] < min){
min = arr[i];
}
sum = sum + arr[i];
}
return [max, min, sum / arr.length];;
};
console.log(maxMinAvg([1, 5, 10, -2]));
A slightly more succinct version using array::reduce:
const maxMinAvg = arr => {
const [max, min, sum] = arr.reduce(([max, min, sum], current) => {
if (max < current) max = current;
if (min > current) min = current;
sum += current;
return [max, min, sum];
}, [arr[0], arr[0], arr[0]]);
return [max, min, sum / arr.length];;
};
console.log(maxMinAvg([1, 5, 10, -2]));
I want to create a function that will generate a random number between 0 to 9 which is not in the array.
My code so far:
var myArr = [0,2,3,4];
console.log("Arr: " + myArr);
function newNum(){
console.log("test");
for (var i = 0; i < 10; i++) {
var n = myArr.includes(i)
// I want to return n if it's not present in the array
}
return n;
}
newNum()
I want to return only 1 number. How do I do this?
Thanks.
What about this?
const invalidValues = [0,2,3,4];
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const getValidRandomInt = (min, max) => {
while(true) {
let temp = getRandomInt(min,max)
if(!invalidValues.includes(temp)) {
return temp;
}
}
}
console.log(getValidRandomInt(0,10))
var myArr = [0,2,3,4];
function newNum(){
for (var i = 0; i < 10; i++) {
if (!myArr.includes(i)) {
return i;
}
}
// return -1 if all numbers present in array..
return -1;
}
newNum();
Generate the number within the range by using Math.random() then loop and check whether the number generated is in the array or not, if not in the array return the number:
function getRandomArbitrary(min, max, arr) {
arr = new Set(arr);
while(true){
let val = Math.floor(Math.random() * (max - min) + min);
if(!arr.has(val)){ return val;}
}
}
console.log(getRandomArbitrary(0, 10, [4,3,2]));
Answer:
Use Math.random() * (max - min) + min to get a number within a range.
You can wrap it with Math.floor to round down to an integer, or alternatively use a bitwise OR ( | ) for small numbers.
function newNum(n_arr) {
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
Example:
var myArr = [0,2,3,4];
function newNum(n_arr){
let r = () => Math.random()*9 | 0,
n = r();
while(n_arr.includes(n)) {
n = r();
}
return n;
}
let result = newNum(myArr);
console.log(result);
var myArr= [0,2,5];
function randomNumber(myArr, n){
n ? n : 1;
var num = Math.random() * n;
if(myArr.indexOf( num ) !==-1 ) {
return randomNumber( myArr, n );
}
return num;
}
randomNumber(myArr, 10);
If you want to return the first number missing in the array, from your code above, you could just check if every value of i exists in the array and the moment that value doesn't exist, return it.
var myArr = [0,2,3,4]; // original array
function newNum(){
for (var i = 0; i < 10; i++) { // loop through i from 0-9
if (myArr.indexOf(i) === -1){ // check for the first missing number
return i; //return it
}
}
}
newNum()