Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Given a sorted array of numbers, how do you get ranges of consecutive numbers? The function should return ranges and single numbers as a string. Example:
function findRanges(arrayOfSortedNumbers) {
// logic here
}
findRanges([1, 3, 4, 5, 7]) => (expected output: "1, 3-5, 7")
findRanges([1, 2, 3, 5]) => (expected output: "1-3, 5")
findRanges([2, 3, 4, 5, 6]) => (expected output: "2-6")
Sorry for not being able to explain the problem better.
You can use Array.reduce() to do it:
Sort the array (safety)
Iterate over the array with reduce to create an object containing the ranges and the start of the active range (rangeStart).
On the first iteration, push the first element in the ranges and save this element as the rangeStart
On the successive iterations, if the value equals the last value + 1, we are in the same range, so we update it by changing the last value in the ranges array. Otherwise, we push the element in the ranges array and update rangeStart to be this element.
Return the ranges property of the object output by reduce and join it using commas.
function findRanges(numbers) {
return [...numbers].sort((a, b) => a - b).reduce((acc, x, i) => {
if (i === 0) {
acc.ranges.push(x);
acc.rangeStart = x;
} else {
if (x === acc.last + 1) {
acc.ranges[acc.ranges.length-1] = acc.rangeStart + '-' + x;
} else {
acc.ranges.push(x);
acc.rangeStart = x;
}
}
acc.last = x;
return acc;
}, { ranges: [] }).ranges.join(', ');
}
console.log(findRanges([1, 3, 4, 5, 7]));
console.log(findRanges([1, 2, 3, 5]));
console.log(findRanges([2, 3, 4, 5, 6]));
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
In JavaScript, I'm trying to select random elements from an array, either in ascending and descending order. I would like to create a function that takes an array to select from, the number of elements to select and the random order (either ascending or descending). How can I go about doing this?
e.g
let ar = [a,b,c,d,e,f,g,h,i,j,k,l]
selectRandom(ar, 4, 'ascending')
// returns [b,e,f,j]
selectRandom(ar, 6, 'descending')
// returns [l,j,f,e,b,a]
You could build random arrays and sort them as result.
const
getValues = (array, size) => {
const values = new Set;
while (values.size < size) values.add(array[Math.floor(Math.random() * array.length)]);
return [...values];
},
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
up = 4,
down = 7,
result = [
...getValues(array, up).sort((a, b) => a - b),
...getValues(array, down).sort((a, b) => b - a)
];
console.log(...result);
Maybe something like this:
let array = [1,2,3,4,5,6,7,8,9,10,11,12]
const up = 4
const down = 7
let outputRadnomUpDown = new Array(up).fill(null).map(() => array[~~(Math.random() * array.length)]).sort(function(a, b){return a-b}).concat(new Array(down).fill(null).map(() => array[~~(Math.random() * array.length)]).sort(function(a, b){return b-a}));
console.log(outputRadnomUpDown);
PS: I've edited the answer because by mistake I've switch the number of up/down elements in my previous proposition.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
How do I compare elements in an array using Javascript?
I want to know if cas[1], cas[2] and cas[3] have the same value.
cas = ["0","1", "2","3","4","5","6","7","8","9"];
if(cas[1]== cas[2] && cas[2]==cas[3]){
console.log("yea");
}
The first of all it's better to use ===, because 0 == false is true, but 0 === false is false.
=== works without type casting.
You don't need full cycle loop here, you have to compare only the first 3 elements so if statement is ok here.
If you want to do that with every 3 elements, you can do something like this.
const getThreeArrayElements = (array, startIndex) => array.slice(startIndex, startIndex + 3);
getThreeArrayElements([1, 2, 3, 3, 3, 3], 0); // [1, 2, 3]
getThreeArrayElements([1, 2, 3, 3, 3, 3], 3); // [3, 3, 3]
So you can easily get an array with 3 required elements.
The another task is how to compare them.
const areArrayElementsEqual = array => array.every(item => item === array[0]);
areArrayElementsEqual([1, 2, 3]); // false
areArrayElementsEqual([3, 3, 3]); // true
if you're looking for an algorithm to check the entire array :
let cas = ["0","1", "2","3","4","5","6","7","8","9"];
let checkCas = (cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?checkCas(++cur):false;};
console.log(checkCas());
cas = ["0","1", "2","3","4","5","5","7","8","9"];
console.log(checkCas());
as for ticktacktoe :
let casa = ["0","1", "2","3","4","5","6","7","8","9"];
let allEqual = (cas,cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?allEqual(cas,++cur):false;};
for(let i = 0;i<Math.floor(casa.length/3);i++)
{
let tempLengArr = [casa[i],casa[i+3],casa[i+6]];
if(allEqual(casa.slice(i*3,(i*3)+3))||allEqual(tempLengArr))
console.log("won");
}
if(allEqual([casa[0],casa[4],casa[9]])||
allEqual([casa[3],casa[4],casa[2]])) console.log("won");
might have messed up a bit on my allEqual call but it's an idea
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1, 2, 3, 4, 4, 4, 3], 4)); // 3
I was watching for explanation in manuals, but it seems to me very complex to understand.
So I get that 0 is the starting total, and that x===1 should be equal to 1 or 0 depending on the truth.
I'm mainly confused with n because I read that n is the return value of the previous function, but there's no previous function in the beginning.
but there's no previous function in the beginning.
Exactly - The "previous function" doesn't exist at the start - so n starts off as 0, the second argument you passed to reduce. The docs give you the argument list:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
The last argument there is initialValue, which is exactly what it sounds like - it is the inital value of accumulator.
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1, 2, 3, 4, 4, 4, 3], 4)); // 3
the above countInArray function look up the no of instances of given value in given array.
in JS true is equal to 1 therfore 0 + 1 is 2 and so on.
countInArray([1, 2, 3, 4, 4, 4, 3], 4) here you are trying to count the no of inctance of 4 the answer is 3.
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1, 2, 3, 4, 4, 4, 3], 4)); // 3
Lets break it into parts:
The function countInArray intends to count occurrences of the value (not necessarily a number) in a given array. Therefore accepts an array and a value.
The reduce function works on the given array. it gets 2 params: a function and a initialization value for the accumulator.
the function also get 2 params: an accumulator (n in this case) and a current value (x in this case). They are both accessible in every iteration, but the accumulator's keeps its value between iterations while the current value varies at each itaration (possess a new array value).
In every iteration we ask if the current array value equals the value we entered in step 1, if so, we increase by 1 the accumulator (which was initialized to 0 ).
*. The line n + (x === value) can be a little confusing. notice that in javascript 1 + true equals 2 and 1 + false stays 1.
In an attempt to improve my general problem solving skills, I recently subscribed to Daily Coding Problem. One of the challenges that came up has the following description:
This problem was asked by Uber.
Given an array of integers, return a new array such that each element
at index i of the new array is the product of all the numbers in the
original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output
would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the
expected output would be [2, 3, 6].
Follow-up: what if you can't use division?
I solved this particular challenge within minutes using the following function:
function solution(_input) {
return _input.map((_number, _index, _list) => {
return _list.reduce((_accumulator, _currentValue, _currentIndex) => {
return _accumulator * ((_index !== _currentIndex) ? _currentValue : 1);
}, 1);
});
}
My function works, matching every expected output perfectly... But this makes me curious about the last line of the challenge.
How could division be used to solve this?
As #Steve alluded in the comments, you would:
first find the product of all the elements in the array:
const product = input.reduce((accumulator, value) => accumulator * value, 1);
then map the array to the product divided by each element.
return input.map(value => product / value);
This reduces operational complexity from O(N2) to O(N) (if I'm not mistaken) because we are removing the nested loop.
const func = input => {
const product = input.reduce((accumulator, value) => accumulator * value, 1);
return input.map(value => product / value);
}
console.log(func([1, 2, 3, 4, 5]));
This question already has answers here:
Summing ; delimited values in Javascript
(1 answer)
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 5 years ago.
I am trying to add together an undetermined amount of arrays, but only add or reduce them item by item.
I cannot figure out how to make this work in ES6 javascript.
const arrayList = [
[1, 2, 3],
[1, 2, 3],
[2, 2, 2]
];
const totalRow = arrayList.map((array) => {
const total = [];
array.map((number, i) => {
total[i] = (total[i] == undefined ? 0 : total[i]) + number;
});
return total;
});
//Output is just 3 more arrays with no change, as it seems
//the total variable resets to an empty array with each iteration.
//what i want is this output:
[4, 6, 8]
What am I doing wrong? I tried reduce method as well but came up empty