JavaScript: How to get two elements in a array to equal any given number - javascript

My question is:
If I have a array like this,
example:
var myArray = [1,2,4,6,9]
and I want to get the number 15 by getting (adding) the index of 6 and 9.
How do I do that?
I can't make it work and I have tried endlessly... please help.
My attempt:
var list = [1,3,5,7,9];
function sumOfIndex(list , weight) {
weight = [];
for (i = 0; i < list.length; i++) {
for (j = 0; j < list[i].length; j++) {
list.push(weight);
}
}
}

In the array from your example, the index of 6 is [3] and the index of 9 is [4].
Simply add them together and you have 15.
Run the snippet below:
var myArray = [1,2,4,6,9]
console.log(myArray[3] + myArray[4])

I'd go over the array and create a map from the complement of each element to its index:
function findSum (arr, sum) {
const diffs = new Map();
for (let i = 0; i < arr.length; ++i) {
if (diffs.has(arr[i])) {
return [diffs.get(arr[i]), i];
}
diffs.set(sum - arr[i], i);
}
}

Related

find possible pair from array of string on this particular case

I want to generate possible pairs from string array
this is what I got now:
const findPossiblePair = (array) => {
const results = [];
for (let i = 0; i < array.length - 1; i++) {
for (let j = i + 1; j < array.length; j++) {
results.push(`${array[i]}-${array[j]}`);
}
}
return results;
};
const result = findPossiblePair(['michael', 'john', 'annie'])
console.log(result)
currently it generates: ["michael-john", "michael-annie", "john-annie"]
I want it to be: ["michael-john", "john-michael", "michael-annie", "annie-michael"]
notice michael becomes some sort of "anchor" because it's there in all of the elements
e.g.
if the anchor is "annie", it generates: ["annie-michael", "michael-annie", "annie-john", "john-annie"]
I believe I need to add a parameter on the function for the anchor
but I'm in complete stuck
please help me
I would use Array.reduce to iterate the names instead and just push the pairs to the result array when the name being iterated is not the anchor:
const findPossiblePair = (array, anchor) =>
array.reduce((acc, name) => {
if (name != anchor) {
acc.push(`${anchor}-${name}`);
acc.push(`${name}-${anchor}`);
}
return acc;
}, [])
const result = findPossiblePair(['michael', 'john', 'annie'], 'annie')
console.log(result)
#nick solution is great. but just for info , you can add one more line in your existing code.
for (let i = 0; i < array.length - 1; i++) {
for (let j = i + 1; j < array.length; j++) {
results.push(`${array[i]}-${array[j]}`);
results.push(`${array[j]}-${array[i]}`); // add this line
// [...results,`${array[i]}-${array[j]}`,`${array[j]}-${array[i]}`] //or replace with this
}
}

Probleme with empty items in 2d array

