highest and smallest number in javascript using only switch statement - javascript

i am wondering how to use switch statement to tell which is the highest and lowest number in javascript, without using math.max in my script, any help?

Pseudo-code only since it may be homework.
If it is, you should do some of the work yourself.
If it isn't you should be able to convert it to whatever language you want :-)
To work out the maximum and minimum of a and b:
def mymin(a,b): def mymax(a,b):
switch (a-b): switch (a-b):
case 0: case 0:
return a return a
default: default:
switch ((a-b)/abs(a-b)): switch ((a-b)/abs(a-b)):
case -1: case -1:
return a return b
default: default:
return b return a
It basically uses (a-b)/abs(a-b) which, assuming a and b are different will return -1 if b > a otherwise 1. You would get a divide-by-zero error if they were equal hence the outer switch to detect this first.
If you're looking for the minimum and maximum from a list, just set min and max initially to the first value in the list, then run through the list comparing each value with min and max and adjusting them accordingly:
def minAndMax(list):
min = first element in list
max = first element in list
for each element e in list:
min = mymin (min,e)
max = mymax (max,e)
return (min,max)

switch (true) {
case a > b:
min = b; max = a;
break;
case a < b:
min = a; max = b;
break;
case a == b:
// I know I could just use >= or <=
min = max = a;
}
Actually it's just uglier (or not?) form of if - else if - else statement.

Related

Problem with a string: how to do a rating with javascript

I can't implement the function tipPercentage that takes the argument rating as a string and return the values:
terrible or poor, then returns 3
good or great, then returns 10
excellent, returns 20
none of the above, returns 0
the input format for custom testing must be that the first line contains a integer, n, denoting the value of rating
HELP FOR A BEGGINNER!!!
You can use a switch statement to do this relatively easily, we check the input rating, then return the relevant tip percentage.
If we don't have a tip percentage for the rating, we'll fall back to the default condition, and return 0.
One could also use a map, though a switch statement is probably more flexible.
// Takes rating as a string and return the tip percentage as an integer.
function tipPercentage(rating) {
switch ((rating + "").toLowerCase()) {
case "terrible":
case "poor":
return 3;
case "good":
case "great":
return 10;
case "excellent":
return 20;
default:
return 0;
}
}
let ratings = ["excellent", "good", "great", "poor", "terrible", "meh", null];
for(let rating of ratings) {
console.log(`tipPercentage(${rating}):`, tipPercentage(rating))
}
function tipPercentage(rating) {
switch(rating) {
case "terrible":
case "poor":
return 3; break;
case "good":
case "great":
return 10; break;
case "excellent":
return 20; break;
default:
return 0;
}
}
Instead of a switch statement you could simply use an object:
const tipPercentage = {
'excellent': 20,
'good': 10,
'great': 10,
'terrible': 3,
'poor': 3,
}
const myRatings = [
"excellent",
"good",
"great",
"terrible",
"whatever",
undefined
];
for (let rating of myRatings) {
// Tip percentage, or 0 if it doesn't exist
console.log(rating, tipPercentage[rating] || 0)
}

How to find maximum between two numbers in javascript using switch case?

I am trying to run with this code block but it does not work
Switch (num1>num2) {
case 0:
document.write(num2);
break;
case 1:
document.write(num1);
break;
}
You could use something simple as Math.max(5, 10);
const numOne = 5;
const numTwo = 10;
console.log(`Bigger number is: ${Math.max(numOne, numTwo)}`);
Or if you absolutely 'have to' use switch statement, you can try something like this:
const numOne = 5;
const numTwo = 10;
switch(true) {
case (numOne > numTwo):
console.log(`Bigger number is ${numOne}`);
break;
case (numOne < numTwo):
console.log(`Bigger number is ${numTwo}`);
break;
case (numOne === numTwo):
console.log(`${numOne} is equal to ${numTwo}`);
break;
default: console.log(false, '-> Something went wrong');
}
Logical operations return boolean on Javascript.
document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console.
switch (num1>num2) {
case true:
console.log(num1);
break;
case false:
console.log(num2);
break;
}
switch (with a lower case s) uses strict comparison === so the value of a boolean like 11 > 10 will never === 0 or 1.
You need to test for the boolean if you want to do it this way:
let num1 = 10
let num2 = 20
switch (num1>num2) {
case false:
console.log(num2);
break;
case true:
console.log(num1);
break;
}
If for some reason you were given numbers you could explicitly cast them to booleans with something like case !!0: but that starts to get a little hard on the eyes.
If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability.
You would just use the greater than / less than inside of the switch statement.
var x = 10;
var y = 20;
switch(true) {
case (x > y):
console.log(x);
break;
case ( y > x):
console.log(y);
break;
}

How to find the closest value of N no. into the sequence?

