How to use loop in JavaScript using while? - javascript

please excuse my ignorance; I am learning JavaScript from scratch with no background in coding.
Here is the question:
Define three variables for the LaunchCode shuttle---one for the starting fuel level, another for the number of astronauts aboard, and the third for the altitude the shuttle reaches.
Construct while loops to do the following:
Prompt the user to enter the starting fuel level. The loop should continue until the user enters a positive value greater than 5000 but less than 30000. I am very confused by the question, can you please explain it to me?
Use a second loop to query the user for the number of astronauts (up to a maximum of 7). Validate the entry by having the loop continue until the user enters an integer from 1 - 7.
Use a final loop to monitor the fuel status and the altitude of the shuttle. Each iteration, decrease the fuel level by 100 units for each astronaut aboard. Also, increase the altitude by 50 kilometers. (Hint: The loop should end when there is not enough fuel to boost the crew another 50 km, so the fuel level might not reach 0).
After the loops complete, output the result with the phrase, The shuttle gained an altitude of ___ km.
If the altitude is 2000 km or higher, add "Orbit achieved!"
Otherwise add, "Failed to reach orbit."
And here is my code for the question to answer first part:
const input = require("readline-sync")
let startingFuelLevel=0;
let numberAstronautsAboard =0;
let altitudeshuttleReaches =0;
//a:
while (startingFuelLevel <= 5000 || startingFuelLevel >30000){
startingFuelLevel = input.question("Enter the starting fuel level: ")
};
//b:
while(numberAstronautsAboard < 1 || numberAstronautsAboard > 7){
numberAstronautsAboard = input.question("Enter the number of astronauts: ")
}

JSFiddle (pure js):
https://jsfiddle.net/DariusM/14parbue/18/
Apart from the messages, a condition and a check for isNaN, it seems that you got the first two parts somewhat right - the user input.
As for the third loop, you can use setInterval() to run a function repeatedly, each time doing the following:
decrease fuel level
increase altitude
check if there is enough fuel for another iteration.
Depending on the check at (3) above, you can then show a certain message to the user depending on the current altitude.
Then, after the fuel is finished and the final message is displayed to the user, the interval needs to be cleared using clearInterval()
Good luck with your endeavor and happy coding!

Related

When does Math.random() start repeating?

I have this simple test in nodejs, I left it running overnight and could not get Math.random() to repeat. I realize that sooner or later the values (or even the whole sequence) will repeat, but is there any reasonable expectancy as to when it is going to happen?
let v = {};
for (let i = 0;; i++) {
let r = Math.random();
if (r in v) break;
v[r] = r;
}
console.log(i);
It is browser specific:
https://www.ecma-international.org/ecma-262/6.0/#sec-math.random
20.2.2.27
Math.random ( ) Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo
randomly with approximately uniform distribution over that range,
using an implementation-dependent algorithm or strategy. This function
takes no arguments.
Each Math.random function created for distinct code Realms must
produce a distinct sequence of values from successive calls.
The requirement here is just pseudo-random with uniform distribution.
Here's a blog post from V8 (Chrome and NodeJs's Javascript Engine).
https://v8.dev/blog/math-random
Where they say they are using xorshift128+, which has a maximal period of 2^128 -1.
Related (on another site): Acceptable to rely on random ints being unique?
Also extremely related: How many double numbers are there between 0.0 and 1.0?
Mathematically, there are an infinite number of real numbers between 0 and 1. However, there are only a finite number of possible values that Math.Random could generate (because computers only have a finite number of bits to represent numbers). Let's say that there are N possible values that it could generate. Then, by the Pigeonhole Principle, there is a 100% chance of getting at least one duplicate value once you generate exactly N + 1 values.
At this point, the Birthday Paradox demonstrates that you should start seeing duplicates surprisingly quickly. According to this "paradox" (which isn't a true paradox, just counterintuitive), given a room with only 23 people, there's a greater than 50% chance of two of them having the same birthday.
Returning to our example, the rule of thumb for calculating this (see the linked Wikipedia article) suggests that Math.Random reaches a 50% probability of duplicates once you generate approximately sqrt(N) numbers.
From the linked Stack Overflow question, if we assume that there are 7,036,874,417,766 numbers between 0 and 1 like the accepted answer says (and please read the linked question for a more detailed explanation of how many there actually are), then sqrt(7036874417766) is just over 2.652 million, which isn't actually all that many. If you are generating 10,000 random numbers per second, you'd reach 50% probability in approximately 737 hours, which is just under 31 days. Less fortunately, even at 10,000 per second, it would take approximately 195,468 hours (which is approximately 22.3 years) to reach 100% probability.
Some of the other answers give much higher figures for how many numbers there are, so take your pick.

Stacking percentage reduction depending on input (java script)

I'm sure this is simple enough for someone better at maths than me, but the solution is eluding me.
I need to take a number, the block chain height, which at every 500 thousand blocks, reduces the reward by 5%.
The original reward is 3 per block. So block 500001 would be 2.85, block 1,000,001 would be 2.7075, block 1,500,001 would be 2.572125, etc.
This happens all the way to block 30,000,000 so using case or if is not practical.
I can't quite tell if you need continuous reduction, or "sudden" reduction after crossing the next 500,000 (for example, is the reward at block 499,999 still 3%?).
Assuming you need "sudden" reduction, you first calculate the number of reductions.
var blocks = 10000000; // 10 million, just as an example
var reductions = Math.floor(blocks / 500000);
Then apply the reductions to your reward
var reward = 0.03 * Math.pow(0.95, reductions);
That will take off 5% (by multiplying by 0.95) the correct number of times. The result will be a decimal percent (like 0.0285 representing 2.85%, etc).
If you need a continuous reduction, you can actually just remove the Math.floor from the calculation of reductions above.

Two player number battling simulator favours second player

I am writing a fairly basic (for now) number crunching battle simulator in javascript. Its purpose is to test formula for a forthcoming game, so we can balance players stats.
Currently, the sim reduces a players health based on the following formula
player1.hp -= (Math.floor(Math.random() * 5) + 1) * player2[Math.floor(Math.random() * player2.length)].str;
HP starts on 100, and str is 2.
player2[Math.floor(Math.random() * player2.length)].str
The above code picks 1 of 3 "parts" of the player (head, body, legs) as each piece has its own stats.
So for any particular turn, starting with player 1, their head's HP is reduced by an amount based on the first formula (random part of player 2 picked, it's str stat is multiplied by a random number between 1 and 5)
Then player 2's parts are attacked, with a random part of player 1 being picked for the str stat.
(Yes, player 2 attacks first always currently, then player 1 - this may be the issue?)
When I run a single "battle", the results are fairly mixed. But when I run 100 or 1000 battles, player 2 typically comes out on top, with an average 60% win rate.
JS file here (download and run via Node)
Player who starts always has advantage because he is 1st to be able to do the finishing blow if you think of a situation where each player has 100 hp and 1 hit = 10 damage then player who started will do the 10th hit and finish the battle while player 2 will have done only 9 hits. Randomizing damage still gives advantage as 1st player has 1 hit advantage
This is a well-known problem in military combat simulation models which are turn-based. There are a couple of solutions that are commonly used. One is to randomize who gets to go first. The second is to calculate the deltas for both players before applying those deltas. The second approach has the interesting (and realistic) result that in some cases both players can be killed.

