Countdown 3rd array element and print sorted even numbers - javascript

I am trying to solve this task I have and I do not seem to know what is the issue with it exactly.
My task requires the following;
1- countdown from a given number by 3
2- only print the even numbers
4- sorted
what I did so far;
function cd (num){
let arrayCount = [];
let arrayEven = [];
for(let i = 0; i <= num; i++) {
arrayCount.push(num-i);
}
//return arrayCount;
for (let j = 0; j <= arrayCount.length; j+=3) {
if (arrayCount[j] % 2 == 0) {
arrayEven.push(arrayCount[j]);
}
}
arrayEven.sort(function(a,b){return a - b;});
return arrayEven;
}
console.log(cd(10)); // expected output [4]
console.log(cd(23)); // expected output [2,8,14,20]
console.log(cd(103)); // expected output [4,10,16,22,28,34,40,46,52,58,64,70,76,82,88,94,100]
console.log(cd(15)); //expected output [6,12]
My issue is with input 15 and 10 and I am not sure what I am doing work. Any help would be appreciated.

So, I figured out what was missing. The thing is that the loop would always print the first element and THEN apply the conditions you want on the rest of the elemnts, and that is why in input [10] the number 10 was printed. In short, I just needed to let my loop start from i = num-3. Thank you for you comments as they helped me a lot. Although the solution was right there, still I wanted to share the updated part, so here you go:
for (let i = num-3; i > 0; i-=3) {
if (i % 2 == 0)
array.push(i);
} let result = array.sort((a, b) => a - b);

Related

Bug in leetcode, javascript 219. Contains Duplicate II

This is the question: https://leetcode.com/problems/contains-duplicate-ii/
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
My code:
var containsNearbyDuplicate = function(nums, k) {
for(let i = 0; i < nums.length; i++) {
for(let j = i+1; j < nums.length; j++) {
console.log([i, j])
if(nums[i] == nums[j] && Math.abs(i-j) <= k){
return true;
}
}
}
return false;
};
On submission, I can pass 20/51 cases with status being 'Time Limit Exceeded'.
I can pass the following example inputs:
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
I can't think of any fringe cases which is causing the submission to exceed time limit. I'm aware that there are other ways to solve this problem, but I would like to know what's wrong with my code.
EDIT:
I realised the problem is with this line: console.log([i, j]). If I comment it out, there is no problem with submission. But I'm not quite sure why that line is causing the time limit exceeded error.
Leetcode and similar sites often provide huge data sets as input. In such cases, an unnecessarily computationally complex algorithm can take too much processing time to complete. That may be what's happening here.
You have a nested loop - if the input array contains 1000 items, that's on the order of 1000 * 1000 iterations. Use a different, less expensive algorithm - such as by iterating over the input only once. One possible approach is
var containsNearbyDuplicate = function(nums, k) {
const numsByLastIndex = {};
for(let i = 0; i < nums.length; i++) {
const num = nums[i];
if (numsByLastIndex[num] !== undefined && i - numsByLastIndex[num] <= k) {
return true;
}
numsByLastIndex[num] = i;
}
return false;
};
When I try the above code, the time required has changed from on the order of 9 seconds (which may be close to the limit) down to 1/4 of a second.
Another issue is that logging in the Node CLI, if you do a ton of logging, can slow things down. Sometimes, logging can even take up most of the processing time of your script. It's not needed to perform the task, so feel free to remove it.

Changing a number to a string and then adding up the individual integers?

I have tried multiple functions so far but the piece that I am stuck on is how to setup the function so that the argument will be 1) split into an array, 2) added together then 3) returned. I am not sure if I am looking at the question right, but I am assuming to use string.Split. Any help is welcome! Thanks!
Write a function that takes a number an an argument and returns the sum of each individual digit. So an input of 998 would return 26 (because 9 + 9 + 8) is 26.
Write the same function above, but that takes an input from the built-in browser function, prompt().
Check this below code.
let num = 998;
function individualSum(inputNum) {
let numStr = String(inputNum);
let numStrArray = numStr.split("");
let result = 0;
let len = numStrArray.length;
for (let i = 0; i < len; i++) {
result = result + Number(numStrArray[i]);
}
console.log(result);
}
individualSum(num);
Another option, with comments
let n = 998;
// To string
n = String(n);
// Split
n = n.split("");
// Summ
n = n.reduce((a, b) => Number(a) + Number(b), 0);
// Log
console.log(n)

Why does this loop terminate partway through?

