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

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

Related

Checking which element is bigger when merging two arrays?

I have two arrays that are the same length, for example var a = [5,2,6,2,7,5]; and var b = [2,3,7,4,3];.
I also have another array which is var c = [0,0,0,0,0];
How do I compare a and b to put the highest element into c which in this case should become [5,3,7,7,5];
ES6 single-line solution:
c = a.map((a, i) => a > b[i] ? a : b[i])
Array#map into a new array, and take the max of the current number from a, and the number with the same index from array b:
const a = [5, 2, 6, 2, 7];
const b = [2, 3, 7, 4, 3];
const c = a.map((num, i) => Math.max(num, b[i]));
console.log(c);
You would iterate through both arrays, doing the comparison at each step, and inserting the larger number:
Note: Even though you mention that you have equal length arrays, the two sample arrays you've given don't have the same length so my example uses similar equal-length arrays:
let a = [5, 2, 6, 2, 7]
let b = [2, 3, 7, 4, 3]
let c = [0, 0, 0, 0, 0]
// we can use a single loop index `i` since the arrays have same length
for (let i = 0; i < a.length; i++) {
// take the current number from a and from b
let numA = a[i]
let numB = b[i]
// determine larger of the two numbers
let largerNumber = numA > numB ? numA : numB
// add larger to array at current position
c[i] = largerNumber
}
console.log(c)
You can simplify your solution to be a simple map operation, as demonstrated by dhilt.
Just use a simple for loop:
var a = [2, 3, 7, 8];
var b = [3, 2, 5, 9];
var c = [0, 0, 0, 0];
for (var i = 0; i < c.length; i++) {
c[i] = a[i] > b[i] ? a[i] : b[i];
}
console.log("Result: "+c);
try this, below code takes two arrays and gives the result of max number
var array=[5,3,7,7,5];
var array2 = [5,6,4];
var array3=array.concat(array2);
var max=array3.sort((a,b)=>b-a)[0];
console.log("Result: " + max);
see example:
var a = [5,2,6,2,7,5];
var b = [2,3,7,4,3];
var c = [0,0,0,0,0];
for(var i in c){
c[i]=a[i]>b[i]?a[i]:b[i];
}
console.log('result:' + c);

Count number of values in array between two input values

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

Split Array of items into N Arrays

I want to split an Array of numbers into N groups, which must be ordered from larger to smaller groups.
For example, in the below code, split an Array of 12 numbers into 5 Arrays, and the result should be evenly split, from large (group) to small:
source: [1,2,3,4,5,6,7,8,9,10,11,12]
⬇
output: [1,2,3] [4,5,6] [7,8] [9,10] [11,12]
Playground
// set up known variables
var arr = [1,2,3,4,5,6,7,8,9,10,11,12],
numberOfGroups = 5,
groups = [];
// split array into groups of arrays
for(i=0; i<arr.length; i++) {
var groupIdx = Math.floor( i/(arr.length/numberOfGroups) );
// if group array isn't defined, create it
if( !groups[groupIdx] )
groups[groupIdx] = [];
// add arr value to group
groups[groupIdx].push( arr[i] )
}
// Print result
console.log( "data: ", arr );
console.log( "groups: ", groups )
Update:
Thanks to SimpleJ's answer, I could finish my work.
The use case for this is an algorithm which splits HTML lists into "chunked" lists, a think which cannot be easily achieved by using CSS Columns.
Demo page
I'm not 100% sure how this should work on different sized arrays with different group counts, but this works for your 12 digit example:
function chunkArray(arr, chunkCount) {
const chunks = [];
while(arr.length) {
const chunkSize = Math.ceil(arr.length / chunkCount--);
const chunk = arr.slice(0, chunkSize);
chunks.push(chunk);
arr = arr.slice(chunkSize);
}
return chunks;
}
var arr = [1,2,3,4,5,6,7,8,9,10,11,12];
console.log( chunkArray(arr, 5) )
A shorter version of #SimpleJ answer and without using slice two times.
function splitArrayEvenly(array, n) {
array = array.slice();
let result = [];
while (array.length) {
result.push(array.splice(0, Math.ceil(array.length / n--)));
}
return result;
}
console.log(splitArrayEvenly([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))
I think this is a more of a mathematical problem than a Javascript.
const getGroups = (arr, noOfGroups) => {
const division = Math.floor(arr.length / numberOfGroups);
const groups = [[]];
let remainder = arr.length % numberOfGroups;
let arrIndex = 0;
for (let i = 0; i < noOfGroups; i++) {
for (let j = division + (!!remainder * 1); j >= 0; j--) {
groups[i].push(arr[arrIndex]);
arrIndex += 1;
}
remainder -= 1;
}
return groups;
};
const myGroups = getGroups([1,2,3,4,5,6,7,8,9,10,11,12], 5);
myGroups will be [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10], [11, 12]]
This will work for any number of groups and players

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

Categories

Resources