Max-Mn Sum JavaScript HackerRank challenge - javascript

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)

Related

how to get output 2 with Fibonacci number in array

function isPerfectSquare(num)
{
let n = parseInt(Math.sqrt(num));
return (n * n == num);
}
// Function to check
// if the number is
// in Fibonacci or not
function checkFib(array, n)
{
let count = 0;
for (let i = 0; i < n; i++)
{
if (isPerfectSquare(5 * array[i] *
array[i] + 4) ||
isPerfectSquare(5 * array[i] *
array[i] - 4))
{
console.log(array[i] + " ");
count++;
}
}
if (count == 0)
console.log("None present + <br>");
}
// Driver Code
let array = [15, 1, ,3];
let n = array.length;
checkFib(array, n);
that is function to check nearest fibonaci how to get the output
Question : with Array [ 15, 1, 3 ] Expected Output is 2 because nearest fibonacci of 19 is 21 = 2
Thank u for help. :)
I just write code to get nearest fibonacci, may it should help you. It works !
const getNearestFibonacci = (array) => {
const total = array.reduce((acc, v) => acc + v);
let fibo = [0, 1];
do {
fibo = [...fibo, fibo[fibo.length - 1] + fibo[fibo.length - 2]];
} while (fibo[fibo.length - 1] < total);
const afterTotal = fibo[fibo.length - 1];
const beforeTotal = fibo[fibo.length - 2];
const next = afterTotal - total;
const prev = total - beforeTotal;
return next < prev ? next : prev;
};
console.log("getNearestFibonacci", getNearestFibonacci([15, 1, 3]));
Your code checks Fibonacci numbers in an array and outputs them. To check nearest Fibonacci, you need a number, why array? Are you summing numbers in array? If yes, then:
First, add array[i] as sum = sum + array[i]
Then, call NearestFibonacci (sum)
where,
NearestFibonacci (int sum){
if (sum == 0) {
cout << 0;
return;
}
int first = 0, mid = 1;
int last = first + mid;
while (last <= sum) {
first = mid;
mid=last;
last = first + mid;
}
int ans = min(last - sum, sum - mid);
cout << ans;
}

Not able to get value after Do...While loop

Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))

Getting values higher than average in Array - JS

I'm trying to get all the numbers that are higher than the average of a given Array.
(this goes into an HTML page so it's with document.write
this is what I wrote:
sumAndBigger(arrayMaker());
function sumAndBigger(array) {
for (i = 0; i < array.length; i++) {
sum += array;
}
var equalAndBigger = []
var avg = sum / array.length;
for (i = 0; i < array.length; i++) {
if (array[i] > avg) {
equalAndBigger.push(array[i])
}
}
document.write('The numbers are: ' + equalAndBigger)
}
function arrayMaker() {
var array = [];
for (i = 0; i < 5; i++) {
var entrie = +prompt('Enter a number: ');
array.push(entrie)
}
return array;
}
This doesn't seem to work.. what am I doing wrong here?
Thanks in advance!
Ok so here I am giving you a one-liner code to get all the elements from the array that are "strictly greater than" the average value
let array = [1, 2, 3, 4, 5]
let allNums = array.filter(v => v > array.reduce((x, y) => x + y) / array.length);
Explanation
array.reduce((x, y) => x + y) → sum of all elements in the array
array.reduce((x, y) => x + y) / array.length → getting the average
Output
[4, 5]
MORE DETAILED CODE
function getAverage(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
function getGreaterThanAverage(arr) {
let avg = getAverage(arr);
let numbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > avg) {
numbers.push(arr[i]);
}
}
return numbers;
}

Javascript Max Min Avg

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]));

Find missing numbers in JavaScript array

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);
}

Categories

Resources