I know that an array is essentially an object with the indexes as the keys, and the elements as the values, so I'm trying to reverse engineer an array with some methods as practice and learn since I'm new to JS and coding in general. I was able to recreate the following methods: push, pop, unshift, shift. Now my question is, is it possible to make it so that when I console log the object, it looks like an array rather than an object? I can't seem to figure it out without using an actual array and the push method. I would appreciate it if I could be led in the direction of the answer or given hints/things to look up and learn rather than a code answer. Also, any suggestion to improve the code I already written would be much appreciated. Thank you in advance!
Here's the object I created:
function createArray() {
let index = -1;
const obj = {
push: (...element) => {
for (let i = 0; i < element.length; i++) {
index++;
obj[index] = element[i];
}
},
pop: () => {
let current = obj[index];
delete obj[index];
index--;
return current;
},
shift: () => {
let current = obj[0];
for (let i = 0; i < index; i++) {
obj[i] = obj[i + 1];
}
delete obj[index];
index--;
return current;
},
unshift: (...element) => {
index += element.length;
for (let i = index; i >= 0; i--) {
if (i >= element.length) obj[i] = obj[i - element.length];
else obj[i] = element[i];
}
return index;
}
}
return obj;
};
//test:
const array = createArray();
array.push(4, 5, 6, 7);
array.unshift(0, 1, 2, 3);
array.shift();
array.pop();
console.log(array);
how about using class ?
class newArray {
length = -1;
array = {};
constructor(){
}
push(...element) {
for (let i = 0; i < element.length; i++) {
this.length++;
this.array[this.length] = element[i];
}
}
pop() {
let current = this.array[this.length];
delete this.array[this.length];
this.length--;
return current;
}
shift() {
let current = this.array[0];
for (let i = 0; i < this.length; i++) {
this.array[i] = this.array[i + 1];
}
delete this.array[this.length];
this.length--;
return current;
}
unshift(...element) {
this.length += element.length;
for (let i = this.length; i >= 0; i--) {
if (i >= element.length) this.array[i] = this.array[i - element.length];
else this.array[i] = element[i];
}
return this.length;
}
}
const array = new newArray();
array.push(4, 5, 6, 7);
array.unshift(0, 1, 2, 3);
array.shift();
array.pop();
console.log(array);
In the example below shows a literal object converted into an array of pairs:
{prop: 'A'} => [ ['prop', 'A'] ]
If you want to display something on the console in a practical way, use JSON.stringify()
console.log(JSON.stringify(x));
Note in the example, there's a simple function that makes this process easier:
const log = data => JSON.stringify(data);
// Usage: log(data);
const literalObject = {
propA: "String",
propB: 23,
propC: [1, 'A', true],
propD: {
propE: 'B',
propF: 5
}
};
const arrayOfPairs = Object.entries(literalObject);
const log = data => console.log(JSON.stringify(data));
log(arrayOfPairs);
To meet with the OP's expectation that the console.log needs to show only the elements of the array, a new display prop may be used as shown below:
function createArray() {
let index = -1;
const obj = {
push: (...element) => {
for (let i = 0; i < element.length; i++) {
index++;
obj[index] = element[i];
}
},
pop: () => {
let current = obj[index];
delete obj[index];
index--;
return current;
},
shift: () => {
let current = obj[0];
for (let i = 0; i < index; i++) {
obj[i] = obj[i + 1];
}
delete obj[index];
index--;
return current;
},
unshift: (...element) => {
index += element.length;
for (let i = index; i >= 0; i--) {
if (i >= element.length) obj[i] = obj[i - element.length];
else obj[i] = element[i];
}
return index;
},
display: () => {
let result = [];
for (let i = 0; i <= index; i++) result.push(obj[i]);
return result;
// OR - if you like to avoid using 'result', try this:
// return Object.values(obj).filter((o, i) => i < index);
}
}
return obj;
};
//test:
const array = createArray();
array.push(4, 5, 6, 7);
array.unshift(0, 1, 2, 3);
array.shift();
array.pop();
console.log(array.display());
Rather than holding the actual array-data in the same obj that is being used to hold the methods, it may be better to use a dedicated variable within the closure to hold the elements.
function createArray() {
let index = -1;
let itemsObj = {}; // new variable to hold the elements
const obj = {
push: (...element) => {
for (let i = 0; i < element.length; i++) {
index++;
itemsObj[index] = element[i];
}
},
pop: () => {
let current = itemsObj[index];
delete itemsObj[index];
index--;
return current;
},
shift: () => {
let current = itemsObj[0];
for (let i = 0; i < index; i++) {
itemsObj[i] = itemsObj[i + 1];
}
delete itemsObj[index];
index--;
return current;
},
unshift: (...element) => {
index += element.length;
for (let i = index; i >= 0; i--) {
if (i >= element.length) itemsObj[i] = itemsObj[i - element.length];
else itemsObj[i] = element[i];
}
return index;
},
// new method 'display' to get the elements to be shown like an array
display: () => (Object.values(itemsObj))
}
return obj;
};
//test:
const array = createArray();
array.push(4, 5, 6, 7);
array.unshift(0, 1, 2, 3);
array.shift();
array.pop();
console.log(array.display());
Reference:
The above snippets use JavaScript closure
How something is printed on the console is entirely up to the console.
The closest thing you can get is to override toString and leverage string concatenation:
...
toString: () => "[your representation here]"
...
console.log("My array: " + array);
That prints My array: [your representation here]
How does it work? When you concatenate (+) a string with an object then the toString method of that object is called.
Related
I have this problem:
Given an array of integers nums and an integer target, return the indices of two numbers that add up to target.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
With the code below was able to get the values added in array using set and Map
What I need help is to return the indices
const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];
valueArray.forEach((v1, i1) => {
for (let i2 = i1 + 1; i2 < valueArray.length; i2++) {
if ((v1 + valueArray[i2]) === k) {
// Return the indices
return valueArray[i2];
}
}
});
You have to parse and find the combination of indexes which gives you the sum.
Below code will help you
const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];
let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1++) {
for (let i2 = i1 + 1; i2 < valueArray.length && !isFound; i2++) {
if ((valueArray[i1] + valueArray[i2]) === k) {
//Return the Indices
indices = [i1, i2];
isFound = true;;
}
}
}
console.log(indices);
The answer provided by Nitheesh works well. As for an explanation as to why your initial approach was not successful:
Using forEach to iterate over an array is different than using traditional for loops, in that the callback function is called for every element on the array. Using return in a forEach loop just breaks out of that particular element's callback, but not the entire iteration (hence, a return in a forEach loop behaves similarly to a continue in a for (...) loop.
You can read more about it here.
First you need to get the array with the values from your array with keys [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];. Then you loop the value array and return the index if the condition (nums[i] + nums[j] == target) => (7 + 2 == 9) is true.
const arr = [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
const k = 9;
nums = arr.map((o) => {
return Object.values(o)[0]
})
const twoSum = (nums, target) => {
for(let i = 0; i < nums.length; i++){
for(let j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return [i, j]
}
}
}
};
console.log(twoSum(nums, k))
Maybe this should do it:
function indice1(target, arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
return (result = [arr[i], arr[j]]);
}
}
}
return result;
}
function indice2(target, arr) {
let result = [];
for (const i of arr) {
for (const j of arr) {
if (i + j === target) {
return (result = [i, j]);
}
}
}
return result;
}
function indice3(target, arr) {
return arr.reduce((acc, curr, i, arr) => {
let result = [...acc, curr];
for (const i of acc) {
if (i + curr === target) {
result = [i, curr];
arr.splice(1);
break;
}
}
return result;
}, []);
}
const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];
valueArray.forEach((v,ind) => {
let ind2 = valueArray.findIndex(iv => iv === k - v)
ind2 > -1 && console.log([ind,ind2])
})
Given
[1,3,1,6,22] ,
it should return
[3,6,22]
So far I have this:
const returnUniques = (array) {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if (array[i] === array[j]) {
}
}
}
}
return array
}
I tried
const returnUniques = (array) {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if (array[i] === array[j]) {
array.splice(i, 1)
}
}
}
}
return array
}
But it just removes duplicate and I could have this by one line with either new Set() or other techniques
So I added
const returnUniques = (array) => {
if (array.length == 1) return array[0]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i !== j) {
if(array[i] === array[j]) {
array.splice(i,1)
array.splice(j-1, 1)
}
}
}
}
return array
}
console.log(returnUniques([1,3,1,6,22]))
because I thought that if I removed array[i] so array[j] would be at index of itself -1.
But this method doesn't work if there is more than twice the same number and if many other reasons..
Maybe this nested loop isn't the best way to go ?
Thanks for helps !
Using a Set and filter to check if first and last index are the same
const returnUniques = (arr) => {
return [...new Set(arr)].filter(n => arr.indexOf(n) === arr.lastIndexOf(n))
}
console.log(returnUniques([1,3,1,6,22]))
Using Array.prototype.reduce, you can get the counts for each item.
And based on that content, you can filter the array items which are appeared only one time.
const input = [ 1, 3, 1, 6, 22 ];
const uniques = (arr) => {
const groupBy = arr.reduce((acc, cur) => {
acc[cur] ? acc[cur] ++ : acc[cur] = 1;
return acc;
}, {});
return Object.entries(groupBy).filter(([key, count]) => count === 1).map(([key, count]) => Number(key));
};
console.log(uniques(input));
You can do something like this.
const removeDuplicates = (arr) => {
const results = [];
for (const v of arr) {
const occurences = arr.filter((x) => x === v);
if (occurences.length === 1) results.push(v);
}
return results;
};
console.log(removeDuplicates([1, 3, 1, 6, 22]));
if the first index is equal to last index of the element then it is unique:
const unique = (array) =>
array.filter((e,idx,arr) => arr.indexOf(e) === arr.lastIndexOf(e))
console.log(unique([1,3,1,6,22]))
Something like this
let arrayData = [1, 3, 1, 6, 22];
let getUniqueValuesFunc = (arrayParam) => {
let unqiueValues = [];
for (let unqiueValue of arrayParam ) {
let compare = arrayParam.filter((x) => x === unqiueValue );
if (compare.length === 1) unqiueValues.push(unqiueValue);
}
return unqiueValues;
};
console.log(getUniqueValuesFunc( arrayData ));
Solution in single loop:
const input = [1, 3, 1, 1, 6, 22];
const returnUniques = (array) => {
let output = [];
let filter = [];
for (let j = 0; j < array.length; j++) {
const index = output.indexOf(array[j])
if (index==-1) {
output.push(array[j])
} else {
filter.push(array[j]);
}
}
output = output.filter((o)=>(filter.indexOf(o)==-1))
return output;
}
console.log(returnUniques(input));
I have tried to implement Quick-Sort in Javascript without any reference to psuedo Code. Is this correct implementation? if not how can i improve on it.
const quickSort = (arr = []) => {
const length = arr.length;
if (length === 0 || length === 1) {
return arr;
}
const pivot = arr[0];
const leftArray = [];
const rightArray = [];
for (let i = 1; i < length; i++) {
if (arr[i] < pivot) {
leftArray.push(arr[i]);
} else {
rightArray.push(arr[i]);
}
}
return [...quickSort(leftArray), pivot, ...quickSort(rightArray)];
};
console.log(quickSort([2, 45, 6, 7, 8, 1]));
I have added code of test case and executed it over 250000 times.
// Function to generate random array.
const generateRandomArray = n =>
Array.from({
length: n
}, () => Math.floor(Math.random() * n));
// Function to check whether array is sorted.
const checkSorted = (arr = []) => {
let sorted = true;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
sorted = false;
break;
}
}
return sorted;
};
// Testing Quick-Sort
const testQuickSort = () => {
for (let i = 1; true; i++) {
const sortedArray = quickSort(generateRandomArray(Date.now() % 100000));
const isSorted = checkSorted(sortedArray);
if (!isSorted) {
console.log("error");
break;
}
console.log("pass", i);
}
};
testQuickSort();
You can try the following Solution
function pivot(arr, start = 0, end = arr.length - 1) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};
// We are assuming the pivot is always the first element
let pivot = arr[start];
let swapIdx = start;
for (let i = start + 1; i <= end; i++) {
if (pivot > arr[i]) {
swapIdx++;
swap(arr, swapIdx, i);
}
}
// Swap the pivot from the start the swapPoint
swap(arr, start, swapIdx);
return swapIdx;
}
function quickSort(arr, left = 0, right = arr.length -1){
if(left < right){
let pivotIndex = pivot(arr, left, right) //3
//left
quickSort(arr,left,pivotIndex-1);
//right
quickSort(arr,pivotIndex+1,right);
}
return arr;
}
console.log(quickSort([100,-3,2,4,6,9,1,2,5,3,23]));
I want to count how often a number in an Array occurs. For example, in Python I can use Collections.Counter to create a dictionary of how frequently an item occurs in a list.
This is as far as I've gotten in JavaScript:
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
/* obj[array[i]] = +=1 */ <= pseudo code
}
How can I create this frequency counter object?
Close but you can't increment undefined so you need to set initial value if it doesn't exist
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
obj[array[i]] = (obj[array[i]] || 0) +1 ;
}
You were almost there. See below code:
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
obj[array[i]] = (obj[array[i]] || 0 ) +1;
}
console.log(obj);
Create an object and check if that specific key exist.If exist then increase it's value by 1
var array = [1, 4, 4, 5, 5, 7];
var obj = {};
for (var i = 0; i < array.length; i++) {
if (obj.hasOwnProperty(array[i])) {
obj[array[i]] += 1;
} else {
obj[array[i]] = 1;
}
}
console.log(obj)
You can use the ? : ternary operator to set initial value as 1 and then increment it on subsequent matches.
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
obj[array[i]] = obj[array[i]]?obj[array[i]]+1:1;
}
console.log(obj);
If the array is always going to be same, and you are going to check frequency of multiple items in the same array without it it being modified, #JohanP's answer is good.
But if you are only going to check frequency of only one item, or the array can change, creating the object is nothing but extra overhead.
In that case, you can do something like this:
const getItemFrequency = function(array, item) {
return array.filter(i => i === item).length;
}
var array = [1,4,4,5,5,7];
console.log(getItemFrequency(array, 4));
Concise logic written as proper function:
function countArrayItemFrequecy(array) {
const length = array.length;
const map = {};
for ( let i = 0; i < length; i++ ) {
let currentItem = array[i];
if (typeof map[currentItem] !== 'undefined' ) {
map[currentItem]++
} else {
map[currentItem] = 1
}
}
return map;
}
You need to make sure to assign default value to your frequency object for the first occurrence of the item. As a shortcut you can use ternary operator
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
obj[array[i]] = obj[array[i]] ? obj[array[i]]++ : 1;
}
which is the same as:
var array = [1,4,4,5,5,7];
var obj = {};
for (var i=0; i < array.length; i++) {
if (obj[array[i]]) {
obj[array[i]]++;
} else {
obj[array[i]] = 1;
}
}
You can use Object.assign: below clones map and then increments/adds the counter. These are pure (no side effects/param reassignment), single-purpose functions.
addToMap does the same thing as { ...map, map[e]: [e]: (map[e] || 0) + 1 }, but that requires babel.
const addToMap = (map, e) => Object.assign({}, map, { [e]: (map[e] || 0) + 1 });
const buildMap = a => a.reduce(addToMap, {});
Using Array.reduce:
arr.reduce(function (acc, item) {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
Example:
var arr = [1,1,2,4,1,4];
var counts = arr.reduce(function (acc, item) {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
console.log(counts);
I am in mid of my JavaScript session. Find this code in my coding exercise. I understand the logic but I didn't get this map[nums[x]] condition.
function twoSum(nums, target_num) {
var map = [];
var indexnum = [];
for (var x = 0; x < nums.length; x++)
{
if (map[nums[x]] != null)
// what they meant by map[nums[x]]
{
index = map[nums[x]];
indexnum[0] = index+1;
indexnum[1] = x+1;
break;
}
else
{
map[target_num - nums[x]] = x;
}
}
return indexnum;
}
console.log(twoSum([10,20,10,40,50,60,70],50));
I am trying to get the Pair of elements from a specified array whose sum equals a specific target number. I have written below code.
function arraypair(array,sum){
for (i = 0;i < array.length;i++) {
var first = array[i];
for (j = i + 1;j < array.length;j++) {
var second = array[j];
if ((first + second) == sum) {
alert('First: ' + first + ' Second ' + second + ' SUM ' + sum);
console.log('First: ' + first + ' Second ' + second);
}
}
}
}
var a = [2, 4, 3, 5, 6, -2, 4, 7, 8, 9];
arraypair(a,7);
Is there any optimized way than above two solutions? Can some one explain the first solution what exactly map[nums[x]] this condition points to?
Using HashMap approach using time complexity approx O(n),below is the following code:
let twoSum = (array, sum) => {
let hashMap = {},
results = []
for (let i = 0; i < array.length; i++){
if (hashMap[array[i]]){
results.push([hashMap[array[i]], array[i]])
}else{
hashMap[sum - array[i]] = array[i];
}
}
return results;
}
console.log(twoSum([10,20,10,40,50,60,70,30],50));
result:
{[10, 40],[20, 30]}
I think the code is self explanatory ,even if you want help to understand it,let me know.I will be happy enough to for its explanation.
Hope it helps..
that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming
In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.
Lets investigate how it works to better understand it:
twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler
In iteration 0:
value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.
So in our map, 40 points to 0.
In iteration 2:
value is 40. I look at map my map to see I previously found a pair for 40.
map[nums[x]] (which is the same as map[40]) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.
Does that make any sense now?
Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)
Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)
function twoSum(arr, S) {
const sum = [];
for(let i = 0; i< arr.length; i++) {
for(let j = i+1; j < arr.length; j++) {
if(S == arr[i] + arr[j]) sum.push([arr[i],arr[j]])
}
}
return sum
}
Brute Force not best way to solve but it works.
Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)
((arr,targetSum) => {
if ((arr && arr.length === 0) || targetSum === undefined) {
return false;
} else {
for (let x = 0; x <=arr.length -1; x++) {
let partnerInPair = targetSum - arr[x];
let start = x+1;
let end = (arr.length) - 2;
while(start <= end) {
let mid = parseInt(((start + end)/2));
if (arr[mid] === partnerInPair) {
console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
break;
} else if(partnerInPair < arr[mid]) {
end = mid - 1;
} else if(partnerInPair > arr[mid]) {
start = mid + 1;
}
}
};
};
})([0,1,2,3,4,5,6,7,8,9], 10)
function twoSum(arr, target) {
let res = [];
let indexes = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (target === arr[i] + arr[j] && !indexes.includes(i) && !indexes.includes(j)) {
res.push([arr[i], arr[j]]);
indexes.push(i);
indexes.push(j);
}
}
}
return res;
}
console.log('Result - ',
twoSum([1,2,3,4,5,6,6,6,6,6,6,6,6,6,7,8,9,10], 12)
);
Brute force.
const findTwoNum = ((arr, value) => {
let result = [];
for(let i= 0; i< arr.length-1; i++) {
if(arr[i] > value) {
continue;
}
if(arr.includes(value-arr[i])) {
result.push(arr[i]);
result.push(value-arr[i]);
break;;
}
}
return result;
});
let arr = [20,10,40,50,60,70,30];
const value = 120;
console.log(findTwoNum(arr, value));
OUTPUT : Array [50, 70]
function twoSum(arr){
let constant = 17;
for(let i=0;i<arr.length-2;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i]+arr[j] === constant){
console.log(arr[i],arr[j]);
}
}
}
}
let myArr = [2, 4, 3, 5, 7, 8, 9];
function getPair(arr, targetNum) {
for (let i = 0; i < arr.length; i++) {
let cNum = arr[i]; //my current number
for (let j = i; j < arr.length; j++) {
if (cNum !== arr[j] && cNum + arr[j] === targetNum) {
let pair = {};
pair.key1 = cNum;
pair.key2 = arr[j];
console.log(pair);
}
}
}
}
getPair(myArr, 7)
let sumArray = (arr,target) => {
let ar = []
arr.forEach((element,index) => {
console.log(index);
arr.forEach((element2, index2) => {
if( (index2 > index) && (element + element2 == target)){
ar.push({element, element2})
}
});
});
return ar
}
console.log(sumArray([8, 7, 2, 5, 3, 1],10))
Use {} hash object for storing and fast lookups.
Use simple for loop so you can return as soon as you find the right combo; array methods like .forEach() have to finish iterating no matter what.
And make sure you handle edges cases like this: twoSum([1,2,3,4], 8)---that should return undefined, but if you don't check for !== i (see below), you would erroneously return [4,4]. Think about why that is...
function twoSum(nums, target) {
const lookup = {};
for (let i = 0; i < nums.length; i++) {
const n = nums[i];
if (lookup[n] === undefined) {//lookup n; seen it before?
lookup[n] = i; //no, so add to dictionary with index as value
}
//seen target - n before? if so, is it different than n?
if (lookup[target - n] !== undefined && lookup[target - n] !== i) {
return [target - n, n];//yep, so we return our answer!
}
}
return undefined;//didn't find anything, so return undefined
}
We can fix this with simple JS object as well.
const twoSum = (arr, num) => {
let obj = {};
let res = [];
arr.map(item => {
let com = num - item;
if (obj[com]) {
res.push([obj[com], item]);
} else {
obj[item] = item;
}
});
return res;
};
console.log(twoSum([2, 3, 2, 5, 4, 9, 6, 8, 8, 7], 10));
// Output: [ [ 4, 6 ], [ 2, 8 ], [ 2, 8 ], [ 3, 7 ] ]
Solution In Java
Solution 1
public static int[] twoNumberSum(int[] array, int targetSum) {
for(int i=0;i<array.length;i++){
int first=array[i];
for(int j=i+1;j<array.length;j++){
int second=array[j];
if(first+second==targetSum){
return new int[]{first,second};
}
}
}
return new int[0];
}
Solution 2
public static int[] twoNumberSum(int[] array, int targetSum) {
Set<Integer> nums=new HashSet<Integer>();
for(int num:array){
int pmatch=targetSum-num;
if(nums.contains(pmatch)){
return new int[]{pmatch,num};
}else{
nums.add(num);
}
}
return new int[0];
}
Solution 3
public static int[] twoNumberSum(int[] array, int targetSum) {
Arrays.sort(array);
int left=0;
int right=array.length-1;
while(left<right){
int currentSum=array[left]+array[right];
if(currentSum==targetSum){
return new int[]{array[left],array[right]};
}else if(currentSum<targetSum){
left++;
}else if(currentSum>targetSum){
right--;
}
}
return new int[0];
}
function findPairOfNumbers(arr, targetSum) {
var low = 0, high = arr.length - 1, sum, result = [];
while(low < high) {
sum = arr[low] + arr[high];
if(sum < targetSum)
low++;
else if(sum > targetSum)
high--;
else if(sum === targetSum) {
result.push({val1: arr[low], val2: arr[high]});
high--;
}
}
return (result || false);
}
var pairs = findPairOfNumbers([1,2,3,4,4,5], 8);
if(pairs.length) {
console.log(pairs);
} else {
console.log("No pair of numbers found that sums to " + 8);
}
Simple Solution would be in javascript is:
var arr = [7,5,10,-5,9,14,45,77,5,3];
var arrLen = arr.length;
var sum = 15;
function findSumOfArrayInGiven (arr, arrLen, sum){
var left = 0;
var right = arrLen - 1;
// Sort Array in Ascending Order
arr = arr.sort(function(a, b) {
return a - b;
})
// Iterate Over
while(left < right){
if(arr[left] + arr[right] === sum){
return {
res : true,
matchNum: arr[left] + ' + ' + arr[right]
};
}else if(arr[left] + arr[right] < sum){
left++;
}else{
right--;
}
}
return 0;
}
var resp = findSumOfArrayInGiven (arr, arrLen, sum);
// Display Desired output
if(resp.res === true){
console.log('Matching Numbers are: ' + resp.matchNum +' = '+ sum);
}else{
console.log('There are no matching numbers of given sum');
}
Runtime test JSBin: https://jsbin.com/vuhitudebi/edit?js,console
Runtime test JSFiddle: https://jsfiddle.net/arbaazshaikh919/de0amjxt/4/
function sumOfTwo(array, sumNumber) {
for (i of array) {
for (j of array) {
if (i + j === sumNumber) {
console.log([i, j])
}
}
}
}
sumOfTwo([1, 2, 3], 4)
function twoSum(args , total) {
let obj = [];
let a = args.length;
for(let i = 0 ; i < a ; i++){
for(let j = 0; j < a ; j++){
if(args[i] + args[j] == total) {
obj.push([args[i] , args[j]])
}
}
}
console.log(obj)}
twoSum([10,20,10,40,50,60,70,30],60);
/* */