I'm trying to build 2d array with JS.
In a theater there is 26 lines, each one include 100 seats :
function theaterSeats() {
let seats= new Array(26);
for (let i = 1; i <= 26; i++){
seats[i] = new Array(100);
for (let j = 1; j <= 100; j++) {
seats[i][j] = `${i}-${j}`
}
}
return seats;
}
console.log(theaterSeats());
The result is not far from what I expected, except that there is an empty item in each array... I don't understand why. Some help please ?
[
<1 empty item>,
[
<1 empty item>, '1-1', '1-2', '1-3',
'1-4', '1-5', '1-6', '1-7',
'1-8', '1-9', '1-10', '1-11'
(...................)
Thanks in advance for your answer ;).
JavaScript arrays' index start from 0 that's why your first item is always empty because you have skipped index 0 and started your iteration from index 1. You need to fill your array starting from index 0!
The correct version of your code could be:
function theaterSeats() {
let seats= new Array(26);
for (let i = 0; i < 26; i++){
seats[i] = new Array(100);
for (let j = 0; j < 100; j++) {
seats[i][j] = `${i + 1}-${j + 1}`
}
}
return seats;
}
Simple map solution
const theaterSeats = [...Array(26)].map((_, i) => {
return [...Array(100)].map((_, j) => `${i+1}-${j+1}`)
})
console.log(theaterSeats)
It's just because you're using 1 as the 1st index instead of 0, array index starts in 0, something like:
An array of 7 elements have those indexes: 0,1,2,3,4,5,6. So when setting a value to a position you'll begin like: array[0] = 'some value', array[1] = 'some other value' ...
Here in your for loop you'll need to begin with i and j = 0. So it'll look like
function theaterSeats() {
let seats= new Array(26);
for (let i = 0; i <= 26; i++){
seats[i] = new Array(100);
for (let j = 0; j <= 100; j++) {
seats[i][j] = `${i+1}-${j+1}`
}
}
return seats;
}
console.log(theaterSeats());
Thanks for your reply ;).
I found the solution before checking your answer. I did that and it's working :
function theaterSieges() {
let siege = new Array(26);
for (let i = 0; i < 26; i++){
siege[i] = new Array(100);
for (let j = 0; j < 100; j++) {
siege[i][j] = `${i+1}-${j+1}`
}
}
return siege;
}
console.log(theaterSieges());
I will keep in mind your tips.
Thanks again ;)

find all numbers disappeared in array

Please help me to solve this leetcode problem using javascript as I am a beginner and dont know why this code is not working
Ques: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
var findDisappearedNumbers = function (nums) {
var numLength = nums.length;
nums.sort(function (a, b) { return a - b });
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
}
}
for (var k = 0; k < nums.length; k++) {
for (var j = 1; j <= numLength; j++) {
if (nums[k] !== j) {
return j;
}
}
}
};
if there is any error in my code please let me know;
i have done the following thing
first i have sorted the array in ascending order
then i have cut all the duplicate elements
then i have created loop that will check if nums[k] !== j ;
and it will return j which is the missing number;
for example this is the testcase [4,3,2,7,8,2,3,1]
first my code will sort this in ascending order [1,2,2,3,3,4,7,8]
then it will remove all duplicate elements and it will return [1,2,3,4,,7,8]
and then it will check nums[k] is not equal to j and it will print j
I think it'd be easier to create a Set of numbers from 1 to n, then just iterate through the array and delete every found item from the set:
var findDisappearedNumbers = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(i + 1);
}
for (const num of nums) {
set.delete(num);
}
return [...set];
};
console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]));
To fix your existing code, I'm not sure what the logic you're trying to implement in the lower section, but you can iterate from 1 to numLength (in the outer loop, not the inner loop) and check to see if the given number is anywhere in the array. Also, since you're mutating the array with splice while iterating over it in the upper loop, make sure to subtract one from i at the same time so you don't skip an element.
var findDisappearedNumbers = function(nums) {
var numLength = nums.length;
nums.sort(function(a, b) {
return a - b
});
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
i--;
}
}
const notFound = [];
outer:
for (var j = 1; j < numLength; j++) {
for (var k = 0; k < nums.length; k++) {
if (nums[k] === j) {
continue outer;
}
}
notFound.push(j);
}
return notFound;
};
console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]));
#CertainPerformance certainly cracked it again using the modern Set class. Here is a slighly more conservative approach using an old fashioned object:
console.log(missingIn([4,3,2,7,8,2,3,1]));
function missingIn(arr){
const o={};
arr.forEach((n,i)=>o[i+1]=1 );
arr.forEach((n) =>delete o[n] );
return Object.keys(o).map(v=>+v);
}
My solution for the problem to find the missing element
var findDisappearedNumbers = function(nums) {
const map={};
const result=[];
for(let a=0;a<nums.length;a++){
map[nums[a]]=a;
}
for(let b=0;b<nums.length;b++){
if(map[b+1]===undefined){
result.push(b+1)
}
}
return result;
};
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]

js how to make 2d array matrix with for loop and continue counting numbers on next row

