Count number of values in array between two input values - javascript

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the array was [1, 4, 6, 7, 8, 6] and the user entered 5 as their first value and 7 as their second value, they would be greeted with an alert that said
"total number of values = 3".

You can create an extremely clean solution to this problem by utilizing the second property of Array#filter (which sets the this binding given to your callback of choice):
var array = [1, 4, 6, 7, 8, 6]
function inRange (x) {
return this[0] <= x && x <= this[1]
}
var result = array.filter(inRange, [5, 7]).length
console.log('Total number of values:', result)

All you need is a simple for loop.
var total = 0;
var num1 = 5;
var num2 = 7;
var array = [1,4,6,7,8,6];
for(var a = 0; a < array.length; a++) {
if(array[a] >= num1 && array[a] <= num2) {
total++;
}
}
alert("Total numbers of values = " + total);
This will loop through the array, detect nums within the range, tally up a value, and output it in a alert.

You can use Array.prototype.filter(), RegExp.prototype.test() with RegExp constructor with class from-to, where from is 5, to is 7, get .length of resulting array
var from = 5;
var to = 7;
var len = arr.filter(RegExp.prototype.test.bind(new RegExp(`[${from}-${to}]`))).length;
You can alternatively use .toString(), .match()
var arr = [1,4,6,7,8,6];
var from = 5;
var to = 7;
var res = arr.toString().match(new RegExp(`[${from}-${to}]`, "g"));
var len = res.length;
console.log(res.length);

You may do as follows;
var arr = [1,4,6,7,8,6],
input = [5,7],
result = arr.reduce((r,n) => n >= input[0] && n <= input[1] ? ++r : r, 0);
console.log(result);

var array = [1, 4, 6, 7, 8, 6];
function countNumber(arr,a,b){
let count = 0;
for (const number of arr){
if (number >= a && number <= b){
count ++;
}
}
return count;
}
console.log(countNumber(array, 5, 7));

Related

Way to multiply each element of one array to PARTS of another?

I am newbie in programming and try to find out how to multiply
[1,1,0]
to
[4,9,7,2,1,6]
for the next result output
[4,9,7,2,0,0]
As you see I want to multiply each value of [1,1,0] array to each two of second array by shifting in them
[1..] * [4,9..] = [4,9]
[.1.] * [.7,2.] = [7,2]
[..0] * [..1,6] = [0,0]
As example in js i writed something like
var firstArray = [1,1,0];
var secondArray = [4,9,7,2,1,6];
var shift = secondArray / firstArray;
var startpos = 0;
var outArray = [];
for(i=0; i< firstArray.length; i++){
for(z=i; z< shift+i; z++){
outArray.push(firstArray[i] * secondArray[z]);
}
}
console.log(outArray);
It may be in python
You can abuse zip and list slicing:
a = [1, 1, 0]
b = [4, 9, 7, 2, 1, 6]
shift = len(b) // len(a) # use / in Python 2
li = []
for num_a, num_b1, num_b2 in zip(a, b[::shift], b[1::shift]):
li.extend([num_a * num_b1, num_a * num_b2])
print(li)
# [4, 9, 7, 2, 0, 0]
You can express this as a standard matrix multiplication by making your inputs 2D arrays.
I got the multiplication algorithm from here: https://stackoverflow.com/a/27205510/5710637
The calculation would now look like:
[1,0,0] [4,9] [4,9]
[0,1,0] * [7,2] = [7,2]
[0,0,0] [1,6] [0,0]
function multiplyMatrices(m1, m2) {
var result = [];
for (var i = 0; i < m1.length; i++) {
result[i] = [];
for (var j = 0; j < m2[0].length; j++) {
var sum = 0;
for (var k = 0; k < m1[0].length; k++) {
sum += m1[i][k] * m2[k][j];
}
result[i][j] = sum;
}
}
return result;
}
var in1 = [[1, 0, 0], [0, 1, 0], [0, 0, 0]];
var in2 = [[4, 9], [7, 2], [1, 6]]
console.log(multiplyMatrices(in1, in2))
In Javascript, you could use a more functional approach by using
Array#reduce for iterating the factors and returning a new array,
Array#concat for adding a part result after multiplying to the result set,
Array#slice, for getting only two elements of the values array,
Array#map for multiplying the part array with the given factor,
at least use an array as start value for reduce.
var factors = [1, 1, 0],
values = [4, 9, 7, 2, 1, 6],
result = factors.reduce(
(r, f, i) => r.concat(
values
.slice(i * 2, (i + 1) * 2)
.map(v => f * v)
),
[]
);
console.log(result);
You can do this:
Iterate over first array so that you get a number to multiply.
Then extract two elements from the target array and multiply, store the result in res array.
var mul = [1,1,0];
var target = [4,9,7,2,1,6];
var start = 0;
var res = [];
mul.forEach(function(v,i) {
var arr = target.slice(start, start+2);//from start index extract two
//elements
arr.forEach(function(val,i) {
res.push(v * val);
});
start += 2;
});
console.log(res);
You can use map() on array2 and use one var for incrementing index of array1 for each two elements and then multiply current element of array1 with element from array2 that has index as that var.
var a1 = [1,1,0];
var a2 = [4,9,7,2,1,6];
var j = 0;
var result = a2.map(function(e, i) {
if(i % 2 == 0 && i != 0) j++
return e * a1[j];
})
console.log(result)
In python you can use the following code. I'm assuming the length of the second array is larger and it is divisible by the length of the shorter array
def multiply(a, b):
x, y = len(a), len(b) # Find lengths
assert x % y == 0
n = x / y
result = [a[i] * b[i / n] for i in range(x)] # For each index in a, calculate the appropriate element in output by multiplying with relevant part
print result

