I have this code - its a bit tricky:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++;
output.current = input;
return JSON.stringify(output);
}
The output looks like this:
{"current":605,"sum":0}
{"current":708}
{"current":456}
{"current":1838,"sum":1769}
{"current":1619}
{"current":1404}
{"current":1068,"sum":6630}
{"current":1178}
{"current":989}
{"current":1280,"sum":9865}
But I want it to look like this:
{"current": 605}
{"current": 708}
{"current": 456}
{"current": 1838,"sum":1769}
{"current": 1619}
{"current": 1404}
{"current": 1068,"sum":6630}
{"current": 1178}
{"current": 989}
{"current": 1280,"sum":9865}
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {
"current": "0"
};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++;
output.current = input;
return JSON.stringify(output);
}
I don't want to show the sum the first time but later show it every 3 times
Got any ideas? :D
PS. I prefer staying basic and only use a for loop
Have a nice evening
Could you just check if the i is not zero when you assign the value of output.sum?
Something like the following:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
if (i !== 0) output.sum = sum; // HERE
}
i++;
output.current = input;
return JSON.stringify(output);
}
I found this out, yours is obviously shorter but here was my Idea :D
let i = 0;
const inputBuffer = [];
let db = false;
const randomnumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
for (let k = 0; k < 10; k++) {
console.log(convert(randomnumber(0, 1982)));
}
function convert(input) {
inputBuffer.push(input);
const output = {"current" : "0"};
if (db && i % 3 == 0) {
let sum = 0;
for (let ii = 0; ii < i; ii++) {
sum += inputBuffer[ii];
}
output.sum = sum;
}
i++
db = true;
output.current = input;
return JSON.stringify(output);
}
This is my solution and it passes some of the tests, but not all of them. Can anyone help me and explain why? Thank you :)
function evenLast(numbers) {
let sum = 0;
let lastNum = numbers.pop();
let arr = numbers.filter(el => el % 2 === 0);
for(let i = 0; i < arr.length; i++) {
sum += (arr[i] * lastNum);
}
return sum;
}
You need to check the index, not the value
let arr = numbers.filter((_, i) => i % 2 === 0);
And you could multiply the sum at the last step.
for (let i = 0; i < arr.length; i++) {
sum += arr[i]);
}
return sum * lastNum;
A better approach takes only a single loop and sums the values by taking an increment of two.
function evenLast(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i += 2) sum += numbers[i];
return sum * numbers[numbers.length - 1];
}
function evenLast(arr) {
var lastarr = arr.slice(arr.length-1)
//return lastarr;
let newarr = [];
for(i=0; i<arr.length; i++){
if(arr[i] % 2 === 0) {
newarr.push(arr[i]);
}
}
//return newarr;
var sum1 =0;
for(i=0; i<newarr.length; i++) {
var sum = newarr[0] * lastarr[0];
var sum1 = newarr[1] * lastarr[0];
//return sum;
var sum2 = sum1 + sum;
//i++;
}
return sum2;
}
console.log(evenLast([2, 3, 4, 5]))
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 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;
}
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);
}