So that the result of the check is always true [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
You need to always be true in the console)
Without gaps, without rounding to the integer, without changing the comparison operator and the general calculation logic, as well as the loop
condition )
P.S. This is an interview task for junior level ...
for (let i = 0; i <= 10; i++) {
console.log(i + ':' + ((i * 0.1) == (i / 10)));
}
// needed to always true in console.log

I would just create a function to compare the difference to a threshold e.g. 0.001.
/**
* Determines if two floating value are equal within a threshold
* #param {Number} a - First floating value
* #param {Number} b - Second floating value
* #param {Number} [t=0.001] - Threshold of difference
* #return {boolean} Whether the difference is less than the threshold
*/
const equalsFloat = (a, b, t = 0.001) => Math.abs(a - b) < t;
for (let i = 0; i <= 10; i++) {
console.log(`${i}: ${equalsFloat(i * 0.1, i / 10)}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Related

Converting a 'for loop' from Javascript to Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to convert the following javascript code to python.
let speed = 50;
const lightCount = 1;
const lights = [[200, 10];
const isRed = (speed, dist, dur) =>
(18 * dist) % (10 * speed * dur) >= (5 * speed * dur);
for(let i = 0; i < lightCount; i++) {
if (isRed(speed, lights[i][0], lights[i][1])) {
speed--; // Reduce speed
i = -1; // Start again
}
}
console.log(speed);
I tried the following in python, but it is not working:
speed = 50
light_count = 1
lights = [[200, 10]
def is_red(speed, dist, dur):
if (18 * dist) % (10 * speed * dur) >= (5 * speed * dur):
return True
return False
for i in range(light_count):
if is_red(speed, lights[i][0], lights[i][1]):
speed -= 1
i = -1
print(speed)
The answer is supposed to be 36 but it is showing 49.
It always loops only once.
Please suggest a solution.
Thanks in advance
Editing i will not step the loop back. ints are immutable, so you are just editing the state of a temporary variable. You can try using a while loop, and just incrementing back i.
Example:
speed = 50
light_count = 1
lights = [[200, 10]
def is_red(speed, dist, dur):
if (18 * dist) % (10 * speed * dur) >= (5 * speed * dur):
return True
return False
i = 0
while i < light_count:
if is_red(speed, lights[i][0], lights[i][1]):
speed -= 1
# i -= 1
#i += 1
else:
i += 1
del i

Creating IF statement inside math.Random function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create code that if we generate number between 20 and 120 and the generated number is >= than 100 then we want to reduce by 20. I dont want to create multiple random numbers..Can someone help ??
my basic math.rand function -
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
the code i tried to make
randomNumber(20,120);
if(randomNumber >= 100){
return randomNumber - 20;
}
message.reply(randomNumber);
In messages it display function randomNumber(min, max) { etc...
Store the result of the randomNumber function in a variable like this:
let number = randomNumber(20,120);
if(number >= 100){
number -= 20;
}
message.reply(number);
In JavaScript, you add () to run a function. Without those parentheses, you are just returning the code itself. When you state if(randomNumber >= 100), you aren't comparing the value that the function returns, rather the function itself.
When you call randomNumber(20,120) it returns a number, but you don’t put that number in any variable, so it just gets lost. And then you return randomNumber, which is a function, that’s why it prints out the content of the function.
To avoid that, create a variable containing the random number, like so:
let x = randomNumber(20,120);
if(x >= 100){
x -= 20;
}
message.reply(x);
Just save the result of your function in a variable and then check if that variable is >= 100 and if it is reduce it by 20 using a simple ternary operator.
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
number = randomNumber(20,120);
number = (number < 100) ? number : number -20;
console.log(number);

Calculating trailing zero in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How do i calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * 4 ... N
Any Help on this?
Because zeros come from factors 5 and 2 being multiplied together, iterate over all numbers from 1 to the input number, adding to a cumulative count of fives and twos whenever those factors are found. Then, return the smaller of those two counts:
function zeroCount(n) {
let fives = 0;
let twos = 0;
for (let counter = 2; counter <= n; counter++) {
let n = counter;
while (n % 2 === 0) {
n /= 2;
twos++;
}
while (n % 5 === 0) {
n /= 5;
fives++;
}
}
return Math.min(fives, twos);
}
console.log(zeroCount(6)); // 720
console.log(zeroCount(10)); // 3628800
It is very simple, This will help you.
function TrailingZero(n)
{
var c = 0;
for (var i = 5; n / i >= 1; i *= 5)
c += parseInt(n / i);
return c;
}
Let me know if you need help to understand this function.

javascript program without using math. pow, find power of any number using for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to know the code built in for the syntax math.pow(x,y). Actually I used the syntax to find exponent of any number... e.g.
var e = Math.pow(-3, 3); yields -27 but couldn't find out the program behind this... Help me please
If you know what power means..
multiplying the number x n times where x is base and n is exponent.
So you just have to repeat the same thing over and over - and that's why loops are for:
var sum = 1; //note that it's not zero!
for (int i=0;i<n;i++) { //loops n times
sum = sum * x; //on each loop multiplies sum by base number
}
Did you mean alternative for Math.pow? Here is one way with simple loop.
function pow(base,power) {
var p = 1;
for (var i=0; i<power; i++) {
p *= base;
}
return p;
}
You can also use recursion to solve this kind of challenge. Beware that recursion has the disadvantage of increasing space complexity as compared to a for-loop.
function pow(base, power) {
if (power === 1) return base * power
return base * pow(base, power - 1)
}
This is a better way to calculate power of a number with recursion:
function power(base, exp) {
if(exp === 0){
return 1;
}
return base * power(base, exp - 1);
}
You can try this:
function pow(n, e) {
let num = n;
for (let i = 1; i < e; i++) {
num *= n;
}
return num;
}
console.log(pow(-3, 3));
It will give you the required result.

how can I program an Armstrong number in Javascript with one For loop, given that the algorithm used is mathematically correct? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have tried to code this problem by converting the looped variables from 100 to 999 to strings, seperate it's digits to numerical values, find the sum of them when cubed, it seems correct when I calculate it on pen and paper, however when I log it it just prints all looped numbers from 100 to 999 , he is my code
for (var i=100; i<=999; i++){
var x = i.toString();
var z = i
var a = parseInt(x[0]);
var b = parseInt(x[1]);
var c = parseInt(x[2]);
var y = (a * a * a) + (b * b * b) + (c * c * c);
if (y = z){console.log ("a happy number is " + x);}
}
Here is a jsfiddle for you JS FIDDLE LINK
for (var i=100; i<=999; i++){
var myString = i.toString();
var a,b,c;
//this is how I would split string apart
a =myString.substring(0,1);
b =myString.substring(1,2);
c =myString.substring(2,3);
var y = (a * a * a) + (b * b * b) + (c * c * c);
//this was your logic error
if (y === i){console.log ("a happy number is " + i);}
}
console.log('done');

Categories