Logic for my land size calculator application - javascript

I'm making this acres and karats calculator for my uncle to help him in his work.
I'll explain the whole idea of this thing with this example. So if you add 3.22 + 2.2 it should be = 5.42 but in this calculator 3.22 + 2.2 should = 6, because 3 acres + 2 acres = 5 acres and 22 karats + 2 karats = 1 acre, so the total would be 6 acres.
The way I'm doing it in the code is that I'm splitting a number like 3.22 to two, 3 and 22 and the other number to 2 and 2 and I add the whole numbers together and the fractions together and if the fractions are >= 24 I add one to the whole numbers and if there're fractions left from the whole calculation I leave it. For example 3.15 + 2.15 = 6.6, but I'm stuck on how I can add the numbers, there's also an error in there that I don't know how to resolve.
Anyway here's the code
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
function getTotal() {
d += Math.floor(num);
p += getValue(num);
if (p >= 24) {
p -= 24;
++d;
}
total = d + p / 100;
ptag.textContent = total;
}
I added the part of the code where I'm stuck.
Note: I'm trying to make the thing able to add multiple numbers not only two. Also I'm trying to add subtraction but I have no idea how to start working on the subtraction because I haven't even finished the addition.

If the error you are talking about is something like this:
Uncaught TypeError: Cannot read property '1' of null
It is because of your getValue function.
My suggestion is, instead of using something as complicated as
function getValue(v) {
return +v.toString().match(/\.(\d*)/)[1] || 0;
}
use
function getValue(v) {
return floor((v % 1) * 100);
}
This has the same effect as the code you wrote. Which for example, from input 3.13, returns 13.
But there are few other problems.
First, you should update your num variable every now and often, otherwise, it is always going to stay as an empty string (you only defined it on line 20, and you didn't update it after that).
Second, you should clear the d and p variable after you use. As of right now, both of these variables just keeps on increasing every time you run the getTotal function
For your question of how you can add two numbers, I suggest you to create a variable where you can store the first number that the user typed.
For example, when the user typed in 4.19 and pressed the plus button, save that 4.19 into a variable (let's say firstNum).
Then when the user pressed equal button, add the number from the current input field with the firstNum variable.
On how exactly you are going to add two different numbers, break two numbers you want to add into Acres part and Karats parts. Then add them separately, then use your getTotal.
So if the number is 3.21 and 5.18, add 3 and 5, add 21 and 18, then add both of them.
you'll get 8.39. Finally, convert 8.39 into 9.15.
Sorry if my calculation is not correct. It is my first time with this concept!
But I believe this is the way to go.

Related

I need help determining the difference between my code that I believe produces the same result as another, but won't be accepted

I am stuck on how my code will not be accepted by freeCodeCamp's auto-grader. The objective was to create a function without any parameters that will generate a random number using Math.random(). Then we would have to multiply the randomly generated number by 10. After multiplying the randomly generated by 10, I would have to use Math.floor() to round it up or down.
Link to challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript
These are the objectives given to me, quoted directly from freeCodeCamp's challenge:
1.) The result of randomWholeNum should be a whole number.
2.) You should use Math.random to generate a random number.
3.) You should have multiplied the result of Math.random by 10 to make it a number that is between zero and nine.
4.) You should use Math.floor to remove the decimal part of the number.
Here is my code:
function randomWholeNum() {
var x = Math.random();
var z = x * 10;
var y = Math.floor(z);
return y;
}
As you can see, I used multiple variables to complete this task. x would generate the random number, z would store the random number multiplied by 10, y would round z, resulting in all objectives passed. However, when running the code, all objectives were ticked except for Number 3. I don't understand what went wrong, and after looking at the answer for the challenge, which is:
function randomWholeNum() {
// Only change code below this line.
return Math.floor(Math.random() * 10);
}
I don't understand why the code I wrote doesn't produce the same result of freeCodeCamp's own.

Order of operations for Math.floor(Math.random() * 5 + 1)?

In the Code Academy JS course, Dragon Slayer 2/6, the following text is used in the hint to describe the order of operations for the code I included in the title.
How does this code work?
Math.floor(Math.random() * 5 + 1);
First we use Math.random() to create a random number from 0 up to 1. For example, 0.5
Then we multiply by 5 to make the random number from 0 up to 5. For >example, 0.5 * 5 = 2.5
Next we use Math.floor() to round down to a whole number. For example, >Math.floor( 2.5 ) = 2
Finally we add 1 to change the range from between 0 and 4 to between 1 and >5 (up to and including 5)
I've looked this up in several different places (here and here), and a majority of them either focus on the range that Math.random() produces (which I understand) or confirm the order of operations outlined in the hint, wherein "Math.floor" acts upon "Math.random()*5" prior to the "+1" being added.
It seems to me however that, according to the order of operations that I learned in school, the last two steps should be flipped. Would that not be the case since "Math.random()*5" and the "+ 1" are both within the parenthesis?
While the difference between these two might not make a difference in the value returned from this particular code, I could see a fundamental change in the order of operation like the one outlined here would cause me some frustration further down the road if I didn't know it.
Math.floor() will work on whatever is inside the brackets, after it has been calculated.
Math.floor(Math.random() * 5 + 1)
is the same as
var i = Math.random() * 5;
i += 1;
Math.floor(i);
You are correct that the wording on the page is wrong. The last thing that will happen is the floor call. Everything in the parenthesis will be processed first.
Honestly, I think they mixed up here, and you're right. According to PEMDAS and any mathematics I've ever learned, the +1 comes before the Math.floor function.
The Math.random() function returns a random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive). It can be any thing like 0,.34,.42 etc.
if you want random number between 0-5.
you will used Math.Random()*5. This will give you any number like 0,4.43.4.34 but not five.
Then we add 1 like this Math.random() * 5 + 1. Now the chances is you will get a number which is between 0 and 6. But you don't want number above 5. so
you apply floor method which will return largest integer less than or equal to a given number.