Check if random numbers in array contains 5 of them in ascending order

Hello I want to check if 5 random numbers in array are ascending.
Example from this:
var array = [2, 5, 5, 4, 7, 3, 6];
to this:
array = [2,3,4,5,6];
and of course if higher sequence is possible:
array = [3,4,5,6,7];
Is there any shortcut for this kind of sorting in jQuery?
Thanks in advance.
var array = [2, 5, 5, 4, 7, 3, 6];
//first convert into an object literal for fast lookups.
var ao = {};
array.forEach(function (e) { ao[e] = true; });
//now loop all in array, and then loop again for 5
array.forEach(function (num) {
var count = 0, l;
for (l = 0; l < 5; l ++) {
if (ao[num + l]) count ++;
}
if (count === 5) {
//found, push into array just to show nice in console
var nums = [];
for (l = 0; l < 5; l ++) {
nums.push(num + l);
}
console.log(nums.join(','));
}
});
I think, this will do the trick:
get unique members
sort them
slice last 5
(or reverse, slice first 5, reverse) like I did, since your array could be less then 5.
If resulting array has length of 5 then you have a positive answer.
console.log($.unique([2,5,5,4,7,3,6]).sort().reverse().slice(0,5).reverse())
You might do as follows;
function checkStraight(a){
var s = [...new Set(a)].sort((a,b) => a-b);
return s.length >= 5 && s.reduce((p,c,i,a) => c - a[i-1] === 1 ? ++p
: p < 5 ? 1
: p , 1) > 4;
}
var array = [2, 5, 5, 4, 7, 3, 6, 9],
result = checkStraight(array);
console.log(result);

Find Missing Numbers from Unsorted Array

I found this JavaScript algorithm excercise:
Question:
From a unsorted array of numbers 1 to 100 excluding one number, how will you find that number?
The solution the author gives is:
function missingNumber(arr) {
var n = arr.length + 1,
sum = 0,
expectedSum = n * (n + 1) / 2;
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i];
}
return expectedSum - sum;
}
I wanted to try and make it so you can find multiple missing numbers.
My solution:
var someArr = [2, 5, 3, 1, 4, 7, 10, 15]
function findMissingNumbers(arr) {
var missingNumbersCount;
var missingNumbers = [];
arr.sort(function(a, b) {
return a - b;
})
for(var i = 0; i < arr.length; i++) {
if(arr[i+1] - arr[i] != 1 && arr[i+1] != undefined) {
missingNumbersCount = arr[i+1] - arr[i] - 1;
for(j = 1; j <= missingNumbersCount; j++) {
missingNumbers.push(arr[i] + j)
}
}
}
return missingNumbers
}
findMissingNumbers(someArr) // [6, 8, 9, 11, 12, 13, 14]
Is there a better way to do this? It has to be JavaScript, since that's what I'm practicing.
You could use a sparse array with 1-values at indexes that correspond to values in the input array. Then you could create yet another array with all numbers (with same length as the sparse array), and retain only those values that correspond to an index with a 1-value in the sparse array.
This will run in O(n) time:
function findMissingNumbers(arr) {
// Create sparse array with a 1 at each index equal to a value in the input.
var sparse = arr.reduce((sparse, i) => (sparse[i]=1,sparse), []);
// Create array 0..highest number, and retain only those values for which
// the sparse array has nothing at that index (and eliminate the 0 value).
return [...sparse.keys()].filter(i => i && !sparse[i]);
}
var someArr = [2, 5, 3, 1, 4, 7, 10, 15]
var result = findMissingNumbers(someArr);
console.log(result);
NB: this requires EcmaScript2015 support.
The simplest solution to this problem
miss = (arr) => {
let missArr=[];
let l = Math.max(...arr);
let startsWithZero = arr.indexOf(0) > -1 ? 0 : 1;
for(i = startsWithZero; i < l; i++) {
if(arr.indexOf(i) < 0) {
missArr.push(i);
}
}
return missArr;
}
miss([3,4,1,2,6,8,12]);
Something like this will do what you want.
var X = [2, 5, 3, 1, 4, 7, 10, 15]; // Array of numbers
var N = Array.from(Array(Math.max.apply(Math, X)).keys()); //Generate number array using the largest int from X
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;}); //Return the difference
};
console.log(N.diff(X));
Option 1:
1. create a binary array
2. iterate over input array and for each element mark binary array true.
3. iterate over binary array and find out numbers of false.
Time complexity = O(N)
Space complexity = N
Option 2:
Sort input array O(nLogn)
iterate over sorted array and identify missing number a[i+1]-a[i] > 0
O(n)
total time complexity = O(nlogn) + O(n)
I think the best way to do this without any iterations for a single missing number would be to just use the sum approach.
const arr=[1-100];
let total=n*(n+1)/2;
let totalarray=array.reduce((t,i)=>t+i);
console.log(total-totalarray);
You can try this:
let missingNum= (n) => {
return n
.sort((a, b) => a - b)
.reduce((r, v, i, a) =>
(l => r.concat(Array.from({ length: v - l - 1 }, _ => ++l)))(a[i - 1]),
[]
)
}
console.log(missingNum([1,2,3,4,10]));
Solution to find missing numbers from unsorted array or array containing duplicate values.
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
var array1 = [1, 3, 4, 7, 9];
var n = array1.length;
var totalElements = array1.max(); // Total count including missing numbers. Can use max
var d = new Uint8Array(totalElements)
for(let i=0; i<n; i++){
d[array1[i]-1] = 1;
}
var outputArray = [];
for(let i=0; i<totalElements; i++) {
if(d[i] == 0) {
outputArray.push(i+1)
}
}
console.log(outputArray.toString());
My solution uses the same logic as trincot's answer
The time complexity is O(n)
const check_miss = (n) => {
let temp = Array(Math.max(...n)).fill(0);
n.forEach((item) => (temp[item] = 1));
const missing_items = temp
.map((item, index) => (item === 0 ? index : -1))
.filter((item) => item !== -1);
console.log(missing_items);
};
n = [5, 4, 2, 1, 10, 20, 0];
check_miss(n);