How to find the amount of each review based on the average and total number of reviews

So I have this problem that I need to work out for work, but I can't figure out a good algorithm. I am given the average for the reviews and the number of total reviews. From those two pieces of information, I need to randomly generate how many 5 star, 4 star, 3 star, 2 star, and 1 star reviews were made. Here are two formulas that might better explain what exactly the problem is.
Given Review Average (x)
Given Total Number of Reviews (y)
Find:
a = # of 5 star reviews
b = # of 4 star reviews
c = # of 3 star reviews
d = # of 2 star reviews
e = # of 1 star reviews
a + b + c + d + e = total # of reviews (KNOWN: y)
(5*a + 4*b + 3*c + 2*d + 1*e) = total number of stars = average(x) * total reviews(y)
This is more of a type of math problem than programming, but I need to be able to write some type of algorithm to get a,b,c,d, and e programatically in JavaScript. Does anyone know of any good algorithms for something like this? Thanks!
You can get the maximum possible points total by making everything a 5-star review. You can reduce this total by one by making one of the 5-star reviews a 4-star review. You could continue reducing this by one until everything is a 4-star review. Again, reduce by one by making a 4-star review a 3-star review...
So there is a way to get every possible points total from all 5-stars to all 1-stars, and you can get some sort of answer for every possible total.
Of course, you don't need to compute this point by point. You can start your search by comparing the points total with all 5-stars, all 4-stars.. all 1-stars and find the smallest total bigger than your target. Then change just enough of whatever star you have settled on to the next smallest value to reach your exact target.
(Of course this will look a bit artificial but you couldn't be creating fake review numbers to push products on a sight because this would be false advertising and sooner or later you would get caught).

Javascript: How do I code a script where the user inputs a number and it returns three other numbers?

I'm not even quite sure how I can make myself clear and I do apologize... but I have been searching all over the internet for a similar JavaScript code and I'm not even quite sure how to phrase the question ...
Basically, I want the user to input one thing, and I want something else to pop up.
As an example, the user would type in a number, let's say "10" into a text field or drop-down menu and then three other numbers would pop up, such as 15.25, 16.50, and 17.75 (either in pop window form, or just in a plain sentence, or in other text fields ... it doesn't really matter).
What I'm doing is I want to post an estimate calculator for loan payments on a website (with options for 30 day, 60 day, and 90 day payoff options).
There's no math involved in this code whatsoever (I understand if I have to input a lot of numbers - I already have those!). I don't want to create a calculator, because I think a calculator would be more complicated (I'm aiming for simple!) ... The loan fees and interest vary from one group of numbers to another, so if it were to be a calculator the script might get really complicated (because we're not looking at a easy 1 + 1 = 2 equation ... it's more like 1 + 1.50 + 1.00 = 3.50, or 10.00 + 4.00 + 1.25 = 15.25, or even 30.00 + 6.00 + 1.75 etc., there's no consistency).
So I'm figuring a simpler way around this beast would be to have the numbers readily available, with no calculations. So if they enter in a 1, the result they would get be 3.50, 4.50, and 5.50.
I don't know, that might be asking a bit much too....
Thank you in advance for your time and help.
In a simplest form it will look like this:
var magic_box = {
'1': [3.50, 4.50, 5.50],
'2': [2.50, 34.50, 5.55],
'3': [1.50, 0.50, 15.50]
};
var what = prompt( 'Tell me the magic number!' );
alert( magic_box[ what ] );
We use hash-map (aka javascript object) each element of which is an array, and each element of those arrays is your desired number.
Then, we give user a popup with question and store his answer (or his input) into variable.
Then we use this variable as a key for our hash-map.
p.s.: there are several issues with solutions above, so its purely for educational reasons.
building on #c69's answer, if there is a range for each set of numbers then add min, max values to the three numbers, loop through array, do an inclusion check, stop on row where number is in range

Categories

Resources