How do I find the largest negative integer in an array? - javascript

let test12 = [-1, -2, -3];
I'm stuck on this one. I used the below on positive integers but I'm not sure what to change for negatives.
let test = [1 , 2, 3];
var largest= 0;
for (i=0; i<=test.length;i++){
if (test[i]>largest) {
largest=test[i];
}
}
console.log(largest);

largest negative integer in an array
Your question can have 3 interpretations:
The negative integer that is farthest from 0
The negative integer that is closest to 0
The largest number in general (you might be struggling if an all negative integer array comes along, because you initialize min to 0)
Just to clarify, smallest is 'farthest from zero'. But here's all three ways :) :
const ints = [-3, -2, -1, 0, 1, 2]
const negativeInts = ints.filter(i => i < 0)
const smallestNegative = Math.min(...negativeInts)
const largestNegative = Math.max(...negativeInts)
const largestOverall = Math.max(...ints)
console.log({smallestNegative, largestNegative, largestOverall}) // -3, -1, 2
Hope this helps. Cheers.

Just initialize largest to -Infinity rather than 0. You also need to iterate over the input array's length, not 0 to largest:
let test12 = [-1, -2, -3];
var largest = -Infinity;
for (i = 0; i < test12.length; i++) {
if (test12[i] > largest) {
var largest = test12[i];
}
}
console.log(largest);
Another method would be to spread into Math.max:
let test12 = [-1, -2, -3];
console.log(
Math.max(...test12)
);

Largest negative would be -244, so you can sort and get the first index.
let arr = [-1, -2, -244, -7],
[largets] = arr.slice().sort((a, b) => a - b);
console.log(largets);

Try this..
var array = [-155,3, 6, 2, 56, 32, 5, -89, -32,115,-150];
array.sort(function(a, b) {
return a - b;
});
console.log(array[0]);

In case you want a programming solution ,like an edit that your program needs to perform even if an all negative array is given, then try this :
let test = [-10, -1, -2, -3];
// just Assign largest to the first element in test.
// the largest int might not be greater than zero,
// but will definitely be larger that any other element in the array.
var largest= test[0];
for (i=0; i<=test.length;i++){
if (test[i]>largest) {
largest=test[i];
}
}
console.log(largest);

Related

Converting an array of digits into a number for large numbers ignores some digits

I am converting array digits into a number e.g. [1,2,4] = 124.
This code is working for smaller values but when I checked for big values like [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3], I was not able to add the last 543 to my sum.
var plusOne = function(digits) {
let tsum = 0;
let sum = 0;
for (let i = 0; i < digits.length; i++) {
let k =Math.pow(10, (digits.length - (i + 1)));
tsum = arr[i]* k;
console.log(tsum);
sum = sum + tsum;
console.log(sum);
}
console.log(sum);
sum= sum + 1;
let cnt=0;
while (sum!=0) {
digits.unshift(Math.floor(sum%10));
sum = Math.floor(sum/10);
cnt++;
}
digits.length = cnt;
return digits;
};
let arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3];
console.log(plusOne(arr));
First, join the digits and make a string:
const joined =[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3].join('')
// output: "6145390195186705543"
Second, convert the string to a BigInt:
const number = BigInt(joined)
Your method for adding a one to a an array of digits won’t work for large numbers. JavaScript stores all numbers as a floating point, so as Darshna Rehka and pesehr suggested, you should use BigInt for this. See Issue with combining large array of numbers into one single number
for more information.
Although this doesn’t directly answer your question, here’s a different implementation of plusOne that should work for larger numbers:
const plusOne = digits => {
// Base case: treat empty arrays as 0 so return [1]
// This part is important for the recursion below
if (!digits.length) return [1];
const init = digits.slice(0, -1);
const last = digits[digits.length - 1];
return last === 9
// 9 + 1 = 10, carry the 1 (add 1 to the rest of the digits)
// If there are no more digits to the left of the 9 (init.length === 0),
// plusOne(init) will just return [1] (base case)
? [...plusOne(init), 0]
// Simply add 1 to the last digit and keep the rest
: [...init, last + 1];
};
const arr = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
console.log(plusOne(arr).join(''));
console.log(plusOne([1, 8, 9]).join(''));
console.log(plusOne([9, 9, 9]).join(''));