How to store divisible number in a new array with javascript

I am trying to store the numbers that are divisible by three in the threes array. How is this done?
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push([i]);
console.log(threes);
}
} return threes
};
iLoveThree();
There were a few problems.
You needed to access the number in the array using the index numbers[i] rather than just checking the index.
You also needed to pass the two parameters to the iLoveThree function.
Here is the working code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
var iLoveThree = function (numbers, threes) {
for (i in numbers) {
if (numbers[i] % 3 === 0) {
threes.push(numbers[i]);
}
}
return threes;
};
console.log(iLoveThree(numbers, threes));
// [3, 6, 9]
As a side note, you could simplify your code by using the .filter() method.
If the boolean num % 3 === 0 is true, then the number isn't removed from the array.
var numbers = [1,2,3,4,5,6,7,8,9].filter(function (num) {
return num % 3 === 0;
});
console.log(numbers);
// [3, 6, 9]
you put brackets around i when you did the push. You do not need the brackets.
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push(i); //don't put brackets here
console.log(threes);
}
} return threes
};
Here you go:
var numbers = [1,2,3,4,5,6,7,8,9];
function iLoveThree(numbers) {
return numbers.filter(function(n) {
return n % 3 === 0;
});
}
var threes = iLoveThree(numbers);
Try substituting for loop for..in loop ; using numbers[i] number in array instead of [i] index of item within array in current iteration
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
for(var i = 0; i < numbers.length; i++)
!(numbers[i] % 3) && threes.push(numbers[i]);
console.log(threes)

Access every other item in an array - JavaScript

Is it possible for me to access every other item in an array? So basically, all items in positions 0, 2, 4, 6 etc.
Here's my code if it helps:
function pushToHash(key, value) {
for (var t = 0; t < value.length; t++) {
MQHash[key[t]] = value.slice(0, lineLength[t]);
}
}
So, I need to get every other value of lineLength. I only want this for lineLength, not key. I was thinking of doing a modulus, but wasn't sure how I'd implement it. Any ideas?
Thanks in advance!
You can use the index (second parameter) in the array filter method like this:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// filter out all elements that are located at an even index in the array.
let x = arr.filter((element, index) => {
return index % 2 === 0;
})
console.log(x)
// [1, 3, 5, 7, 9]
If you just want this with lineLength and not with key, then add a second variable and use += when incrementing:
function pushToHash(key, value) {
for (var t = 0, x = 0; t < value.length; t++, x += 2) {
MQHash[key[t]] = value.slice(0, lineLength[x]);
}
}
(The power of the comma operator...)
How about for (var i = 1; i < array.length; i += 2)
Here is a function that will truncate an array every X elements (factor).
const truncateArray = (array: any[], factor: number): any[] => {
let lastNumber = 0;
return array.filter((element, index) => {
const shouldIncludeThisElement = index === lastNumber + factor ? true : false;
lastNumber = shouldIncludeThisElement ? index : lastNumber;
return shouldIncludeThisElement;
});
};

Categories

Resources