Javascript: Use reduce() method to find the LCM in an array - javascript

I am trying to find the LCM(least common multiples) among several numbers in an array. To get a LCM between each two numbers in the array, I use the reduce() method which is not working.Please tell me what's wrong? Thanks.
function gcd(a,b){
//gcd: greatest common divisor
//use euclidean algorithm
var temp = 0;
while(a !== 0){
temp = a;
a = b % a;
b = temp;
}
return b;
}
function lcm(a,b){
//least common multiple between two numbers
return (a * b / gcd(a,b));
}
function smallestCommons(arr) {
//this function is not working, why?
arr.reduce(function(a, b){
return lcm(a, b);
});
}
smallestCommons([1,2,3,4,5]);
//------>undefined

Your smallestCommons function is missing a return. undefined is the default return value for all functions that don't have an explicit return.
function smallestCommons(arr) {
return arr.reduce(lcm);
}

Related

Generating random integer between two inputs Javascript

I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.
I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?
function GetRandomInteger(a, b, c) {
a = Number(a), b = Number(b);
if (a > b) {
var a = 2,
b = 1,
c = a;
a = b;
b = c;
} else {
var x = parseInt(Math.random() * b) + a;
}
return x;
}
let x;
console.log(Number(GetRandomInteger(x)));
When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.
The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.
You don't need the c parameter. Use a temporary variable declared inside the function when swapping.
Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).
You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.
function GetRandomInteger(a, b) {
a = Number(a), b = Number(b);
if (a > b) {
let temp = a;
a = b;
b = temp;
}
var x = Math.floor(Math.random() * b) + a;
return x;
}
console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));

why does this function not work? I want it to count backwards from 10 to 1

I want it to count backwards from 10 to 1.
function countdown(n) {
if (n < 1) {
return []
} else {
return countdown(n - 1).unshift(n);
}
}
The value returned by the function isn't an array. unshift has to be used only on array objects. There's many much simpler way to achieve what you are trying to do here.
I have mentioned a simple recursive function which achieves the same -
function countdown(n) {
console.log(n)
// recursive till n becomes zero. When n === 0, just return 0
return n ? countdown(n - 1) : 0;
}
countdown(10)
NOTE : The method you are using - unshift() returns new length property of the object upon which the method was called. So, if you want to have a countback array to be returned from the function, you could choose to use the following approach which uses recursion and unshift(), just as in your code with slight changes in code -
function countdown(n) {
if (n < 1) {
return []
} else {
let z = countdown(n - 1);
z.unshift(n);
// return the array itslef so unshift() would work. Directly returning z.unshift would result in returning a number and not an array.
return z;
}
}
// will return countdown array
console.log(countdown(10))
There will probably be a better way to do this without using unshift() or recursion...but I have just shown an approach which can be used to achieve the desired result.
unshift works on arrays. n is a number.
function countdown(n){
if (n < 1) {
console.log(n)
return n
} else {
console.log(n)
return countdown(n-1);
}
}
countdown(10)

Only allowing a function to run n times with wrapper function

