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.
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]));
Here is the leetcode question, for combination sum problem.
One answer code is here in java. (or see follow)
public class Solution {
public List<List<Integer>> combinationSum(int[] cands, int t) {
Arrays.sort(cands); // sort candidates to try them in asc order
List<List<List<Integer>>> dp = new ArrayList<>();
for (int i = 1; i <= t; i++) { // run through all targets from 1 to t
List<List<Integer>> newList = new ArrayList(); // combs for curr i
// run through all candidates <= i
for (int j = 0; j < cands.length && cands[j] <= i; j++) {
// special case when curr target is equal to curr candidate
if (i == cands[j]) newList.add(Arrays.asList(cands[j]));
// if current candidate is less than the target use prev results
else for (List<Integer> l : dp.get(i-cands[j]-1)) {
if (cands[j] <= l.get(0)) {
List cl = new ArrayList<>();
cl.add(cands[j]); cl.addAll(l);
newList.add(cl);
}
}
}
dp.add(newList);
}
return dp.get(t-1);
}
}
I need to convert it in javascript.
Here is my attempt.
function sortFunc(a, b) {
return a-b;
}
function combinationSum(cands, t) {
cands.sort(sortFunc);
let dp = []; //[[[]]];
for (let i = 1; i <= t; i++) {
console.log('-- i --');
console.log(i);
let newList = []; // [[]];
for (let j = 0; j < cands.length && cands[j] <= i; j++)
{
console.log('-- j --');
console.log(j);
if (i === cands[j]) {
console.log('-- push --');
console.log(i);
newList.push([cands[j]]);
}
else {
// list of int
let myListList = dp[i-cands[j]-1];
for(let k=0; k<myListList.length; k++) {
let myList = myListList;
if(cands[j] <= myList[0]) {
myListList.unshift([cands[j]]);
newList.push(myListList);
}
}
}
}
dp.push(newList);
}
return dp[t-1];
}
let arr = [2, 3, 5];
let t = 15;
let out = combinationSum(arr, t);
console.log(out);
I have some understanding of the code, but not a lot. Currently, my javascript is in infinite loop.
Does anyone know why?
Or if you have a better solution for "combination sum"?
You went off the rails a bit in the last for loop and kept adding to myNewList inside the loop based on it's length so the loop never ended.
Here's a version that sticks pretty close to the original:
function sortFunc(a, b) {
return a - b;
}
function combinationSum(cands, t) {
cands.sort(sortFunc);
let dp = []; //[[[]]];
for (let i = 1; i <= t; i++) {
let newList = []; // [[]];
for (let j = 0; j < cands.length && cands[j] <= i; j++) {
if (i === cands[j]) {
newList.push([cands[j]]);
} else {
for (l of dp[i - cands[j] - 1]) { // for of is similar to `for (List<Integer> l : dp.get(i-cands[j]-1))`
if (cands[j] <= l[0]) {
let cl = [cands[j], ...l] // use spread ...l to get ArrayList.addall() behavior
newList.push(cl)
}
}
}
}
dp.push(newList);
}
return dp[t - 1];
}
let arr = [2, 3, 5, 4];
let t = 7;
let out = combinationSum(arr, t);
console.log(out);
The problem is this line:
let myList = myListList;
You create a reference to myListList rather than a copy so that when you start manipulating the myListList array you end up in an endless loop.
to fix it, copy the myListList array like this
let myList = myListList.splice();
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);
/* */