How do i rewriting a function code javascript - javascript

A function that returns a new array that contains the product of each pair of numbers from the arguments that have the same index.
var a = [3, 5, 7];
var b = [9, 10, 11];
a.map(function(x, index) { //here x = a[index] //how do i write this as function name(){}
console.log(b[index] * x);
});

var a = [3, 5, 7];
var b = [9, 10, 11];
let c = [];
function name(a, b) {
a.map(function(x, index) {
let result = b[index] * x;
c.push(result);
}
}
name(a, b);
console.log(c) // this will show a new array with the results

this way
var a = [3, 5, 7];
var b = [9, 10, 11];
function myFunction(x,index)
{
return (b[index] * x);
}
var c = a.map(myFunction);
console.log( c )

You need to return the new value from the map callback.
var a = [3, 5, 7];
var b = [9, 10, 11];
const res = a.map((x,index)=>b[index] * x);
console.log(res);

The specs of .map() say that:
The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.
var a = [3, 5, 7];
var b = [9, 10, 11];
function name(value_of_array_a, index_of_array_b) {
return b[index_of_array_b] * value_of_array_a;
}
var result = a.map(name);
console.log(result);

Related

JS Function restrict type of arguments

Let's say i have a range() function that returns an array of numbers in a range, how can i make sure that this function only accepts numbers as arguments?. Is it correct to throw an error like new Error('input must be a number')?. Thanks in advance.
function range(from, to, step = 1) {
if (!to) {
to = from;
from = 0;
}
let result = []
for (let i = from; i < to; i += step) {
result.push(i)
}
return result
}
const rango1 = range(5); // [0, 1, 2, 3, 4]
const rango2 = range(2, 8); // [2, 3, 4, 5, 6, 7]
const rango3 = range(3, 12, 2); //[3, 5, 7, 9, 11]
console.log(rango1)
console.log(rango2)
console.log(rango3)
console.log(range('string')) // throw Error instead []

How to distribute a number to an array as evenly as possible?

I'm trying to distribute a number to an array.
For example,
const num = 30;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);
The result should be [10, 10, 10]
Another example,
const num = 32;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);
The result should be [8, 8, 8, 8]
Last example,
const num = 34;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);
The result should be [9, 9, 8, 8]
And here's my code that works only until 98. If it reaches 99, it no longer works and I don't know why.
const num = 99;
const maxNumPerElement = 10;
if (num > maxNumPerElement) {
const numSubtitles = Math.ceil(num / maxNumPerElement);
const minNumPerElement = Math.floor(num / numSubtitles);
const numArray = new Array(numSubtitles).fill(minNumPerElement);
const remainder = num % minNumPerElement;
for (let i = 0; i < remainder; i++) {
numArray[i]++;
}
const sum = numArray.reduce(function (a, b) {
return a + b;
}, 0);
if (sum !== num) {
console.log("ERROR!!", num, numArray);
}
else {
console.log(num, numArray);
}
}
Result: ERROR!! 99 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
It seemed easy but I can't solve it. Is there an easy way to solve this?
probably you're looking for something like this:
function getDistributedArray(n, max) {
var a = [];
var r = n; // rest of total sum
var c = Math.ceil(n / max); // get maximal number of elements in array
var i = 0; // index
while (r > 0) {
var t = Math.ceil(r / c); // get max number from the rest
a[i++] = t;
r -= t;
c--;
}
return a;
}
console.log(getDistributedArray(30, 10)); // [10, 10, 10]
console.log(getDistributedArray(32, 10)); // [8, 8, 8, 8]
console.log(getDistributedArray(34, 10)); // [9, 9, 8, 8]
console.log(getDistributedArray(99, 10)); // [10, 10,..., 9]

Algorithm for rotating image represented by array not working as expected

