Split array of strings into more arrays of strings? - javascript

Hello so what I want to do is split array of names into more arrays of names and each arrays element joined together should be smaller than specific amount of characters and none of the strings should be split in half. if it needs to be split in half then move it to the next array.
so an example would be.
Input: arr: ["george","ben","bob","alex","robert"] amount_of_characters: 10
Output: [["george","ben"],["bob","alex"],["robert"]]

const arr = ["george","ben","bob","alex","robert"];
const amount_of_characters = 10;
const result = [];
let sumChars = 0;
for (let i = 0; i < arr.length; i++) {
const word = arr[i];
if (word.length + sumChars > amount_of_characters) {
result.push([word])
sumChars = 0;
}
else {
!result.length ? result.push([word]) : result[result.length - 1].push(word);
}
sumChars += word.length;
};
console.log(result);

You can easily achieve the result as:
const arr = ['george', 'ben', 'bob', 'alex', 'robert'];
const amount_of_characters = 10;
let currentTotal = 0;
const result = [];
for (let i = 0; i < arr.length; i++) {
const curr = arr[i];
if (currentTotal + curr.length <= amount_of_characters) {
currentTotal += curr.length;
const last = result[result.length - 1];
!last ? result.push([curr]) : result[result.length - 1].push(curr);
} else {
currentTotal = 0;
result.push([]);
i--;
}
}
console.log(result);

function split(arr, amount_of_characters){
let final_arr = [];
let i = 0; // This will be used to denote which position on the original array should be filled
let j = 0; // This will be used to denote which position on the final array should be filled
while (i < arr.length){
// Create a new array in the array
final_arr[j] = [];
let current_character_count = 0;
// Iterate over the input array
while (i < arr.length && arr[i].length + current_character_count < amount_of_characters){
final_arr[j].push(arr[i]);
current_character_count += arr[i].length;
i++;
}
j++;
}
}

You could use a for-of loop and access the last element of the current group using Array.prototype.at():
const groupByUpToNCharacters = (arr, n) => {
const groups = [[]];
let currGroupLength = 0;
for (const word of arr) {
const wordLength = word.length;
if (currGroupLength + wordLength <= n) {
groups.at(-1).push(word);
currGroupLength += wordLength;
} else {
groups.push([word]);
currGroupLength = wordLength;
}
}
return groups;
}
const arr = ["george", "ben", "bob", "alex", "robert"];
const groupedArr = groupByUpToNCharacters(arr, 10);
console.log(groupedArr);

So, what is required here is an algorithm to achieve the expected result. While multiple answers above have given elegant solutions, the below solutions use a recursive approach.
Solution - Style-1:
const joinUptoLen1 = (arr = [], mlen, i = 0) => (
i < arr.length - 1 ?
arr[i].length + arr[i + 1].length < mlen ?
[
[arr[i], arr[i + 1]]
].concat(joinUptoLen1(arr, mlen, i + 2)) :
[
[arr[i]]
].concat(joinUptoLen1(arr, mlen, i + 1)) :
i === arr.length - 1 ?
[
[arr[i]]
] :
[]
);
The same solution written another way is shown below:
Solution - Style-2:
const joinUptoLen2 = (arr = [], mlen, i = 0) => {
if (i < arr.length - 1) {
if (arr[i].length + arr[i + 1].length < mlen) {
return [
[arr[i], arr[i + 1]]
].concat(joinUptoLen2(arr, mlen, i + 2));
} else {
return [
[arr[i]]
].concat(joinUptoLen2(arr, mlen, i + 1));
}
} else {
if (i === arr.length - 1) return [
[arr[i]]
];
return [];
}
};
Approach is very simple. Check if sum-of-lengths of 2 consequent array-elements is lesser than the input-length. If so, make an array of the 2 elements and push this new-array into the result-array. If not, push an array with just the one element into the result-array. Recursively follow the same and handle the edge-scenario (if the last element was not included into a pair).
And here's a code snippet for quick-demo:
const inpArr1 = ["george", "ben", "bob", "alex", "robert"];
const inpArr2 = ["george", "ben", "bob", "alex", "robert", "pat"];
const splitLen = 10;
const joinUptoLen1 = (arr = [], mlen, i = 0) => (
i < arr.length - 1 ?
arr[i].length + arr[i + 1].length < mlen ? [
[arr[i], arr[i + 1]]
].concat(joinUptoLen1(arr, mlen, i + 2)) : [
[arr[i]]
].concat(joinUptoLen1(arr, mlen, i + 1)) :
i === arr.length - 1 ? [
[arr[i]]
] : []
);
const joinUptoLen2 = (arr = [], mlen, i = 0) => {
if (i < arr.length - 1) {
if (arr[i].length + arr[i + 1].length < mlen) {
return [
[arr[i], arr[i + 1]]
].concat(joinUptoLen2(arr, mlen, i + 2));
} else {
return [
[arr[i]]
].concat(joinUptoLen2(arr, mlen, i + 1));
}
} else {
if (i === arr.length - 1) return [
[arr[i]]
];
return [];
}
};
console.log('style-1 results: ', joinUptoLen1(inpArr1, splitLen));
console.log('style-2 results: ', joinUptoLen2(inpArr1, splitLen));

