function mathx(n){
var total
for(var i = 0; i<n.length; i++){
var sumlah = n[i] * 2;
}
}
mathx('123')
I will multiply all the data in the variable sumlah. On the code snippet there are 3 numbers that will be multiplied by the number 2 if this code is executed it will produce var sumlah = 1 * 2, var sumlah = 2 * 2 and var sumlah = 3 * 3. The result of a sumlah of 2,4,6. And I want to multiply all the data sumlah. I tried using * = but failed.
I recommend to use map:
function mathx(xs) {
return xs.map((x) => x*2);
}
mathx([1,2,3])
That just do the work. maptakes a function and the result replace every value from the list.
Also, don't use a string '123', use a list: [1,2,3].
How about this:
function mathx(n, multiple) {
var digits = n.split('');
return digits.map(function (x) {
return Number.parseInt(x) * Number.parseInt(multiple);
}).reduce(function (x, y) {
return x * y;
});
}
console.log( mathx('123', 2) )
You can be extra fancy by using map and reduce
function mathx(n) {
return n.split('').map(Number).reduce(function(acc, val) {
return acc + (val * 2);
}, 0);
}
alert(mathx('123'));
JSFiddle: click here
You need to initialize sumlah to 1, then use *= to multiply each result into it. And you have to return the result.
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
console.log(mathx('123'));
I believe this will work for what you want:
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
alert(mathx('123'));
You had two variables that you I believe were supposed to be the same - total and sumlah.
Your biggest problem is that sumlah was declared inside the for loop. By declaring it outside of the loop, it has scope outside the loop.
You want to calculate twice the current number with n[i] * 2. Then, multiply it into the accumulator sumlah with sumlah *= n[i] * 2;. When you are done, return it with return sumlah;.
However, it is best not to use a string to store numeric data. Try an array instead: [1, 2, 3]. Then you can do this:
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
alert(mathx([1, 2, 3]));
Which is almost the same, but makes sense to other people.
Related
I was attempting the leet-code problem next permutation and here's my js soln.
/**
* #param {number[]} nums
* #return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
for(let i=nums.length-1;i>=0;i--){
if(nums[i]>nums[i-1]){
var x= [...nums.slice(0,i-1),nums[i],nums[i-1]]
console.log(x)// <- This gives a different value as compared to
return x// the returned value
}
}
return nums.reverse()
};
The issue is that I am pretty much failing every test case on leetcode and the printed values are absolutely correct whereas the returned values are incorrect. It gets weirder as it runs exactly as expected on my local system with node.js.
Is this an issue with leetcode? I'd really appreciate if someone could try running this on leetcode on their local system.
So for each number sequence, we need to find the next bigger one by swapping digits. That's awesome lets try. The hardest part was to define the algorithm. Here's how I did it:
/*
Instruction
start with 2nd digit from right
swap with next smallest to the right
if result is bigger than exit that's the solution
start with 3rd digit from right
if exists, swap with next smallest to the right, sort to the right. solution
start with 4rd digit from right
if exists, swap with next smallest to the right, sort to the right. solution
return first number (minimal)
*/
And here's my solution:
/**
* #param {number[]} nums
* #return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function (nums) {
function swap(index1, index2) {
var temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp;
}
function next_bigger_from(pos) {
var current = nums[pos];
result = -1;
var min = Infinity;
for (var i = pos + 1; i < len; i++) {
if (nums[i] > current && nums[i] < Infinity) {
result = i;
min = nums[i];
}
}
return result;
}
function sort_from(pos) {
for (var i = pos; i < len - 1; i++) {
for (var j = i + 1; j < len; j++) {
if (nums[i] > nums[j]) {
swap(i, j)
}
}
}
}
var len = nums.length;
if (len < 2) {
console.log("" + nums)
return;
}
var rotator = 2; // from right
while (rotator <= len) {
var pos = len - rotator;
var pos2 = next_bigger_from(pos);
if (pos2 == -1) {
rotator += 1;
continue;
}
swap(pos, pos2);
sort_from(pos+1);
console.log("" + nums)
return;
}
nums = nums.sort();
console.log("" + nums)
return;
};
nextPermutation([1, 2, 3])
nextPermutation([3, 2, 1])
nextPermutation([1, 1, 5])
var nums = [1, 3, 5, 7];
for (var i = 0; i < 24; i++) {
nextPermutation(nums)
}
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
So what is wrong with the following solution by the OP? It doesn't change the array nums but rather returns an array x. This is why the second test (of the 4 digits sequence) fails for your code. By the way, even if I try nums = nextPermutation(nums) for the second test the results are still wrong.
/**
* #param {number[]} nums
* #return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] > nums[i - 1]) {
var x = [...nums.slice(0, i - 1), nums[i], nums[i - 1]]
console.log("" + x) // <- This gives a different value as compared to
return x // the returned value
}
}
console.log("" + nums.reverse()) // added for verbosity
return nums.reverse()
};
nextPermutation([1, 2, 3])
nextPermutation([3, 2, 1])
nextPermutation([1, 1, 5])
var nums = [1, 3, 5, 7];
for (var i = 0; i < 24; i++) {
nextPermutation(nums)
}
I'm trying to get the product of N positive odd numbers
function multOdd(n) {
var mult = 1;
var counter=[];
for (var i = 1; i <= 2*n-1; i += 2){
counter.push(i);
}
console.log(counter);
return mult=mult*counter[i];
}
console.log(multOdd(10));
I pushed the numbers into an array and attempted to get the product from them but I can't get it to work.
When you return mult=mult*counter[i] you're only returning the multipication once. It should return mult = 1 * counter[lastElement+2] which will be wrong. In your case, the last element of counter is 19, before exiting for loop i value is i= 19 + 2 = 21. You're returning mult = 1 * 21 = 21.
You can instead return the multipication value by for loop with no need for an array:
function multOdd(n) {
var mult = 1;
for (var i = 1; i <= 2*n-1; i += 2){
mult = mult * i;
}
return mult;
}
If you just want the result for n, use:
function multOdd(n) {
var result = 1;
for (var i = 1; i <= 2*n-1; i += 2){
result = result * i;
}
console.log(result);
return result;
}
console.log(multOdd(4));
If you want an array that has an array indexed by the number of odd numbers up to n you could use:
function multOdd(n) {
let result = 1;
let results = [];
for (let i = 1; i <= 2*n-1; i += 2){
result = result * i;
results[(i+1) / 2] = result;
}
console.log(results);
return results;
}
console.log(multOdd(10));
There are a few ways to get the product of an array of numbers. Here are two easy ones:
Relevant MDN
// Using `Array.prototype.reduce`
[3, 5, 7, 9].reduce((acc, val) => acc * val)
// Using a `for ... of` loop
let product = 1
for (const val of [3, 5, 7, 9]) {
product *= val
}
You could separate out the two steps of your current code into two functions:
const getFirstNOddNums = (n) => {
let oddNums = []
for (let i = 1; i <= 2*n-1; i+=2) {
oddNums.push(i)
}
return oddNums
}
const productOfArray = (arr) => {
return arr.reduce((a, b) => a * b)
}
const N = 5
const firstNOddNums = getFirstNOddNums(N)
console.log(`The first ${N} odd numbers are: ${JSON.stringify(firstNOddNums)}`)
console.log(`The product of the first ${N} odd numbers is: ${productOfArray(firstNOddNums)}`)
let multOdd = (n) => {
let total = 1;
for (let i = 1; i<= 2*n; i+=2){
total *= i;
}
return total;
}
console.log(multOdd(10));
Instead of recursion, We should use the standard mathematical formula for the product of first n positive odd integers which is
Can also be written as (in the form of pi notation)
For this latex image, I used https://codecogs.com/latex/eqneditor.php.
Factorial is
n! = n(n-1)(n-2)(n-3) ... and so on
So we can use Array(n).fill() to get an array of 10 elements and reduce them to get a factorial by
Array(n).fill().reduce((v,_,i) => (i+1) * v || 2)
Then we divide it by 2 to the power n times the n!. Which is what we want. The advantage here is that, this makes your solution, a one liner
let n = 10
let answer = Array(2*n).fill().reduce((v,_,i) => (i+1) * v || 2) / (Math.pow(2,n) * Array(n).fill().reduce((v,_,i) => (i+1) * v || 2))
console.log(answer)
I'm working on a project for school. I need to generate an array of 15 random integers between 1 & 50. I have a function, but I would not like for the numbers to repeat. (for example, if the number 3 is located at index 0, I would not like for it to show up again in the array.) If I could get some help on not getting repeat numbers, that would be great.
Thank you for any help!
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
In the loop generate a new random number while the number is in the array. In other words only continue when the new number is not in the array already.
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
do
{
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
}while(arr.includes(arrayValue))
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
genArray();
You can make a function in which check the number if its already in array than regenrate the number else push the number in array
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * max) + min;
if(checkno(arrayValue)==true)
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
function checkno(var no)
{
for(var i=0;i<arr.length;i++)
{
if(arr[i]==no)
return false;
else
return true;
}
}
An alternate solution involves the Set object, sets only have unique elements, multiple elements of the same value are ignored.
Example of the set object implemented for this use:
var temp = new Set();
while (temp.size < 15) {
var min = 1;
var max = 50;
temp.add(Math.floor(Math.random()*(max-min+1))+min);
}
This approach uses Arrow functions, forEach and includes functions.
let LENGTH = 15;
let numbers = new Array(LENGTH).fill();
let findRandomNumber = (i) => {
let rn;
while (numbers.includes((rn = Math.floor(Math.random() * 50) + 1))) {}
numbers[i] = rn;
};
numbers.forEach((_, i) => findRandomNumber(i));
console.log(numbers.sort((a, b) => a - b));
.as-console-wrapper {
max-height: 100% !important
}
You do not need to check the resulting array and regenerate the number. It is not efficient.
Please take a look at the following snippet:
function get_N_rand(N = 15, min = 1, max = 50) { // set default values
var N_rand = [], range = [];
for (var i = min; i <= max;) range.push(i++); // make array [min..max]
while (N_rand.length < N) { // cut element from [min..max] and put it into result
var rand_idx = ~~(Math.random() * range.length);
N_rand.push(range.splice(rand_idx, 1)[0]);
}
return N_rand;
}
console.log(JSON.stringify( get_N_rand() )); // run with defaults
console.log(JSON.stringify( get_N_rand(6, 10, 80) )); // run with arbitraries
I am having a little issue writing a function that factorizes numbers. The hard part is done. However I cannot seem to tell the function to return 1 when num is 0.
PS: which other ways would you write the same function in JavaScript?
var arrOfNum = [];
function factorialize(num) {
for(i = 1; i <= num; i++){
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
You already have a for loop, in which you can calculate the factorial at once, without array and reduce.
function factorial(num) {
var result = 1;
for(i = 2; i <= num; i++) {
result *= i;
}
return result;
}
You can use the following method that uses the recursion:
function factorize(num){
if(num === 0){
return 1 ;
}
else {
return num = num * factorize(num-1);
}
}
Roundup:
Declaration of local variable i is missing
var i;
Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function.
Array#reduce needs for this task an initialValue as the second parameter.
The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.
function factorial(num) {
var i,
arrOfNum = [],
result;
for (i = 1; i <= num; i++) {
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
result = arrOfNum.reduce(function (a, b) {
return a * b;
}, 1);
document.write(num+'! = '+result + '<br>');
}
factorial(0);
factorial(1);
factorial(2);
factorial(5);
factorial(8);
Simply return the value 1
function factorialize(num) {
if (num < 1) return 1; //this line is added
for(i = 1; i <= num; i++){
arrOfNum.push(i);
}
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
If you give reduce an initial value of 1, everything will work fine even without an explicit check:
var result = arrOfNum.reduce(function(a,b){
return a * b;
}, 1);
^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE
function factorial(n) {
return Array.apply(0, Array(n)).reduce(function(x, y, z) {
return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ...
}, 1);
}
DEMO
Here's a fairly streamlined function that returns an array of all factors of 'n'
You only need to look at candidates < sqrt(n)
For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor()
As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure
There are improvements that can be made to this but they're complex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes).
function factorize(n) {
n = Number(n);
if(n) {
if(n > 1) {
var sqrtn = Math.sqrt(n) | 0;
var factn = [1, n];
var ipos = 0;
for(i = 2; i <= sqrtn; i++) {
if((n % i) == 0) {
ipos++;
if((n / i) !== i) {
factn.splice(ipos, 0, i, n / i);
} else {
factn.splice(ipos, 0, i);
}
}
}
}
}
return factn;
}
Don't know why there are complicated answers. A very simple answer is:
var i;
function factorialOf(num) {
//Initially set factorial as number
var factorial = num;
//A for loop starting with 1 and running the times equal to num
for (i = 1; i < num; i++) {
//Set factorial to the number itself * i
factorial = factorial * i;
}
//Return factorial
return factorial;
}
console.log(factorialOf(5));
I am learning to code with Javascript and one exercise is about returning the factorial of a provided integer. For example: 5! = 1 * 2 * 3 * 4 * 5 = 120
I came up with a result and it was accepted. However, I am not so sure it would be the most efficient way of solving this.
Anyone would have any tips on how to improve this code?
function factorialize(num) {
var array = [];
for (i = 1; i <= num; i++) {
array.push(i);
}
var multi = 1;
for (var i = 1; i < array.length; i++) {
multi *= array[i];
}
return multi;
}
Many thanks!!
You have several approaches to get a solution.
by iteration
function f(n) {
var r = n;
while (--n) {
r *= n;
}
return r;
}
by recursion
function f(n) {
return n === 0 ? 1 : n * f(n - 1);
}
or a very short version
function f(n) {
return +!~-n || n * f(n - 1);
}
Why don't you use
var ans=1;
for (i=1;i<=num;i++)//for(i=num;i>=1;i--)
{
ans=ans*i;
}
return ans;
I have used this kind of recursive method
function f(p) {
if (p==1) return;
p -= 1;
x = x * p;
f(p);
}
A corrected version (with comments):
function f(p) {
if (p == 0) return 1; /* 0! == 1 by definition, */
return p * f(p - 1); /* otherwise p! = p * (p-1)! */
}