Determining Powers of 2?

I am creating a simple bracket system and I need a way to check if there are a correct number of teams, OR if my program needs to compensate for bye rounds.
Right now, I am checking for "powers of two" with this function:
function validBracket(data) {
var x = data.teams.length;
return ((x != 0) && !(x & (x - 1)));
}
This works pretty well, but I am needing to know how many Bye rounds to add.
For instance, if I had 16 teams, I would not need to add anymore teams. However, if I had 12 teams, I would need the first 4 teams to get a bye round.
How can I calculate number of bye rounds to add to my bracket? And would hard-coding an array of powers of two be better?
In pseudo code, something like this is what i was thinking of:
if(validateBracket(data)) {
// Valid number of teams (power of two). Keep going.
} else {
var byeRounds = calculateByeRounds();
}
NOTE: I would rather not use an array of powers of two like below:
var powersOfTwo = [2,4,8,16,32,...];
The reasoning behind this is that I would be limiting the number of teams that could be put in the system (however, I don't think a person would have over 256 teams).
var needed = (1 << Math.ceil(Math.log2(n))) - n;
More generalized solution for extreme cases:
var needed = Math.pow(2, Math.ceil(Math.log2(n))) - n;

Javascript rounding down

So I've looked into this for several hours before finally giving up and asking help.
I'm currently trying to form fill a character sheet for Pathfinder (D&D 3.5 equivalent) using adobe acrobat. I want to make it so when I fill in my strength score it will auto fill out anything that has to do with strength.
More specifically I need it to take my ability score divide by two and subtract 5 for my ability modifier. But when I use 17 for instance as my Strength score my modifier is 4. I need it to round down not up.
I tried to subtract 5.5 instead and that works until its 10 or lower. At which point I have the opposite problem.
My current code is Strength/2-5
Use Math.floor() like this:
var score = 17.0;
result = Math.floor((score / 2) - 5);
alert(result)
Output:
3
Original:
Strength/2-5
(it worked but it needed to round down instead of up)
Final:
var a = this.getField("Strength")
event.value = Math.floor((a.value - 10) / 2)
Thank you for trying everybody! Process of elimination gets it done

Understanding a function with modulo in Javascript

I had this code written by a user here yesterday and I'm having trouble understanding it. I understand all by line 9 of the deal function, it creates a random card out of 52 numbers but on the next line I don't understand what this does. Could somebody please explain what this code does so I could modify it and expand on it?
//Creates the deck
var Ace = 1;
var Face = 10;
var deck = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Face, Face, Face];
/*Creates a deal function that can deal cards to each player.
Use object_name.property_name = deal() to call this function.*/
var deal = function () {
var randomcard = Math.ceil(Math.random() * 52) + 1;
return deck[Math.floor(randomcard % 13)];
};
Well, first let's correct the code. The original code does give you a working result, but it does it in a confusing way. It doesn't pick a value between 0 and 51 which would be the natural thing to do, it picks a value between 2 and 53. (The result is still useful for getting a value between 0 and 12 to use for a value, but getting the suit for the card is not very straight forward.)
var randomcard = Math.floor(Math.random() * 52);
return deck[randomcard % 13];
The modulo operator gets the reminder from a division, so the result from the expression would get the value for the card. Up to 12 it returns the number itself, then at 13 it starts over at 0 again.
To get the index for the suit for the card, you would use Math.floor(randomcard / 13). With the original random value (2 to 53) you would have needed to use (Math.floor(randomcard / 13) % 4) instead.
There are 52 cards in the deck. 13 different values with 4 different suit( clubs/diamonds...). Note 4 * 13 = 52. The modulus 13 is just there to assure that one of the values from in the deck variables gets picked, and the suit is ignored.
You have an array of only 13 items -- the cards. 0 through 12.
If you take any number and % 13 it, you will always get a value between 0 and 12 -- the remainder of a division of that number by 13. The deck of 52 then % 13 basically reduces the deck from suit + card to just card.
This could have equally been written as Math.ceil(Math.random() * 13) + 1 instead of 52. However if the code needs to be expanded to also have a suit, then you might likely
The code is only half-valid. The modulo is poorly selecting the type of card to draw out of the deck, but not the suit the card is. In addition, the code doesn't account for having already dealt out a specific card (it's never removed from the deck), so multiple players could have identical cards.
See this page for information on how deck structure looks in JavaScript:
http://www.brainjar.com/js/cards/default2.asp

Categories