I'm trying to make my 2d matrix to have numbers which continue on the new row
var myMatrix = [];
var row = 5;
var colom = 3;
for (var i = 0; i < rows; i++) {
var toto = 1;
myMatrix[i] = [i];
for (var j = 0; j < colom; j++) {
myMatrix[i][j] = [i + j];
}
}
console.log(myMatrix);
I'm trying to make it print numbers like this:
123
456
789 and etc...
but without success:/
can someone help and also give a video or site with examples where i can learn more about that kind of stuff?
First, a look at what your code is doing:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [i];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = [i+j];
}
}
console.log(myMatrix);
You have a typo in your row/rows variable name. Ignoring that though...
Your myMatrix[i] line is creating an array at i, which is then being set to an array with a value of i. Just this creates a wonky mash-up , where each "row" gets an array with it's row number as the first value, something like this:
[[0], [1], [2], [3], [4]]
Your inner loop then adds a value to that array at the place and adds i+j together, but puts that inside of an array, which isn't what you want, so you get something like this:
[
[[0], [1], [2]], // i = 0
[[1], [2], [3]], // i = 1
[[2], [3], [4]], // i = 2
// ... etc
]
Also note that you are replacing that first [i] anyways, so don't set it like that, just make it an empty array [].
What you want is something like this:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j;
}
}
console.log(myMatrix);
There were three changes to your code:
Make the [i] and []. It doesn't hurt anything, but [i] also doesn't make sense.
Take the i+j part out of the array, you just want a value there.
When you add i, multiply it by columns so it doesn't reset every time: (i*columns)+j
This will give you a nice output, starting with 0. If you want it start at 1, just add one to your value:
const myMatrix = [];
const rows = 5;
const columns = 3;
for (var i = 0; i < rows; i++) {
myMatrix[i] = [];
for (var j = 0; j < columns; j++) {
myMatrix[i][j] = (i*columns)+j+1;
}
}
console.log(myMatrix);
Use i * columns + j ... and I have to add up to 30 chars for padding

Filling a 2D array with 0s in JavaScript

I've been trying to fill up a 2D array with JavaScript and I keep crashing my browser so I assume I have infinite recursion but I can't seem to find my error. Here's my code:
//The two sequences to compare
var sequence1 = "ATTGCTGACTTCA"
var sequence2 = "ATGCTACTA"
//Creates multi-dimensional array dependent on sequence lengths
var arr = new Array(sequence1.length + 1)
for (i = 0; i < sequence1.length + 1; i++) {
arr[i] = new Array(sequence2.length + 1);
}
//Fills array with 0s
for (i = 0; i < arr.length; i++) {
var col = i;
for (i = 0; i < arr[col].length; i++) {
arr[col][i] = 0;
}
}
When you filling your array, you change the value of i by inner loop, and did not change it back to it's original value after the inner loop! Dont use the same variable name in outer and inner loops!
for (i = 0; i < arr.length; i++) {
var col = i;
for (i = 0; i < arr[col].length; i++) {
arr[col][i] = 0;
}
i = col;
}
what you realy should do:
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
arr[i][j] = 0;
}
}
You can use Array#from, Array#map and Array#fill.
var arr = Array.from({
length: sequence1.length + 1
}).map(() => Array.from({
length: sequence2.length + 1
}).fill(0));
var sequence1 = "ATTGCTGACTTCA",
sequence2 = "ATGCTACTA";
//Creates multi-dimensional array dependent on sequence lengths
var arr = Array.from({
length: sequence1.length + 1
}).map(() => Array.from({
length: sequence2.length + 1
}).fill(0));
console.log(arr);
Explanation:
var arr = Array.from({
length: sequence1.length + 1
})
// Create an array of passed `length` of `undefined` elements
// map will iterate over all the elements of the array and update the value of each element
// Create new array and use this as the individual item in the main array
.map(() => Array.from({
length: sequence2.length + 1
}).fill(0));

Categories