const foo = function (arr, max) { // arr - input, max - max characters in one array
const result = [];
for (let i = 0; i < arr.length; i++) {
let cur = [];
if (arr[i].length < max && i !== arr.length - 1) {
let sum = arr[i].length;
cur.push(arr[i]);
while (sum <= max) {
i++;
if (arr[i].length + sum <= max) {
sum += arr[i].length;
cur.push(arr[i]);
} else {
sum = max + 1;
i--;
}
}
} else cur.push(arr[i]);
result.push(cur);
}
return result;
};

Another way of writing it using Array.reduce():
const input = ["george","ben","bob","alex","Robert"];
let idx=0;
const output = (amount_of_characters)=>{
return input.reduce((acc,curr)=>{
acc[idx]?null: acc.push([]);
acc[idx].join('').length + curr.length <= amount_of_characters?
acc[idx].push(curr):(idx++, acc.push([]), acc[idx].push(curr));
return acc;
},[])
}
console.log(output(10));

Related

Two Sum Array - Brute Force - what am I doing wrong?

var twoSum = function(nums, target) {
let index = 0
let i = 1
while (index <= nums.length - 1) {
while (i <= nums.length - 1) {
if (nums[index] + nums[i] === target) {
if (nums[index] === nums[i]) {
i = i + 1
}
return([index, i])
} else {
i = i + 1
}
}
index = index + 1
i = 0
}
};
twoSum([3, 3], 6)
expected output: [0, 1]
received: [0, 2]
description: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You need to remove below code when you found the matched result
if (nums[index] === nums[i]) {
i = i + 1
}
var twoSum = function(nums, target) {
let index = 0
let i = 1
while (index <= nums.length - 1) {
while (i <= nums.length - 1) {
if (nums[index] + nums[i] === target) {
return([index, i])
} else {
i = i + 1
}
}
index = index + 1
i = 0
}
};
console.log(twoSum([3, 2, 0,1,4], 6))
Just remove this block.
if (nums[index] === nums[i]) {
i = i + 1
}
BTW, why you write this code from the start. You are not getting all the possible numbers. No matter how long the input array is, you just return 2 indexes.
let index = 0
while (index <= nums.length - 1) {
let i = 0
while (i++ <= nums.length - 1) {
if (index!==i && nums[index] + nums[i] === target) {
return([index, i])
}
}
index++
}
#lucumt already pointed out that you should leave out two lines of your code. However, a slightly more conventional way of expressing your function would involve for() loops as they would make the code slightly more readable than the chosen while() construct. The inner loop should also always start at index+1, see below:
var twoSum = function(nums, target) {
const res=[];
for (let index=0; index <nums.length; index++) {
for (let i=index+1;i <nums.length; i++) {
if (nums[index] + nums[i] === target ) res.push([index, i]);
}
}
return res
}
console.log(twoSum([3, 3], 6)) // [[0,1]]
// second example:
console.log(twoSum([1,6,4,7,3,2,8,3], 6)) // [[2,5],[4,7]]
My snippet will return all possible sums in an array of arrays. If you only want the first solution, simply do twoSum(arr,targetNum)[0].
You can use for-loop with the same logic because it looks more simple.
var twoSum = function(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]
}
}
}
};
let index = 0
let i = 1
while (index <= nums.length - 1) {
while (i <= nums.length - 1) {
if (nums[index] + nums[i] === target) {
// if (nums[index] === nums[i]) {
// i = i + 1
// }
return([index, i])
} else {
i = i + 1
}
}
index = index + 1
i = 0
}
};
console.log(twoSum([3, 3], 6));
Skip that "if" statement above it will increase your i's value for this case.