I am trying to rotate the image (a) by making the values at "a" coordinates map to the rotated image according to the coordinates listed below. Why does this not work?
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
// Desired result:
// rotateImage(a) =
// [[7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]]
// aCoords = [[00,01,02],
// [10, 11, 12],
// [20,21,22]]
// rotatedImageCoordsRelatingToa = [[20, 10, 00],
// [21, 11, 01],
// [22,12,02]]
function rotateImage(a) {
const image = [...a]
const length = a.length
const rotatedImage = [...a]
for(let i=0;i<length;i++){
for(let j=0;j<length;j++){
let toRotateCoord = length-(1+j)
console.log("Original coordinates:" + i,j + " should map to rotated coordinates:"+ toRotateCoord, i)
rotatedImage[i][j] = image[toRotateCoord][i]
}
}
return rotatedImage;
}
rotateImage(a);
When I run this I get
//[[7,4,7],
// [8,5,4],
// [9,4,7]]
// Not
// [[7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]]
I know there is probably a better algorithm for this but I am curious why this approach is not working. It seems to be something with how the arrays are being accessed.
As Cris Luengo mentioned, it appears that using the spread operator to assign rotatedImage still points to the same location in memory. I added a for loop to create the new array and now it works:
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
rotateImage(a);
function rotateImage(a) {
const image = [...a]
const length = a.length
const rotatedImage = []
for(var i = 0; i < length; i++){
rotatedImage.push([]);
};
for(let i=0;i<length;i++){
for(let j=0;j<length;j++){
let toRotateCoord = length-(1+j)
rotatedImage[i][j] = image[toRotateCoord][i]
}
}
return rotatedImage;
}
The problem is that although rotatedImage = [...a] creates a new array, it does not create new subarrays. So, rotatedImage shares its rows with image. Whatever you assign to rotatedImage[i][j] will mutate the rows in image, affecting the result of some of the next assignments.
To avoid this, initialise rotatedImage as:
const rotatedImage = Array.from({length}, _ => []);
... and your code will work.
BTW: you don't need the image variable. Since you don't intend to mutate it, you can just use a.
function rotateImage(a) {
const length = a.length;
const rotatedImage = Array.from({length}, _ => []);
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
rotatedImage[i][j] = a[length - (1 + j)][i];
}
}
return rotatedImage;
}
let a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
let b = rotateImage(a);
for (let row of b) console.log(row+"")

Merge arrays and toggle

I have two arrays of ids:
let a = [1, 7, 8];
let b = [1, 7, 99];
I want to merge they and toggle off the common values. The result must be as follow:
let res = [8, 99];
Each array (a or b) can't have duplicates. So next is impossible
let a = [1, 1, 7, 8];
let b = [1, 7, 7, 99, 7];
How can I merge and toggle? I can merge this way without duplicates, but it is not I want.
[...new Set([...a, ...b])]; // [1, 7, 8, 99]
Using Array#filter on both with spread operator.
let a = [1, 7, 8];
let b = [1, 7, 99];
const res = [...a.filter(item=>!b.includes(item)), ...b.filter(item=>!a.includes(item))];
console.log(res);
To avoid a O(n²) time complexity, make a set for one of both arrays
const a = [1, 7, 8];
const b = [1, 7, 99];
const setA = new Set(a);
const res = [...b.filter(item => !setA.delete(item)), ...setA];
console.log(res);
You could take a single set and reduce the second array.
let a = [1, 7, 8],
b = [1, 7, 99],
result = [...b.reduce((s, v) => s.has(v) ? (s.delete(v), s) : s.add(v), new Set(a))];
console.log(result);
Here is another approach by using a for-loop
const a = [1, 7, 8];
const b = [1, 7, 99];
const arr = a.concat(b).sort((a, b) => a - b);
const result = [];
let currentId;
for (const id of arr) {
if (currentId === id) {
result.pop();
} else {
currentId = id;
result.push(id);
}
}
console.log(result);
So, what you want is to calculate the union of the two arrays minus the intersection of they. Skipping the performance, I will do this step by step:
let a = [1, 7, 8];
let b = [1, 7, 99];
// Calculate the union.
let union = new Set([...a, ...b]);
// Calculate the intersection.
let intersection = new Set(a.filter(x => b.includes(x)));
// Calculate union minus intersection.
let res = [...union].filter(x => !intersection.has(x));
console.log(res);
Or in a simplified way (not so readable like the previous one):
let a = [1, 7, 8];
let b = [1, 7, 99];
// Calculate union minus intersection.
let res = [...a, ...b].filter(x => !(a.filter(y => b.includes(y))).includes(x));
console.log(res);
Even more simplified and readable would be one of the next options:
let a = [1, 7, 8];
let b = [1, 7, 99];
// Calculate union minus intersection.
let res1 = [...a, ...b].filter(x => !(a.includes(x) && b.includes(x)));
console.log(res1);
// Or using Morgan’s Law:
let res2 = [...a, ...b].filter(x => !a.includes(x) || !b.includes(x));
console.log(res2);

how to find longest common subarray

