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))
Related
I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (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));
any help or thoughts as to what i may be not be realizing or doing ?
The problem is within your for loops. More specifically, you need to declare the variable i before using it. If you alter your code like the below snippet, then your code works just as expected:
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (let i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
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));
The only difference is using
for (let i = 1; ...
instead of
for (i = 1; ...
I'm trying to create this script: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy
After the comment "Verify and delete" is where I have the problem.
I try to check all the elements form the array 'theCheck' with the elements from 'destroyers' and if the elements dont match then the script will push that value to the output array.
But it pushes every element regardless.
Expected output value: [1,1]
Current output value value: [1,2,3,1,2,3]
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] !== destroyers[j]) {
output.push(theCheck[i])
break;
}
}
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
With the current code you're looping through the destroyers and anytime you find a destroyer that doesn't match the item you're checking you're adding it to the output. But because you've got two items in the destroyers array it is guaranteed that one of the two is not going to match the particular item that you're checking.
Below is a version where we work out whether any of the destroyers are found to match the item that we're checking, and only if it doesn't we're adding it to the output:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
let found = false;
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] === destroyers[j]) {
found = true;
}
}
if(!found) output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You could use the includes function to tidy this up a little:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
if(!destroyers.includes(theCheck[i]))
output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(input, ...arr) {
return input.filter(element => !arr.includes(element));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
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)
I need to be able to write a function that rotates a given array, first to the left, and then to the right by a given number of rotations.
What I have written so far:
function rotateArray(arr, rotLeft, rotRight) {
let len = arr.length;
for(let i=0; i<rotLeft; i++){
let temp = arr[0];
for(let i=0; i< len; i++){
arr[i]=arr[i+1];
}
arr[len-1]=temp;
}
return arr;
for(let i=0; i<rotRight; i++){
let temp = arr[0];
for(let i=0; i< len; i++){
arr[i]=arr[i+1];
}
arr[len-1]=temp;
}
return arr;
}
let arr = [1,2,3,4,5];
let rotLeft = 3;
let rotRight = 4;
let output = rotateArray(arr, rotLeft, rotRight);
console.log("New Array:", output);
Example of my code running:
Initial array = [1,2,3,4,5];
Resulted array = [4, 5, 1, 2, 3].
Any suggestion will be appreciated.
This code should do what you want:
const rotate = (array, rotLeft, rotRight) => {
const leftPass = [...array.slice(rotLeft), ...array.slice(0, rotLeft)];
const rightPass = [...leftPass.slice(array.length - rotRight), ...leftPass.slice(0, array.length - rotRight)];
return rightPass
}
// rotate([1,2,3,4,5], 3, 4) = [5, 1, 2, 3, 4]
Have separate methods for rotateLeft and rotateRight.
On each left rotate, take first element and keep it at last (shift and push)
On each right rotate, take last element and keep it at first (pop and unshift)
const rotateLeft = (arr, num) =>
Array.from({ length: num }).forEach(() => arr.push(arr.shift()));
const rotateRight = (arr, num) =>
Array.from({ length: num }).forEach(() => arr.unshift(arr.pop()));
const rotateArray = (arr, rotLeft, rotRight) => {
rotateLeft(arr, rotLeft);
rotateRight(arr, rotRight);
};
let arr = [1, 2, 3, 4, 5];
let rotLeft = 3;
let rotRight = 4;
rotateArray(arr, rotLeft, rotRight);
console.log(arr);
Couple of things wrong with your code:
The part of the code which should rotate to the right is same as the one which rotates to the left
In order to rotate the array to the right, you have to start from the end of the array (instead of the start, which is for left rotation):
for(let i = 0; i < rotRight; i++) {
let temp = arr[len - 1];
for(let i = len - 1; i > 0; i--) { // start from the last index, end at 0
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
You return the array (arr) just after finishing the left rotation,
therefore exiting the function before right rotation is executed.
All you need to do is remove the first occurrence of the line
return arr;
Here's the working code:
function rotateArray(arr, rotLeft, rotRight) {
let len = arr.length;
for (let i = 0; i < rotLeft; i++) {
let temp = arr[0];
for (let i = 0; i < len; i++) {
arr[i] = arr[i + 1];
}
arr[len - 1] = temp;
}
for (let i = 0; i < rotRight; i++) {
let temp = arr[len - 1];
for (let i = len - 1; i > 0; i--) { // start from the last index, end at 0
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
return arr;
}
let arr = [1, 2, 3, 4, 5];
let rotLeft = 3;
let rotRight = 4;
let output = rotateArray(arr, rotLeft, rotRight);
console.log("New Array:", output);
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
}