Conditioning a Function (JS) - javascript

I'm trying to return a message if one of the argument is not a number. Otherwise continue with the function.
I'm trying this but it's not working as I'm expecting.. ..Please, any help?
function findingPairs(arr, value){
if(isNaN(arr) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
} for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)

You can use Number.isInteger to check if something is a number.
And Array.every over the array to check all the array.
Also I'm throwing an Error instead of returning a value because that's what is expected usually.
Error Docs
function findingPairs(arr, value) {
if (!arr.every(Number.isInteger) || !Number.isInteger(value)) {
throw new Error("Please, introduce just numbers");
}
let sum = 0;
let finalOutput = [];
for (let i = 0; i < arr.length; i++) {
let numA = arr[i];
console.log(numA);
}
for (let j = 1; j < arr.length; j++) {
let numB = arr[j];
console.log(numB);
}
}
const value = findingPairs([1, 3, 7], 9);
const value2 = findingPairs([1, "a", 7], 9); // Will throw
const value2 = findingPairs([1, 23, 7], "hey"); // Will throw
console.log(value);

You need to check if each element of the array is a number, you can use Array.prototype.some() to test if one element of the array respects a condition
function findingPairs(arr, value){
if(arr.some(isNaN) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
}
for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)

Related

equivalent of python's array.pop() in javascript

I wonder if there's an easy to implement equivalent to python's array.pop() which returns the deleted element while deleting it from the array in parallel in javascript.
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let j = 0; j < nums.length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
arr.push(nums.splice(smallest_index, 1).join(""));
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
it seems that if I replace javascript's (nums.splice(smallest_index, 1).join()) with python's (arr.append(nums.pop(smallest_index)) I would get a perfectly sorted array. is there a similar straightforward solution in javascript as well ?
OK, you use splice. Here's an example of the implementation below:
Array.prototype.pythonPop = function (index) {
return this.splice(index, 1)[0];
}
Now, I found the issue, you'll love the answer. So you were using num.length but your methods were augmenting the length of num array. Which is why your answer had only half the needed numbers. See code below. I cached the length prop of nums array
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
console.log(nums)
for (let j = 0, length = nums.length; j < length; j++) {
smallest_index = find_smallest(nums);
console.log("smallest", smallest_index);
console.log(nums)
arr[j] = nums.splice(smallest_index, 1).join("");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
// console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums))

Undefined property after sorting array

This is my function, on my console I got the sorted array, with a property on my array object which's key is undefined, and the property's value is the last item of the array. My question is how did that property was created, why, and what does a property called undefined mean.
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
let smallest = arr[i];
let currentIndex;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
currentIndex = j;
}
if (j === arr.length - 1) {
arr[currentIndex] = arr[i];
arr[i] = smallest;
}
}
}
return arr;
};
The problem is that you assign value to currentIndex inside the first if condition, so in an unsorted array you use an unassigned variable as index.
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
let smallest = arr[i];
let currentIndex;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
currentIndex = j;
}
if (j === arr.length - 1) {
console.log("currentIndex:", currentIndex);
arr[currentIndex] = arr[i];
arr[i] = smallest;
}
}
}
return arr;
};
let res1 = selectionSort([5,8]);
console.log(res1);
let res2 = selectionSort([5,3]);
console.log(res2);
What you are trying to do is called bubble-sort, and here is the code for it:
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
};
let res1 = selectionSort([5,8,1,99,45]);
console.log(res1);
let res2 = selectionSort([5,6,7,8]);
console.log(res2);

Insertion Sort from Right to left with Javascript