JavaScript: Rearrange an array in order – largest, smallest, 2nd largest, 2nd smallest, 3rd largest, 3rd smallest,

Given an array of integers, where the values should be sorted in the following order:
if we have an array
[1, -1, -3, 9, -2, -5, 4, 8,]
we must rearrange it this way: largest number, smallest number, 2nd largest number, 2nd smallest number, ...
[9, -5, 8, -3, 4, -2, 1, -1 ]
I get the first largest and smallest numbers, but can't figure out how to make it dynamic for all values in the array.
I know that I must take two variables, say firstSmallest and firstLargest and point them to the first and last index of the array respectively, run a loop, which I do already in the code below, and store value into new array by incrementing firstSmallest and decrementing firstLargest, but couldn't implement into code.
let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => a-b);
let firstSmallest = sorted[0];
let firstLargest = sorted[unsorted.length-1];
for(let i = 0; i <= sorted.length; i++){
//I should increment firstSmallest and decrement firstLargest numbers and store in output
}
return output;
}
meanderArray(unsortedArr);
console.log(output);
You could take a toggle object which takes the property of either the first item or last from an array and iterate until no more items are available.
function meanderArray([...array]) {
const
result = [],
toggle = { shift: 'pop', pop: 'shift' };
let fn = 'shift';
array.sort((a, b) => a - b);
while (array.length) result.push(array[fn = toggle[fn]]());
return result;
}
console.log(...meanderArray([1, 5, 8, 7, 6, -1, -5, 4, 9, 5]));
You can sort an array by descending, then logic is the following: take first from start and first from end, then second from start-second from end, etc.
let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => b-a);
let output = []
for(let i = 0; i < sorted.length/2; i++){
output.push(sorted[i])
if(i !== sorted.length - 1 - i){
output.push(sorted[sorted.length - 1 - i])
}
}
return output;
}
let result = meanderArray(unsortedArr);
console.log(result);
You can sort, then loop and extract the last number with pop() and extract the first number with shift().
let unsortedArr = [1, -1, -3, 9, -2, -5, 4, 8,]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => a - b);
for(let i = 0; i < unsortedArr.length + 2; i++){
output.push(sorted.pop());
output.push(sorted.shift());
}
console.log(output);
return output;
}
meanderArray(unsortedArr);
Fastest Meandering Array method among all solutions mentioned above.
According to the JSBench.me, this solution is the fastest and for your reference i have attached a screenshot below.
I got a different approach, but i found that was very close to one of above answers from elvira.genkel.
In my solution for Meandering Array, First I sorted the given array and then i tried to find the middle of the array. After that i divided sorted array in to two arrays, which are indices from 0 to middle index and other one is from middle index to full length of sorted array.
We need to make sure that first half of array's length is greater than the second array. Other wise when applying for() loop as next step newly created array will contains some undefined values. For avoiding this issue i have incremented first array length by one.
So, always it should be firstArr.length > secondArr.length.
And planned to create new array with values in meandering order. As next step I created for() loop and try to push values from beginning of the first array and from end of the second array. Make sure that dynamically created index of second array will receive only zero or positive index. Other wise you can find undefined values inside newly created Meandering Array.
Hope this solution will be helpful for everyone, who loves to do high performance coding :)
Your comments and suggestions are welcome.
const unsorted = [1, 5, 8, 7, 6, -1, -5, 4, 9, 5];
const sorted = unsorted.sort((a,b)=>a-b).reverse();
const half = Math.round(Math.floor(sorted.length/2)) + 1;
const leftArr = sorted.slice(0, half);
const rightArr = sorted.slice(half, sorted.length);
const newArr = [];
for(let i=0; i<leftArr.length; i++) {
newArr.push(leftArr[i]);
if (rightArr.length-1-i >= 0) {
newArr.push(rightArr[rightArr.length-1-i]);
}
}

