program to right rotate an array in javascript - javascript

function rotateOnce(a) {
let temp, i;
temp = a[a.length - 1];
for (i = 0; i < a.length-1; i++) {
a[i + 1] = a[i];
}
a[0] = temp;
return a;
}
function main() {
let a = [1, 2, 3, 4, 5];
let i;
let k = 3;
for (i = 0; i < k; i++) {
a = rotateOnce(a);
}
console.log(a);
}
main();
I want to right rotate an array. If k=1,
input=12345
output=51234
What the code does:
It calls rotate once k times to achieve k rotations.
The last element is saved into a variable "temp" which is later put to first element of array.
Changing the for loop to this:
for (i = a.length - 2; i >= 0; i--) {
a[i + 1] = a[i];
}
Fixes the code. But I want to solve it using my way and know why it is not working.

Related

Two Sum confusing bug

I'm trying to solve a beginner problem on leetcode.
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
My solution works well on some of the testcases, but fail on this:
*
Example:
Input: nums = [3,3], target = 6
Output: [0,1]
This is my code:
let nums = [3, 3];
let target = 6;
var twoSum = (nums, target) => {
for (let i = 0; i < nums.length; i++) {
let result = [];
if (target === nums[i] + nums[i + 1]) {
result.push(nums.indexOf(nums[i]));
result.push(nums.indexOf(nums[i + 1]));
return result;
}
}
};
console.log(twoSum(nums, target));
Output is [0,0] here, instead of [0,1].
Where did the logic fail? I clearly pushed nums[i + 1] to the array as the second value.
Your algorithm is incorrect because the elements need not be adjacent to each other. Instead, you should use a nested loop to add each element of the array with every element after it.
var twoSum = (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];
}
}
};

find all numbers disappeared in array

Please help me to solve this leetcode problem using javascript as I am a beginner and dont know why this code is not working
Ques: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
var findDisappearedNumbers = function (nums) {
var numLength = nums.length;
nums.sort(function (a, b) { return a - b });
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
}
}
for (var k = 0; k < nums.length; k++) {
for (var j = 1; j <= numLength; j++) {
if (nums[k] !== j) {
return j;
}
}
}
};
if there is any error in my code please let me know;
i have done the following thing
first i have sorted the array in ascending order
then i have cut all the duplicate elements
then i have created loop that will check if nums[k] !== j ;
and it will return j which is the missing number;
for example this is the testcase [4,3,2,7,8,2,3,1]
first my code will sort this in ascending order [1,2,2,3,3,4,7,8]
then it will remove all duplicate elements and it will return [1,2,3,4,,7,8]
and then it will check nums[k] is not equal to j and it will print j
I think it'd be easier to create a Set of numbers from 1 to n, then just iterate through the array and delete every found item from the set:
var findDisappearedNumbers = function(nums) {
const set = new Set();
for (let i = 0; i < nums.length; i++) {
set.add(i + 1);
}
for (const num of nums) {
set.delete(num);
}
return [...set];
};
console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]));
To fix your existing code, I'm not sure what the logic you're trying to implement in the lower section, but you can iterate from 1 to numLength (in the outer loop, not the inner loop) and check to see if the given number is anywhere in the array. Also, since you're mutating the array with splice while iterating over it in the upper loop, make sure to subtract one from i at the same time so you don't skip an element.
var findDisappearedNumbers = function(nums) {
var numLength = nums.length;
nums.sort(function(a, b) {
return a - b
});
for (var i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i]) {
nums.splice(i, 1);
i--;
}
}
const notFound = [];
outer:
for (var j = 1; j < numLength; j++) {
for (var k = 0; k < nums.length; k++) {
if (nums[k] === j) {
continue outer;
}
}
notFound.push(j);
}
return notFound;
};
console.log(findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]));
#CertainPerformance certainly cracked it again using the modern Set class. Here is a slighly more conservative approach using an old fashioned object:
console.log(missingIn([4,3,2,7,8,2,3,1]));
function missingIn(arr){
const o={};
arr.forEach((n,i)=>o[i+1]=1 );
arr.forEach((n) =>delete o[n] );
return Object.keys(o).map(v=>+v);
}
My solution for the problem to find the missing element
var findDisappearedNumbers = function(nums) {
const map={};
const result=[];
for(let a=0;a<nums.length;a++){
map[nums[a]]=a;
}
for(let b=0;b<nums.length;b++){
if(map[b+1]===undefined){
result.push(b+1)
}
}
return result;
};
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]

Two Sum Leetcode in Javascript - code looks correct but Leetcode says it's wrong

