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 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);
/* */
I'm continue trying to write a alrorithms on Node.js like on the book Algorithms, 4th ed. Sedgewick, Wayne. There all the examples written on Java.
I have this quick sort module:
"use strict";
const _ = require('lodash');
module.exports = (function () {
function _partition(array, lo, hi) {
let i = lo;
let j = hi + 1;
let v = array[lo];
while (true) {
while (_less(array[++i], v)) {
if (i === hi) {
break;
}
}
while (_less(v, array[--j])) {
if (j === lo) {
break;
}
}
if (i >= j) {
break;
}
_exch(array, i, j);
}
_exch(array, lo, j);
return j;
}
function sort(array) {
_sort(array, 0, array.length - 1);
}
function _sort(array, lo, hi) {
if (hi <= lo) {
return null;
}
let j = _partition(array, lo, hi);
_sort(array, lo, j - 1);
_sort(array, j + 1, hi);
}
function _less(array, i, min) {
return array[i] < array[min];
}
function _exch(array, i, min) {
let temp = array[i];
array[i] = array[min];
array[min] = temp;
}
return {
sort: sort
};
})();
I use mocha and chai for testing with this function:
function isSorted(array) {
for(let i = 1, size = array.length; i < size; i++) {
if (array[i] < array[i-1]) {
return false;
}
}
return true;
}
and quick sort not working.
I need the same implementation as in book, but on js.
You can see original implementation here: quick sort in java
That implementation is ugly.
Sorry, I won't be able to help you answer a course question, but here is the beauty of a functionally recursive version of quicksort. Never, ever, use the above in javascript.
In ES6
A functionally recursive quicksort.
const quicksort = ([head, ...tail]) => head === undefined ? [] :
[...quicksort([...tail.filter(a => a <= head)]), head, ...quicksort([...tail.filter(a => a > head)])];
Usage
console.log(quicksort([1,3,1,0,6,8,9,12,15,22,54, 111,12,2,3,4,5,6,7,-1]));
Your function _less uses indexes as arguments:
function _less(array, i, min) {
return array[i] < array[min];
but you call it with array elements values:
let v = array[lo];
while (_less(array[++i], v)
(and omit first argument array - is it legal in JS?)
Simplest (most readable) quick sort function I've been able to come up with.
Quick Sort (Readability Was The Focus)
let quickSort = (items = [], left = [], right = []) => {
if (items.length <= 1) return items
let pivot = items.pop()
let pushToSide = item => (item < pivot ? left : right).push(item)
items.forEach(pushToSide)
return [...quickSort(left), pivot, ...quickSort(right)]
}
Note: Two other ways to write the same logic above are as follows
for loop instead of foreach
let quickSort = (arr = [], left = [], right = []) => {
if (arr.length <= 1) return arr;
let pivot = arr.pop();
for (let i = 0; i < arr.length; i++)
(arr[i] < pivot ? left : right).push(arr[i]);
return [...quickSort(left), pivot, ...quickSort(right)];
}
_ Quicksort using anonymous callback function within items.forEach instead of variable passed callback_
Anonymous ForEach Callback
let quickSort = (items = [], left = [], right = []) => {
if (items.length <= 1) return items;
let pivot = items.pop();
items.forEach(item => (item < pivot? left : right).push(item))
return [...quickSort(left), pivot, ...quickSort(right)];
}
Short list of other sorts created in js/node.js and references to some useful links
let sort = {
quick: (items = [], left = [], right = []) => {
if (items.length <= 1) return items
let pivot = items.pop()
let pushToSide = item => (item < pivot ? left : right).push(item)
items.forEach(pushToSide)
return [...sort.quick(left), pivot,...sort.quick(right)]
},
bubble: (items = []) => {
for (let passover = 0; passover < items.length; passover++)
{
for (let index = 0; index < items.length; index++)
{
if (items[index] > items[index + 1])
{
let temporary = items[index]
items[index] = items[index + 1]
items[index + 1] = temporary
}
}
}
return items;
},
select: (items = []) => {
for (let passes = 0; passes < items.length; passes++)
{
let min = passes
for (let i = passes; i < items.length; i++)
{
if (items[i] < items[min]) {
min = i
}
}
if (min !== passes) {
let temporary = items[passes]
items[passes] = items[min]
items[min] = temporary
}
}
return items
},
insert: (items = []) => {
for (let i = 1; i < items.length; i++)
{
let index = i-1
let temporary = items[i]
while (index >= 0 && items[index] > temporary)
{
items[index + 1] = items[index]
index--
}
items[index + 1] = temporary
}
return items
},
}
console.log('quick: ', sort.quick([0,43,3,2,3,4]))
console.log("select: ", sort.select([0,43,3,2,3,4]))
console.log("insert: ", sort.insert([0,43,3,2,3,4]))
console.log("bubble: ", sort.bubble([0,43,3,2,3,4]))
<ul>
<li>sort.quick O(n log n) avgerage time complexity</li>
<li>sort.bubble O(n^2) average time complexity</li>
<li>sort.insert O(n^2) average time complexity</li>
<li>sort.select O(n^2) average time complexity</li>
<li>Watch how different sorting algorithms compare in real time</li>
<li>
Time Complexity/Space Complexity cheat sheet</li>
</ul>