Can't make pyramid of numbers

I Need to get this output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
What I've tried so far:
function getPyramid() {
let nums = 0;
for (let i = 1; i <= 15; i++) {
for (let n = 1; n < i; n++) {
console.log(n);
}
console.log('<br/>');
}
return nums;
}
getPyramid();
It is possible to do with one single loop
function getPyramid() {
let nums = 0;
let count = 1;
let numbers = ''
for (let i = 0; i <= 15; i++) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + (i +1)
}
}
getPyramid();
Or like this you can specify amount of rows..
function getPyramid(rows) {
let nums = 0;
let count = 1;
let numbers = ''
let i = 1
while (count < rows + 1 ) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + i
i++;
}
}
getPyramid(5);
for (let i = 1 ; i <= 5; i++)
{
let s = []
for (let x = i * (i - 1) / 2 + 1; x <= i * (i + 1) / 2; x++)
{
s.push(x)
}
console.log(s.join(" "))
}
Apart from notes given by jnpdx in the comments, I'd add some:
for better convention between programmers we tend to name varible nested in for-loop: i, j
<br/> for HTML new line, In JS we do \n for that!
number++ is same number += 1
Conditional_Operator (expression)?true:false instead of if/else
function getPyramid(Lines) {
let number = 1; // the counter to display on each line of pyramid!
for (let i = 1; i <= Lines; i++) {
let str = '';//line to display
for (let j = 1; j <= i; j++) {
str += number++;//incrementing counter
str += j!=i ? ' ' : ''; //to make space, but not at the end of line.
}
console.log(str);//display that line
}
}
getPyramid(5);
A completely unnecessary attempt to do this in a functional style:
const ranged_array = (from, to) =>
Array.from({ length: to - from + 1 }, (_, i) => i + from);
const pyramid = (lines) =>
ranged_array(1, lines)
.reduce((a, v, i) => {
const prev = a[i - 1];
const last_num = prev && prev[prev.length - 1] || 0;
a.push(ranged_array(last_num + 1, last_num + v));
return a;
}, [])
.map((v) => v.join(' '))
.join("\n");
console.log(pyramid(5));

shuffle array without consecetive item - Javascript