How to ignore a negative number in Javascript?

I understand that Math.abs is used to convert negative numbers to absolute in JavaScript, but say I want to filter out negative numbers in an array for example, how do I do that? Is there a function for that?
This should solve your issue [1, 2, -3 , 4, -5].filter(val => val > 0);
If you want to eliminate the values, #Antoni 's approach will do.
However, if you want to retain elements but bound the values (also known as clamping) I usually use Math.max(0, number); to set a lower numerical bound - if number is <0, it returns 0.
You can apply this to an array using map:
var array = [1, -2, 3];
array = array.map(number => Math.max(0, number));
//Sets array == [1, 0, 3]
Similarly for an upper bound you can use Math.min(upperLimit, number); and of course you can apply them both for upper and lower bounds:
var array = [1, -2, 3];
const lowerLimit = 0;
const upperLimit = 2;
array = array.map(number => Math.max(lowerLimit, Math.min(upperLimit, number)));
//Sets array == [1, 0, 2]

Find 2nd largest value in an array that has duplicates of the largest integer

I'm trying to find the second largest number in an array of numbers, but the greatest number appears twice, so I can't just remove it from the array and select the new highest number.
array = [0, 3, 2, 5, 5] (therefore 3 is the 2nd largest value)
I have this code where I can explicitly return 3, but it wouldn't work on other arrays:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
If I wanted to make it more dynamic, is there a way that I could identify the greatest value of the array, then compare that against each iteration of the array?
I was thinking that something along the lines of:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
Any help would be appreciated.
You can simply create a Set first and than sort in descending and take the 1st index element
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)
For those who thinks in terms of efficiency. this is the best way IMO
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)
I’d recommend doing something more like
const nums = [0, 3, 2, 5, 5];
nums.sort(function (a,b) {return b - a;})
for (let i = 1; i < nums.length; i++) {
if (nums[0] !== nums[i]) {
return nums[i];
}
}
which should be a lot more efficient (especially in terms of memory) than converting to a set and back...
Try this:
var intArray = stringArray.map(nums); // now let's sort and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
};
For those who wants to do this using Math.max(). Here's the simplest way to do this.
const getSecondLargest = function (arr) {
const largest = Math.max.apply(null, arr);
for (let i = 0; i < arr.length; i++) {
if (largest === arr[i]) {
arr[i] = -Infinity;
}
}
return Math.max.apply(null, arr);
};
console.log(getSecondLargest([3, 5, 9, 9, 9])); //5
Side note: Math.max() don't take an array, so we have to use Math.max.apply() to pass the array in the function. -Infinity is smaller than any negative finite number.

Sort an array in a peculiar order