I need to make a wrapper function to invoke a function multiply with a given number num of times to allow the multiply to execute. nTimes(num,2) Then assign to runTwice -- runTwice can be any function that invoke the nTimes function which given a different num input--
In my case, for simplicity, I am only allowing it to run 2 times num=2
If we run the runTwice function the first time and the second time it will return the result of multiply function calculated with the inputs for multiply. Any invocation after the second time will not run the multiply function but will return the latest result of the multiply function.
Here is my implementation using an object to keep track of how many times we have execute the function, the max number allowed to execute and the latest result of multiply
'use strict'
//use a counter object to keep track of counts, max number allowed to run and latest result rendered
let counter = {
count:0,
max: 0,
lastResult: 0
};
let multiply = function(a,b){
if(this.count<this.max){
this.count++;
this.lastResult = a*b;
return a*b;
}else{
return this.lastResult;
}
}
// bind the multiply function to the counter object
multiply = multiply.bind(counter);
let nTimes=function(num,fn){
this.max = num;
return fn;
};
// here the nTimes is only executed ONE time, we will also bind it with the counter object
let runTwice = nTimes.call(counter,3,multiply);
console.log(runTwice(1,3)); // 3
console.log(runTwice(2,3)); // 6
console.log(runTwice(3,3)); // 6
console.log(runTwice(4,3)); // 6
Note that I have altered the simple multiply quite a bit and bind it the counterobject to make it work. Also using call on nTimes to bind counter object.
What can I do to implement the same result with a wrapper function but less alteration to the simple multiply function?
Let's say the multiply function is very simple:
let multiply = function(a,b){ return a*b };
You could use a closure over the count and the last value and check count and decrement and store the last result.
const
multiply = (a, b) => a * b,
maxCall = (fn, max, last) => (...args) => max && max-- ? last = fn(...args) : last,
mult3times = maxCall(multiply, 3);
console.log(mult3times(2, 3));
console.log(mult3times(3, 4));
console.log(mult3times(4, 5));
console.log(mult3times(5, 6));
console.log(mult3times(6, 7));
Nina's answer is great. Here's an alternative, with code that might look slightly easier to read:
function multiply(a, b) {
return a * b;
}
function executeMaxTimes(max, fn) {
let counter = 0, lastResult;
return (...args) => counter++ < max
? lastResult = fn(...args)
: lastResult;
}
const multiplyMaxTwice = executeMaxTimes(2, multiply);
console.log(multiplyMaxTwice(1, 3)); // 3
console.log(multiplyMaxTwice(2, 3)); // 6
console.log(multiplyMaxTwice(3, 3)); // 6
console.log(multiplyMaxTwice(4, 3)); // 6
Seeing how both Nina and Jeto have answered your question, here is a simple and similar way to do it that also keeps a history of all the results in case you want to get them at a later time.
function multiply(a, b) {
return a * b;
}
function runMaxNTimes(num, callBack) {
var results = new Array(num);
var callTimes = 0;
return function(...params) {
return results.length > callTimes ?
results[callTimes++] = callBack(...params) :
results[callTimes - 1];
};
}
var runTwice = runMaxNTimes(2, multiply);
console.log(runTwice(1, 3)); // 3
console.log(runTwice(2, 3)); // 6
console.log(runTwice(3, 3)); // 6
console.log(runTwice(4, 3)); // 6

Arithmetic with functions in Javascript

I am trying to write a function that solves the following math problem: 3625 * 9824 + 777, using only two functions: "add" and "multiply". I am stuck here:
var multiply = function (number) {
return * 9824;
};
You need to refer to the function's argument (number) to "tell" javascript what you're multiplying:
var multiply = function (number) {
return number * 9824;
// Here^
};
Good start.
Remember that the function parameter (in this case, number) can be used as a variable inside the function itself. In your case, you want to multiply whatever number is passed in and return the result. So what you'd be looking for here is:
var multiply = function(num) {
return num * 9842;
}
:) Good luck!
first create your functions:
function add(a, b){
return a+b;
}
function multiply(a,b){
return a*b;
}
then you can call them...
let ans = 0;
ans = multiply(3625, 9824);
ans = sum(ans, 777);
console.log("3625 * 9824 + 777 = ",ans);
Keep going :) and this apply to all functional languages :D
function add(a,b)
{
return (parseInt(a)+parseInt(b));
}
function multiply(a,b)
{
return (parseInt(a)*parseInt(b));
}
var result = add(mutiply(3625,9824),777);
Try this:
function add(a, b) {
return a + b;
};
var resultAdd = add(9824, 777);
function multiply(a, b) {
return a * b;
};
var result = multiply(resultAdd, 36325);

Can I add numbers using JavaScript Closures?

How can I create a closure function, that sums all passed arguments, like this?
Add(2)(2) //4
Add(2)(2)(3) // 7
Add(3)(2)(3)(0) // 8
function Add(number){
return function(number1){
return function(number2){
return number+number1+number2;
}
}
}
alert(Add(2)(2)(2));
I wanted a generalized way to achieve this.
There are duplicates here, probably with better examples, but I can't find one right now. You need to create a closure to keep track of the sum, then return the add function. Give it valueOf and toString methods so it works in other operations:
var add = (function() {
var sum = 0;
function add(n) {
sum += +n || 0;
return add;
}
add.valueOf = function(){
return sum;
}
add.toString = valueOf;
return add;
}());
document.write(add(1)(2)(3)(-2)); // 4
document.write('<br>' + add(2)(1) * 2); // 14
document.write('<br>' + add( -add())); // 0

Categories