I currently acheive shuffle one of array without duplicated with previous value of next value.
However, I don't think my method is good. I think there are better way.
Firstly, I will describe what the array looks like.
it's an array of object with property {answer,url,category} and there are duplicated item in the array. think as [A,A,B,B,C,C] , A,B,C as object here.
As EzioMerce pointed out, in this array, object will always has equal amount of numbers. such if there are 3 A, will definitely have 3 B and C. It will not have array as such [A,A,A,B]
I need the array to shuffle until there is no consecutive object next to each other such as [A,B,C,B,A,C]
Here is my solution (which I have tested 40 times without consecutive object):
getShuffleWords(array: Card[]) {
//First shuffle..
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor( Math.random() * (i - 1));
if (j > 0) {
//make sure there are no simliar value around position i and j
if (array[i]?.answer !== array[j - 1]?.answer
&& array[i]?.answer !== array[j + 1]?.answer
&& array[i]?.answer !== array[j - 1]?.answer
&& array[i]?.answer !== array[j + 1]?.answer) {
[array[i], array[j]] = [array[j], array[i]];
}
} else {
if (array[i]?.answer !== array[j + 1]?.answer) {
[array[i], array[j]] = [array[j], array[i]];
}
}
}
const before = [...array];
console.log(before);
//Checking duplicate and swap with other value
for (let x = 0; x < array.length; x++){
if (array[x].answer == array[x + 1]?.answer) {
console.log(x,array[x])
for (let y = 0; y < array.length; y++){
//make sure there are no simliar value around position x and y
if (array[y]?.answer !== array[x]?.answer
&& array[y + 1]?.answer !== array[x].answer
&& array[y - 1]?.answer !== array[x].answer
&& array[y]?.answer !== array[x+1]?.answer
&& array[y]?.answer !== array[x-1]?.answer
) {
console.log(y, array[y]);
if (x < y) {
[array[x], array[y]] = [array[y], array[x]];
} else {
[array[y], array[x]] = [array[x], array[y]];
}
break;
}
}
}
}
//just another caculate if there is duplication left (for testing purpose)
let dup = 0;
for (let x = 0; x < array.length; x++){
if (array[x].answer == array[x + 1]?.answer) {
dup++;
}
}
console.log(array, dup);
return array;
}
However, in the //First shuffle.. there are always has some consecutive object exisited in the array. thats why I repeat another checking and replace the value.
How would I improve my method. and why my first shuffle does not work perfectly?
You can try this way. It also works if arr will be an array of objects
const arr = [1, 2, 3, 1, 2, 3, 1, 2, 3];
const shuffle = (arr) => {
const uniqueArr = [...(new Set(arr))];
const shuffledArr = [];
let countOfOneObj = 0;
for (const obj of arr) {
if (obj === arr[0]) ++countOfOneObj;
};
const getRandomObj = () => {
const i = Math.floor(Math.random() * uniqueArr.length);
return uniqueArr[i];
}
for (let i = 0; i < countOfOneObj; ++i) {
let usedObjs = []
for (let j = 0; j < uniqueArr.length; ++j) {
const obj = getRandomObj();
if (
usedObjs.includes(obj) ||
shuffledArr[shuffledArr.length - 1] === obj
) {
--j;
continue;
}
usedObjs.push(obj);
shuffledArr.push(obj);
}
usedObjs = [];
}
return shuffledArr;
}
console.log(shuffle(arr));
You could shuffle an array of indices of same grouped values until you got a result which has no same neighbour indices.
const
fy = array => { // fisher-yates, adapted from https://stackoverflow.com/a/59837259/1447675
let i = array.length;
while (--i) {
const j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
},
shuffle = array => {
do fy(array);
while (array.some((v, i, a) => v === a[i + 1]))
};
indices = [0, 0, 0, 1, 1, 1, 2, 2];
shuffle(indices);
console.log(...indices);

How to Sort an Array of Numbers of String Datatype without using Inbuilt sort() and atoi method in JavaScript

I am trying sort the below given Array without converting the strings to number(without atoi function) and also without using sort() inbuilt function
inputArr = ["1","2","10","3","21","15"]
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
}
return inputArr;
But the above code doesn't sort the numbers in correct order
Output Expected: ["1","2","3",,"10","15","21"]
You seem to be approaching the problem by using a BubbleSort, so tried to come up with a solution using the same algorithm.
The issue is with your comparison.
You will see that
"1" < "10" === true
But
"2" < "10" === false
So you need to check each character of the string to determine whether the number is actually smaller or not.
Here is the code:
const arr = ["1", "2", "10", "3", "21", "15"];
const len = arr.length;
const isGreater = (num1, num2) => {
if (num1.length < num2.length) return false;
for (let i = 0; i < len; ++i) {
if(num1[i] === num2[i]) continue;
return (num1[i] > num2[i]);
}
return false;
}
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len - i - 1; ++j) {
if (arr[j].length > arr[j + 1].length || isGreater(arr[j], arr[j + 1])) {
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
console.log(arr);
The function isGreater will do that check for you.
inputArr = ["1","2","10","3","21","15"]
const sorted = inputArr.sort((a, b) => Number(a) - Number(b))
console.log(sorted);
const a = ["1","2","3",,"10","15","21"];
a.sort((x, y) => x-y);

Pair of elements from a specified array whose sum equals a specific target number

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

Categories

Resources