I am trying to write an insertion sort function that works from right to left.
Not in descending order. I just am not understanding why this code would not properly sort numbers.
function reverseInsertionSort(arr) {
for(var i = arr.length -1; i >0; i--)
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] < val; j--) {
arr[j-1] = arr[j]; }
va=arr[j]; }
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; }
arr[j] = val; }
}
arr[j] = val;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
var arr2= arr.slice();
reverseInsertionSort(arr2);
console.log(arr2)
It is not sorted, and the output ends in undefined.
arr is being used to test the insertionsort fun
Happy to accept constructive criticism.
This will work.
function reverseInsertionSort(arr) {
for(var i = arr.length-2; i>=0; i--) {
var value = arr[i];
var j;
for(j = i; ((j < arr.length) && (arr[j+1] > value)); j++){
arr[j] = arr[j+1];
}
arr[j] = value;
}
return arr;
}
//test
var inputArray = [3,2,4,5,1,10,23];
var resultArray = reverseInsertionSort(inputArray);
console.log(resultArray); //[23, 10, 5, 4, 3, 2, 1]
You should start the outer loop from the last element ie. len-1. The undefined member of the array is created due to your outer loop starting from arr.length .
Try this :
function insSort(arr){
for(var i=arr.length-1;i>=0;i--){
key=arr[i];
j=i+1;
while(j<arr.length&&arr[j]<=key){
arr[j-1]=arr[j];
j++;
}
arr[j-1]=key;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
insSort(arr);
console.log(arr);

Performance: why is the first implementation of the same algorithm significantly faster

The algorithm is taken from LeetCode: https://leetcode.com/problems/maximum-product-of-word-lengths/description/
Here is the jsperf I created (I have some local tests which gives the same result): https://jsperf.com/maximum-product-of-word-lengths
Here is the first "slow" implementation:
function maxProduct (words) {
if (!words || !words.length) return 0;
let len = words.length;
let values = [];
// console.log(values)
for (let i = 0; i < len; ++i) {
let tmp = words[i];
let num = 0, len = tmp.length;
for (let j = 0; j < len; ++j) {
num |= 1 << (tmp.charCodeAt(j) - 'a'.charCodeAt(0));
}
values[i] = {
num: num,
len: tmp.length
};
}
let maxProduct = 0;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len; ++j) {
if ((values[i].num & values[j].num) == 0) {
maxProduct = Math.max(maxProduct, values[i].len * values[j].len);
}
}
}
return maxProduct;
};
Here is the "fast" implementation:
function maxProductFast (words) {
var temp = [];
for(var i = 0; i < words.length; i++){
var tempObj = {};
tempObj.item = words[i];
var num = 0;
for(var j = 0; j < words[i].length; j++){
num |= 1 << (words[i].charCodeAt(j) - 97);
}
tempObj.num = num;
temp.push(tempObj);
}
var res = 0;
for(var i = 0; i < temp.length; i++){
for(var j = i + 1; j < temp.length; j++){
var item1 = temp[i];
var item2 = temp[j];
if((item1.num & item2.num) == 0) {
res = Math.max(res, item1.item.length * item2.item.length);
}
}
}
return res;
}
They're not the same. The second algorithm has a loop with a complexity of (n*(n+1))/2 where each progressive step is from i+1 to the length of temp. the first algorithm has a two nested for loops each with a cost of n^2. the complexity of both will reduce to O(n^2). I believe that both of these will have a similar performance with a significantly large enough set.
The reason you would do n+1 for each sub iteration is because you are trying to find the max of any pair of items. if you place your elements in a grid you will notice that any diagonal pair a_3 * a_2 = a_2 * a_3 produces the same value. you can basically halve the collection and save a few cycles.

[JS]Array merging without using array functions

I need help merging two arrays without using any of the array built in functions ( no concat, push, pop, shift, replace, sort, splice, etc)
And I've got to this point but I'm stuck.
function addTwoArrays(arr1, arr2){
var merge = [], p;
for(p = 0; p < arr1.length; p++){
merge[arr1[p]] = true;
}
for(p = 0; p < arr2.length; p++){
merge[arr2[p]] = true;
}
return Object.keys(merge);
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
return is 1,2,3,4 - instead of 1,2,3,4,4,3,2,1
You only need to loop once - simply take arr1.length as a start index and add to the array:
function addTwoArrays(arr1, arr2) {
let start = arr1.length;
for (let i = 0; i < arr2.length; i++) {
arr1[start++] = arr2[i];
}
return arr1;
}
console.log(addTwoArrays([1, 2, 3, 4], [4, 3, 2, 1]));
Keys are unique in a JSON object. So, Object.keys() will return unique occurrences of each element.
Instead try this:
function addTwoArrays(arr1, arr2){
var merge = [], p, index = 0;
for(p = 0; p < arr1.length; p++){
merge[index++] = arr1[p];
}
for(p = 0; p < arr2.length; p++){
merge[index++] = arr2[p];
}
return merge;
}
window.alert(addTwoArrays([1,2,3,4],[4,3,2,1]));
function mergedArray(arrayOne, arrayTwo) {
let newArr = arrayOne
let x = arrayOne.length
let y = arrayTwo.length
let z = arrayOne.length + arrayTwo.length
let i, j
for (i = x, j = 0; i < z && j < y; i++, j++) {
newArr[i] = arrayTwo[j]
}
return newArr
}

Categories

Resources