I'm trying to write a program to find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
The range will be an array of two numbers that will not necessarily be in numerical order.
For example, for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3.
Why does the loop stop at i = 510,000 (or something close to that) instead of 7,000,000, as I set it?
I also have a screenshot with the output:
function smallestCommons(arr) {
var start;
var finish;
var something;
if(arr[0] < arr[1]){start = arr[0]; finish = arr[1];}else{
start = arr[1]; finish = arr[0];
}
for(var i = finish;i <= 7000000;i++){
var boolea = true;
for(var j = start;j <= finish;j++){
if(i % j !== 0){boolea = false;break;} // 2 % 1
}
if(boolea)return i;
something = i;
}
console.log("final i = " + i);
return 0;
}
Try to add this at the beginning of your loop
// noprotect
it must be that jsbin is forcing your code to exit from the loop. See source

Making a sum of arrays stop when the number 13 shows up but still return sum

I am VERY new to Javascript. I tried to look for an answer here but wasn't very lucky and maybe it's how I am asking. So, now I'm posting.
I have a loop in which I am to get a sum of the arrays. However, if the number 13 is in the array, then the loop stops adding numbers together but still return the numbers it added before it got to the 13. Right now, I have this as my code:
function sumNumbers(array) {
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum += array[i];
if(array[i] == 13) {
break;
}
}
return sum;
}
I set the argument for the function which is 'array'. Then I thought I had to create a variable where the sum of the arrays will appear so I started it at 0 (I did try [] but tested it and it wasn't correct - still wanting to understand that). I understand that for any loop, you have to have the initialization which was i = 0, then the condition and then the final expression. So, since the number of elements is undefined, I used length. So, it says if the variable i is less than that number then it will keep going and keep adding to it. So I asked it to get a sum of all the arrays but if any number in a array is a 13, I need it to stop but still return the numbers it added before it reached 13.
Right now the function is defined, the sum of all arrays are returned and 0 is returned when its empty. But, I get this error
Expected 16 to deeply equal 3.
and can't figure out what I'm doing wrong. If anyone can help and explain it a little that would be awesome. This is my first question on here, so if I did it in an annoying way, thank you in advance!
If you need to stop adding when you find 13 and not include 13 in your sum then you need to check on the value of the next array element before you add it to your sum. I reversed two lines in your code. Please see the new version:
function sumNumbers (array) {
// First check if the array is a valid input to this function
if (typeof array == 'undefined')
return 0; // Or even better throw an exception
var sum = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] == 13) { break; }
sum += array[i];
}
return sum;
}
Array.prototype.some
It's like forEach, but it stops looping whenever you return true. It was created for scenarios like yours.
let total = 0;
[3,7,4,3,2,1,13,44,66,8,408,2].some(num => {
if (num === 13) return true;
total += num;
});
console.log(total); //-> 20
Here's how you would use it:
function sumNumbers (arr) {
let total = 0;
arr.some(num => {
if (num === 13) return true;
total += num;
});
return total;
}
There are plenty ways of doing that... one of them:
function sumNumbers (array) {
var sum = 0;
for (var i = 0; array[i] != 13; i++) {
sum += array[i];
}
return sum;
}
About your:
Then I thought I had to create a variable where the sum of the arrays will appear so I started it at 0 (I did try [] but tested it and it wasn't correct - still wanting to understand that).
Well, if you make a variable initialize with [] you are setting an empty array. Remember that brackets [] are for arrays always.

permutation need help to code

Thank for your reply, first thing i wish to thank you for trying to help me out, and i have post this in few website also no one trying to help at all.
For my code, what i wish to do is permutation count.
it will count from top to bottom
1,2,3
1,2,3
1,2,3
output to
111 = 1
112 = 1
113 = 1
121 = 1
122 = 1
123 = 1
133 = 1
211 = 1
212 = 1
213 = 1
333 = 1
and continue till all number is count and also store to the array which can check how many count after all
code will check the input number and count how many outcome and show the results with how many outcome and each have how many after permutation count.
Its hard to do?.
Anyway thank you for help.
It's not that hard, I guess. It's just the standard permutation thing. You'll need to use a little recursion:
function permute(size) {
var range = getRange(size);
var result = [];
getSubPerms('', range, result);
return result;
};
function getRange(size) {
var range = [];
for (var i = 0; i < size; i++) {
range.push(i + 1);
}
return range;
}
function getSubPerms(perm, range, result) {
for (var i = 0; i < range.length; i++) {
var perm2 = perm + range[i];
if (perm2.length == range.length) {
result.push(perm2);
} else {
getSubPerms(perm2, range, result);
}
}
}
var foo = permute(4); //an array of all of your results.
alert(foo.length); //256
However, if you're only interested in the length of that, without having to generate the results, it would simply be Math.pow(size, size) to get the length of your results.

Categories