I've been trying to figure out how to solve this problem but I can't seem to find the proper sorting order.
Instructions:
Write a program that orders a list of numbers in the following way:
3,-2,1,0,-1,0,-2,1 => -2,-1,-2,0,0,3,1,1
'use strict';
let myNumbers = '3,-2,1,0,-1,0,-2,1';
// I receive the input as a string and split and map it into an array
let myNumbers = gets().split(',').map(Number);
I've tried applying the sort() method in ascending order to all integers below zero and doing the opposite for those above but that's not quite the order in the expected output.
I've also attempted to splice the first array after applying sort() to 0 and then re-arrange the spliced part and concatenate it. However, that won't work with all test inputs.
Another example:
3,-12,0,0,13,5,1,0,-2 => -12,-2,0,0,0,3,13,5,1
What is the logic in this order? Thanks.
Because this sounds like the solution to a homework problem or something of the like, I'll let you write the code:) But the way I would do it is in one iteration through the array, create three separate arrays:
Negative numbers
0s
Positive numbers
Squish the arrays together without sorting and you have your O(N) solution.
So based on sketrik answer which covers the logic, this is the code:
const myNumbers = '3,-2,1,0,-1,0,-2,1';
const arr = myNumbers.split(',').map(Number)
const res = arr.filter(i => i < 0)
.concat(arr.filter(i => i === 0))
.concat(arr.filter(i => i > 0))
console.log(res)
This works thanks to two very basic JS methods of Array.prototype:
concat and filter. I could not explain them better than the documentation, check it out!
But basically, what I am doing is:
find the chunk with negatives with arr.filter(i => i < 0)
find the chunk with zeros with arr.filter(i => i === 0)
find the chunk with positives with arr.filter(i => i > 0)
concat them all into one array.
I am Neo.
'use strict';
let myInput = '3,-2,1,0,-1,0,-2,1';
let myNumbers = myInput.split(',').map(Number);
let negatives = [];
let zeroes = [];
let positives = [];
for (const element of myNumbers) {
if (element < 0) {
negatives.push(element);
} else if (element === 0) {
zeroes.push(element);
} else if (element > 0) {
positives.push(element);
}
}
let sortedArr = negatives.concat(zeroes, positives);
console.log(sortedArr.join(','));
Logic or Typo?
"...ascending order to all integers below zero and doing the opposite for those above..."
Following what was posted in question the examples should be:
-2, -2, -1, 0, 0, 3, 1, 1 and -12, -2, 0, 0, 0, 13, 5, 3, 1
Zero and less ascending: -3, -2, -1, 0. Greater than zero descending: 3, 2, 1
To get those results see Demo 1.
Strictly going by the examples is simpler:
-2, -1, -2, 0, 0, 3, 1, 1 and -12, -2, 0, 0, 0, 3, 13, 5, 1
Group negative numbers, then zeros, and then positive numbers: [-][0][+]. No order within the three arrays is required. Order is only required for the three groups.
To get those results see Demo 2.
Explanation
Demo 1
First, sort array in ascending order:
const ordered = array.sort((current, next) => current - next);
Next, find the index of the first number that's greater than 0, then extract all numbers beginning at that index and ending at the last number. Store the extracted array in a variable:
const positive = ordered.splice(ordered.findIndex(number => number > 0));
Finally, sort extracted array in descending order and then concatenate the extracted array to the end of the original array:
return ordered.concat(positive.sort((current, next) => next - current));
Demo 2
Create three new arrays returned by the filter() method: negative (n < 0), zero (n === 0), and positive (n > 0).
Then concatenate them into one array:
const negative = array.filter(number => number < 0);
const zero = array.filter(number => number === 0);
const positive = array.filter(number => number > 0);
return negative.concat(zero, positive);
Demo 1
const unorderedA = [3, -2, 1, 0, -1, 0, -2, 1];
const unorderedB = [3, -12, 0, 0, 13, 5, 1, 0, -2];
const illogical = array => {
const ordered = array.sort((current, next) => current - next);
const positive = ordered.splice(ordered.findIndex(number => number > 0));
return ordered.concat(positive.sort((current, next) => next - current));
};
// For demonstration purposes
const log = data => {
const string = Array.isArray(data) ? `[${data.join(', ')}]` : data;
return console.log(string);
};
log(illogical(unorderedA));
log(illogical(unorderedB));
Demo 2
const unorderedA = [3, -2, 1, 0, -1, 0, -2, 1];
const unorderedB = [3, -12, 0, 0, 13, 5, 1, 0, -2];
const illogical = array => {
const negative = array.filter(number => number < 0);
const zero = array.filter(number => number === 0);
const positive = array.filter(number => number > 0);
return negative.concat(zero, positive);
};
// For demonstration purposes
const log = data => {
const string = Array.isArray(data) ? `[${data.join(', ')}]` : data;
return console.log(string);
};
log(illogical(unorderedA));
log(illogical(unorderedB));

Categories