here is my problem: I have 5 arrays of integer like these in javascript:
array1 = [0, 1, 2, 3, 4];
array2 = [9, 1, 2, 3, 4];
array3 = [10, 1, 2, 11, 4];
array4 = [12, 1, 2, 13, 4];
array5 = [14, 1, 2, 15, 4];
I have to find the longest common subarray. In this case I have to retrieve the following subarray: [1, 2, 4].
For the records, I won't find repetitions inside arrays and my main goal is not execution speed.
thanks
here is the solution using Set in Javascript
var myArray = [array1 , array2 ,array3 , array4 ,array5];
let keys = new Set();
myArray.forEach(arr => arr.forEach(el => keys.add(el) ))
var common = [...keys].filter(key => myArray.every(arr => arr.includes(key)))
console.log(common);
#define MAX(a,b) a>b?a:b
int main(int argc, char* argv[])
{
if(argc < 2)
return -1;
int x = strlen(argv[1])+1;
int y = strlen(argv[2])+1;
int i,j,k,l;
int longest =0;
char* LCS = (char*)malloc(sizeof(char)*MAX(x,y));
int** arr = (int**)malloc(sizeof(int*)*x);
for(i=0;i<=y;i++)
arr[i] =(int*) malloc(sizeof(int)*y);
for(i=0;i<=x;i++)
for(j=0;j<=y;j++)
{
arr[i][j] = 0;
}
for(i=0;i<x;i++)
for(j=0;j<y;j++)
{
if(argv[1][i] == argv[2][j])
arr[i+1][j+1] = arr[i][j]+1;
if(arr[i+1][j+1] > longest)
{
longest =arr[i+1][j+1];
memset(LCS,0,MAX(x,y));
for( k=0,l=i;k<=longest;k++,l--)
LCS[k] = argv[1][l];
}
}
printf(" %s",argv[2]);
for(i=0;i<x;i++)
{
printf("\n%c",argv[1][i]);
for(j=0;j<y;j++)
{
printf("%d",arr[i][j]);
}
}
printf("\nLongest Common Subarray : %s\n",LCS);
return 0;
}
Try this:
var array1 = [0, 1, 2, 3, 4];
var array2 = [9, 1, 2, 3, 4];
var array3 = [10, 1, 2, 11, 4];
var array4 = [12, 1, 2, 13, 4];
var array5 = [14, 1, 2, 15, 4];
// join everything into one array
var all = array1.join(',')+','+array2.join(',')+','+array3.join(',')+','+array4.join(',')+','+array5.join(',');
all = all.split(',');
// get an object with all unique numbers as keys
var keys = {};
for(var i=0; i<all.length; i++) keys[all[i]] = 1;
console.log(keys);
// generate an array with values present in all arrays
var common = [];
for(var x in keys) {
if(array1.indexOf(parseInt(x)) != -1 && array2.indexOf(parseInt(x)) != -1 && array3.indexOf(parseInt(x)) != -1 && array4.indexOf(parseInt(x)) != -1 && array5.indexOf(parseInt(x)) != -1) {
common.push(x);
}
}
console.log(common);
I guess this can give you a good start:
My script will return you an object with the count of each elements. But for now, it takes the first array as base.
var array1 = [0, 1, 2, 3, 4];
var array2 = [9, 1, 2, 3, 4];
var array3 = [10, 1, 2, 11, 4];
var array4 = [12, 1, 2, 13, 4];
var array5 = [14, 1, 2, 15, 4];
var array6 = [13, 1, 2, 18, 4];
var mainArr = [array1, array2, array3, array4, array5, array6]
function getCommonElement(arr){
var subLength = arr[0].length;
var resultArr = new Array();
var ret = new Object();
for(var k=0;k<subLength;k++){
var temp = new Array();
for(var i=0;i<arr.length;i++){
temp.push(arr[i][k]);
}
resultArr.push(temp);
}
for(var i=0;i<arr[0].length;i++){
ret[arr[0][i]+''] = resultArr[i].join('').split(arr[0][i]+'').length - 1;
}
return ret;
}
Cheers.
/**
longest common subarray b/w 2 arrays
a = [2,3,4,5,6,7,8], b = [6,7,8,4,5,2,3]
ans = 6,7,8
basically create a 2d arr and if elements match dp[i][j] = 1 + dp[i-1][j-1];
if dp[i][j] > maxLen, update maxLen and store the index
Now that we have the maxLen, subarray will be from (index - maxLen) till index.
*/
int[] finMaxCommon(int[] a, int[] b){
int m = a.length, n = b.length, maxLen = 0;
int[][] dp = new int[m+1][n+1];
// i want a 0th row why? m->out of bounds; comparing i-1; i->1 then i-1 will be 0
for (int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
if(a[i-1] == b[j-1]) {
dp[i][j] = 1 + dp[i-1][j-1];
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
// endIndex = 6, 3, a[6-3+1], a[6]
return new int[]{a[endIndex-maxLen+1], [endIndex]};
}
dry run
0,6,7,8,4,5,2,3
0, 0 //
2, 1 // (2,2) i = 1, j = 6 1 + dp[0][5]
3, 2 // (3,3) i = 2, j = 7 1 + dp[1][6]
4,
5,
6, 1
7, 2
8, 3

Categories