I'm working on the 'Two Sum' problem in Leetcode.
I'm sure this code is correct, I've tested it in Repl and it looks correct there, but Leetcode is giving me an error.
Here's my code:
var arr = [];
var twoSum = function(nums, target) {
for(var i = 0; i < nums.length; i++){
for(var j = i+1; j < nums.length; j++){
console.log(nums[i] + ', ' + nums[j]);
var tot = nums[i] + nums[j];
if(tot === target){
arr.push(i,j);
console.log(arr);
return arr;
}
}
}
};
//var a = [2, 7, 11, 15];
//var b = 9;
var a = [2, 3, 4];
var b = 6;
twoSum(a, b);
The error I'm getting is as follows:
Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
Why is it expecting [1, 2]? Surely it should expect [0, 1] in this case, and then why is my code adding to the arr array twice? It looks like a bug to me...
Note: I see there's many posts about this problem on Leetcode, but none address the specific issue I have run into in Javascript.
Why is it expecting [1, 2]?
Because 2 + 4 = 6
Surely it should expect [0, 1] in this case
No, because 3 + 2 = 5
and then why is my code adding to the arr array twice?
Because you declared the array outside of the function. It is being re-used for every call to the function. Move the array declaration into your twoSum function or even better: Simply return [i, j] instead of pushing into the empty array.
Here is another solution you can try...
var twoSum = function(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let compliment = target - nums[i];
if (map[compliment]) {
return [(map[compliment] - 1), i];
} else {
map[nums[i]] = i + 1;
}
}
};
twoSum([2, 3, 4],6);
Click Here to RUN
Here is an optimum solution
/**
* #param {number[]} nums
* #param {number} target
* #return {number[]}
*/
function twoSum(nums, target) {
const numsObjs = {}; // create nums obj with value as key and index as value eg: [2,7,11,15] => {2: 0, 7: 1, 11: 2, 15: 3}
for (let i = 0; i < nums.length; i++) {
const currentValue = nums[i];
if (target - currentValue in numsObjs) {
return [i, numsObjs[target - currentValue]];
}
numsObjs[nums[i]] = i;
}
return [-1, -1];
}
console.log(twoSum([2, 7, 11, 15], 9))
This is my solution, which is a brute force method that uses javascript to search for all possible pairs of numbers.
var twoSum = function(nums, target) {
let numarray = new Array(2);
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
numarray[0] = i;
numarray[1] = j;
}
}
}
return numarray;
};

Loop trough array and sum the length

EDITED:
Can someone help me with the problem below further. I have a class and an array inside the class. I want now use a for loop to sum the length of the previous array length, but for each iteration. If i == 1 I want sum the length of arr[0].x.length, If i == 2 I want sum the length of arr[0].x.length+arr[1].x.length, ect. It will be a lot of code to check each iteration.
Is there a simple way to do this? Instead allways use a new line like
if (i == 1) n = n + arr[i-1].x.length;
if (i == 2) n = n + arr[i-1].x.length+arr[i-2].x.length;
if (i == 3) n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
function Class() {
var x = [];
}
for (var i = 0; i < 9; i++) {
arr[i] = new Class();
}
I add 4 items to each object.
arr[0].x.push(...)
arr[0].x.push(...)
...
arr[1].x.push(...)
arr[1].x.push(...)
...
var n = 0;
for (var i = 0; i < arr.length; i++) {
if (i == 1) {
n = n + arr[i-1].x.length;
} else if (i == 2) {
n = n + arr[i-1].x.length+arr[i-2].x.length;
} else if (i == 3) {
n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
}
// ect.
}
You could use reduce to get a total of all the lengths of your sub-arrays. For example:
const arrs = [[1, 2, 3], [4, 5, 6]];
const sum = arrs.reduce((acc, arr) => acc += arr.length, 0);
console.log(sum);
// 6
Just nest the loop two times: go over the indexes once then go up to that index from 0 in an inner loop:
for (var i = 0; i < arr1.length; i++) {
for(var j = 0; j <= i; j++) {
n = n + arr1[j].length;
}
}
Edit: benvc's answer is what you are looking for if you want to use reduce.
var arr = [[1,2,3], [4,5,6], [7]];
var n = 0;
for (var i = 0; i < arr.length; i++){
n += arr[i].length;
}
console.log(n);

JavaScript Algorithm Insertion Sort slightly off

Here is the link to my JavaScript Insertion Sort Algorithm
Quite simply, I just can't figure out why I can't get that pesky arr[0] to get sorted correctly. I've tried everything I know of. sigh
It's pretty close though.
Any idea's
var aoo = [5,2,4,6,1,3];
function jInsertionSort(a) {
for(var j=2; j<a.length; j++){
//console.log(j);
var key = a[j];
var i = j - 1;
while (i > 0 && a[i] > key) {
a[i+1] = a[i];
i = i-1;
}
a[i+1]=key;
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");
?
JavaScript Insertion Sort Algorithm
You almost got it, this works:
var aoo = [5,2,4,6,1,3];
function jInsertionSort(a) {
for(var j=1; j<a.length; j++){
var key = a[j];
var i = j;
while (i > 0 && a[i-1] > key) {
a[i] = a[i - 1];
a[i - 1] = key;
i = i-1;
}
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");
var aoo = [5,2,4,6,1,3];
function jInsertionSort (a) {
for (var i = 0; i < a.length; i++) {
var k = a[i];
for (var j = i; j > 0 && k < a[j - 1]; j--)
a[j] = a[j - 1];
a[j] = k;
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");

Categories