I have a list of integer sequence:
[10,15,30,45,60,75,90......n*15]
Let's say you have a value i.e. 33
What calculation i should do to find the closest value of 33 into the above sequence?
(JavaScript)
Can we find it without loop?
Thanks.
As others have already pointed out, if you're working with multiples of 15 (assuming the sequence starting with 10 was a mistake), then you can simply do the following:
var interval = 15;
var value = 33;
var closest = Math.round(value / interval) * interval;
console.log(closest);
You didn't specify any language, so here is some pseudocode. Also I assume that the sequence is actually 15*n and there has to be 0 instead of 10 as the first element. Assume the sequence is form 0 to 15*N and the test value is test. IMHO, the simplest algorithm is following:
if(test <= 0)
return 0
else if (test >= 15*N)
return 15*N
else {
lower = Math.floor(test/15)
upper = lower + 1
lowerDif = test - 15*lower
upperDif = 15*upper - test
if (lowerDif < upperDif)
return 15*lower
else
return 15*upper
}
The idea is that you need to check if test is inside [0; 15*N] range. If no - return the boundary, else check two values at indices Math.floor(test/15) and Math.floor(test/15) + 1. It is true that
Math.floor(test/15) <= test < Math.floor(test/15) + 1
So whichever is closer is the answer.

Error message while calculating if number is perfect power

I'm trying to determine if a number "n" is a perfect power. I've created the following code to work through this problem.
var isPP = function(n) {
console.log(n);
for (let base = 2; base < n; base++) {
//Change of base formula used to change natural log to log base "base"
let exp = Math.log(n) / Math.log(base);
//If "exp" variable is integer, return array containing base and exponent
if (Math.pow(base,exp) === n) {
return [base,exp];
}
}
return null;
}
This passes every test except for one random test (ex: when n = 14618, the error message reads "returned not null on non-perfect power 14618"). The same result occurs when the random test provides an "n" of 62383.
I'm not sure why the code is passing every test except for this last one. Could it be that the numbers are too large for JS?
Here are some small changes I've made to your code
var isPP = function(n){
for (let base = 2; base <= n/2; base++) { //start at 2
for (let exp = 2; exp <= n/2; exp++) {
let current = Math.pow(base,exp);
if (current == n)
return [base, exp];
if (current > n)
break; //break when found to create a 'best case' runtime
}
}
return null;
}
As #Isaac stated before, your code also fails for n=9. Your error reads this because 14618 is not a perfect power. Same with 62383.

Javascript Recursion -> what does the return trace look like?

So, I'm just starting to explore recursion and am a little stuck on a concept. Here is a solution I located for a sum digits function ( f(126) = 1 + 2 + 6 = 9 ):
function sumDigits(num, sum){
if (num === 0) {
return sum;
} else {
sum += num % 10;
num = Math.floor(num / 10);
return sumDigits(num, sum);
}}
I traced it down to the base, so far everything makes sense:
**Trace**
f(126, 0)
{
sum = 6
num = 12
f(12, 6)
}
f(12, 6)
{
sum = 8
num = 1
f(1, 8)
}
f(1, 8)
{
sum = 9
num = 0
f(0, 9)
}
f(0, 9) = 9
I guess what doesn't make sense to me is HOW the base case is being passed back through during unwinding? How exactly is it traveling?
I'm expecting a facepalm, but until I understand I don't think I could replicate this solution.
Thanks for your help!
The sum is accumulated and passed forward in each call to sumDigits. It's this value that's returned whenever the first argument equals 0. I find that it helps to write out the recursion explicitly:
sumDigits(123, 0);
return sumDigits(12, 3);
return sumDigits(1, 5)
return sumDigits(0, 6) // the base case (sum = 6)
return sum;
The final call returns 6. The previous call returns the result of the final call. The call before that returns the call before the final call (and so on). So they all end up unraveling the final sum.
Note that each call returns the result of the next call in the chain. What stops this is the base case (i.e. a condition that results in the return of a concrete value (i.e. no additional calls)).
I'd suggest
function sumDigits(num) {
if (num < 0)
return sumDigits(Math.abs(num)) //handle negative numbers
least_sig_digit = num % 10
if (num < 10)
return least_sig_digit //in case num is a float)
else
return least_sig_digit + sumDigits(Math.floor(num / 10))
}
This way you will drill down until sumDigits returns the base case, and then bubble the result. By the time you reach the top of the call stack, you should have the sum of all digits.
Here's how this works:
sumDigits(126)
= 6 + sumDigits(12)
= (6+2) + sumDigits(1)
= (6+2+1)
= 9
The function calls are made from top-to-bottom order.
The return value bubbles up in bottom-to-top order, eventually returning the value 9 for the expression sumDigits(126).
The best way to think about recursion is defining the behavior to move from one layer to the next, and not worry about the big picture. As long as you're satisfied when someone tells you 5! = 5*4!, it's a lot easier to conceptualize recursion.
What is sumDigits(126)? It's 6 + sumDigits(12). But what is sumDigits(12)? It's (6+2) + sumDigits(1). etc.
It's returning sum += num % 10 recursively.
Another way to think about it, it's returning sum but each call modifies sum (the += operator) such that when it gets to the base case the value of sum in the innermost loop is the actual sum. So just return that value through all the returns.
If you just want to print you don't even need to return anything. Just have the base case print the value of sum and return null.
The summing is done on the way in to the base case, not on the way out.

Categories

Resources