简体   繁体   中英

Finding minimum number without using Math.Min() function

I am facing problem with my question below which restricted us to use Math.Min() function to obtain answer. I tried multiple ways but never seems to get the answer right.

Minimum of two numbers Let's pretend the JavaScript Math.min() function doesn't exist. Complete the following program so that the min() function returns the minimum of its two received numbers.

// TODO: write the min() function

console.log(min(4.5, 5)); // Must show 4.5

console.log(min(19, 9)); // Must show 9

console.log(min(1, 1)); // Must show 1

One-liner using .reduce() :

 const min = (...args) => args.reduce((min, num) => num < min? num: min, args[0]); console.log(min(1, 3, 4, 5, 6, 0.5, 4, 10, 5.5)); console.log(min(12, 5));

You can try this

function getMin(a,b) {
  var min = arguments[0];
   for (var i = 0, j = arguments.length; i < j; i++){
        if (arguments[i] < min) {
             min = arguments[i];
         }
    }
  return min;
}

console.log(getMin(-6.5,4));
function min(n1,n2) {
if (n1 < n2) {
    return n1;
} else if ( n2 < n1) {
    return n2;
} else {
    return n1 || n2;
}
}
console.log(min(19,9)); //prints 9 because of the else if statement
console.log(min(1,1));  // prints either because of the else statement
console.log(min(4.5,5)); //prints 4.5 because of the if statement

or to simplify:

function min(n1, n2) {
if (n1 < n2) return n1
return n2
}

This will not win awards for elegance or accuracy but I simply followed the instructions and it worked... (not a programmer)

const min = (a, b) => {
 let arr = [a, b];
 return arr.sort((a, b) => a - b)[0];
};

console.log(min(4.5, 5)); // 4.5

this min() function sorts the array and returns the first element. this should return the smallest element. example:
min([2, 3]) -> 2
min([4.5, 9]) -> 4.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM