making a function to do multiplication - javascript

Hey I'm trying to complete a task it was given at school and I am hitting a wall I have only been learning JavaScript for about 2 days so excuse me if the answer is right in front of my face any and all help is welcome. Below is the instruction given and below the instruction is where I am at with my JavaScript. The problem I am running into is I can't seem to get it to display the cost of the bagels only the amount of bagels themselves I know I am getting close but for the life of me I cannot seem to break through this wall. Thanks in advance and sorry for the blocks of text I am not yet familiar with how to pose questions about these subjects :)
3) calculateBagels
A bagel shop charges 75 cents per bagel for orders of less than a half-dozen bagels and charges 60 cents per bagel for orders of a half-dozen or more bagels. Write a program that requests the number of bagels ordered and displays the total cost.
Test the program for orders of four bagels and a dozen bagels.
function bagelcost(number1){
var result = number1
if(result >= 6){
(result * 0.60)
} else {
(result * 0.75)
}
return result;
}
console.log(bagelcost(100))

You have to store result while multiplication otherwisw it not retain in result variable which you have return
function bagelcost(number1){
var result = number1;
if(result >= 6){
result=result * 0.60;
} else {
result=result * 0.75;
}
return result;
}
console.log(bagelcost(100));
More ever you can directly return result as below
function bagelcost(number1){
if(number1 >= 6){
return number1 * 0.60;
} else {
return number1 * 0.75;
}
}
console.log(bagelcost(200));

You should assign the statements result * 0.60 and result * 0.75 to the result variable
result=result * 0.60;
result=result * 0.75;

You can directly return the calculation. And you can omit the else part, because all code after an if with return is treated as else part. For fixed-point notation use Number.toFixed().
function getBagelCost(count) {
if (count < 6) {
return count * 0.75;
}
return count * 0.6;
}
document.write('$' + getBagelCost(4).toFixed(2) + '<br>');
document.write('$' + getBagelCost(12).toFixed(2) + '<br>');

You were really close.
The key was to save the value. Anything that uses arithmetic like this requires you to capture (assign to a variable, or send as a return value) the result on the left (hence the a = b + c; syntax).
If I might make a suggestion, it might make sense if you use more (and more descriptive) words in your functions.
As you learn (and even as you write software as a day job), it's tempting to use arithmetic everywhere, without much explanation, but it becomes easier to forget what's happening.
The same is true for changing the value multiple times. The more times you save a different value saved at the same name, the less you can tell what's happening when.
function getCostOfBagels (bagelCount) {
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
var unitPrice;
if (bagelCount < discountVolume) {
unitPrice = fullPrice;
} else {
unitPrice = discountPrice;
}
var totalCost = bagelCount * unitPrice;
return totalCost;
}
Eventually, you might consider refactoring this kind of code, so that this function only does the calculating:
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
function getBagelPrice (unitCount) {
var bagelPrice = (unitCount < discountVolume) ? fullPrice : discountPrice;
return bagelPrice;
}
function getCostOfBagels (bagelCount) {
var unitPrice = getBagelPrice(bagelCount);
var totalCost = bagelCount * unitPrice;
return totalCost;
}
getCostOfBagels(4); // 3.00
getCostOfBagels(12); // 7.20

Related

LeetCode javascript Palindrome DONE but still getting wrong output

/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
var y=x,num=0,rem;
while(x>0)
{
rem=x%10;
num=(num*10)+rem;
x=x/10;
}
if(num==y)
return true;
else
return false ;
};
I am still getting wrong output as false but my logic is correct.
This is leetcode palindrome question i am trying it with javascript logic is correct but still not able to figure it out.
There is just one issue:
In JavaScript numbers are floating point numbers by default, and so / performs a floating point division. You need to truncate that:
x = Math.floor(x / 10);
A remark on your code:
The construct if (boolean) return true; else false is an anti-pattern. Since boolean already represents the value you want to return, you should just return it. So in your case do:
return num == y;
Your logic seems fine but execution is having some minor errors. Please use below snippet, it should work:
var isPalindrome = function(x) {
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;
while (number > 0) {
reverse = reverse * 10 + number % 10;
number = parseInt(number / 10);
}
return x === reverse;
}

Usng jquery need to create division sums without remainders

In my current project, I am creating random mathematics questionnaires for abacus student. So the exam page will serve sums one by one. Based on the student level I am generationg sums at front end using jquery and rendering to get student answer for validation. In a particular level I need to generate divisions with zero remainder.
So, I am using below function to generate the sum which is returning undefined sometimes.
tripleDigitSingleDigitWithoutRemainder: function()
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
console.log("out: " + dividend + "_" + divisor);
console.log("remainder: " + (dividend % divisor));
var result_val = "";
// result_val = dividend % divisor;
if(dividend % divisor != 0)
{
console.log('loop_again');
BOBASSESSMENT.general.tripleDigitSingleDigitWithoutRemainder();
}else{
result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
}
console.log("final_return: " + result_val);
return result_val;
}
hence, please help me here to do further.
the requirement is to show question one by one and I need a dividend value and divisor value which does give remainder as 0. It means 16 % 2 = 0 not like 16 % 3 = 1.
Can you please some one help here.
As discussed in the comments here's a way to use a loop to try again with different values instead of recursion:
tripleDigitSingleDigitWithoutRemainder: function()
{
for(;;)
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
if(dividend % divisor == 0)
{
var result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
return result_val;
}
}
}
Here we have an infinite loop and we keep looping until we have a valid problem and then immediately return when we do. for(;;) is one way of writing an infinite loop: there are others e.g. while (true) { ... } if that's clearer - up to you.
(However I prefer the approach in Wimanicesir's answer which constructs a correct value rather than just trying repeatedly until we find one, which may take many more goes.)
As said in the comments. Isn't it better to just create a working division by creating it with a product?
function generate() {
// Numbers [2-9]
var small = Math.floor(Math.random() * 8) + 2
// This will give the limit of current divider
var limit = Math.ceil(900 / small)
// We check the minimum now
var minimum = Math.floor(100 / small)
// We create a new random with given limit
var big = Math.ceil(Math.random() * limit) + minimum
// Create the product
var product = big * small;
return { question: product + ' / ' + small, answer: big }
}
console.log(generate())

How can I make a function that repeats till it gets to a result without several requests?

I'm doing a memory game and I need to don't repeat the same picture more than twice, so I made a random number generator that repeats till the number isn't in an array. Doing that makes so many requests, so, when repeating the code, it doesn't work so I can't make the second half of the game. I know that the problem is in that because, when making it return the result without checking if it isn't in the array, everything works (but the images repeat, obviously). So, how can I make a function that gives a random number between two values that isn't in an array? I hope this is easy to understand.
Here the function:
function thingForTest() {
let forTest = randomBetweenBut(1, 8, 0);
if (array.includes(forTest)) {
return thingForTest();
} else {
return forTest;
}
}
Here the entire code:
var array = [];
function randomBetweenBut(num1, num2, but) {
function ifThing(num1, num2, but) {
let result = parseInt(Math.random() * (num2 - num1 + 1), 10) + num1;
if (result != but) {
return result;
} else {
return ifThing(num1, num2, but);
}
}
return ifThing(num1, num2, but);
}
function pictureRandomizer() {
for (let i = 1; i < 17; i++) {
let r1;
let picture = document.createElement("img");
function thingForTest() {
let forTest = randomBetweenBut(1, 8, 0);
if (array.includes(forTest)) {
return thingForTest();
} else {
return forTest;
}
}
array.push(thingForTest());
picture.src = "img/" + array[i - 1] + ".jpg";
let cuadrado = document.getElementById("cuadrado-" + i);
cuadrado.appendChild(picture);
if(i == 16 && r1 == false) {
i = 1;
r1 = true;
} else {
r1 = false;
}
}
}
pictureRandomizer();
You can use a function like this to return a random number between a min and a max, excluding any number passed in the exclusionArray. No recursion needed! It also includes a clause to stop infinite loops when a complete exclusionArray is passed.
Should be noted that since we're rerolling a random function, this could loop infinitely if you got REALLY unlucky, so this may not be the best function if your min, max and exclusionArray length are in the millions; But for most applications this should get the job done.
const getRandomWithExclusion = (min, max, exclusionArray) => {
// if exculsionArray contains all possible integers, return null to avoid infinite loop
if (exclusionArray.length > max - min) return null;
let output = null;
// if the randomly generated number is in the exclusionArray, reroll
while(output === null || exclusionArray.includes(output)) {
// simple random range function
output = Math.round(Math.random() * (max - min) + min);
}
return output;
}
.....

prevent rendering to page of duplicate random number generated when min and max are user defined [duplicate]

I ran into the challenge where I need a function that returns a random number within a given range from 0 - X. Not only that, but I require the number returned to be unique; not duplicating numbers that have already been returned on previous calls to the function.
Optionally, when this is done (e.g. the range has been 'exhausted'), just return a random number within the range.
How would one go about doing this?
This should do it:
function makeRandomRange(x) {
var used = new Array(x),
exhausted = false;
return function getRandom() {
var random = Math.floor(Math.random() * x);
if (exhausted) {
return random;
} else {
for (var i=0; i<x; i++) {
random = (random + 1) % x;
if (random in used)
continue;
used[random] = true;
return random;
}
// no free place found
exhausted = true;
used = null; // free memory
return random;
}
};
}
Usage:
var generate = makeRandomRange(20);
var x1 = generate(),
x2 = generate(),
...
Although it works, it has no good performance when the x-th random is generated - it searches the whole list for a free place. This algorithm, a step-by-step Fisher–Yates shuffle, from the question Unique (non-repeating) random numbers in O(1)?, will perform better:
function makeRandomRange(x) {
var range = new Array(x),
pointer = x;
return function getRandom() {
pointer = (pointer-1+x) % x;
var random = Math.floor(Math.random() * pointer);
var num = (random in range) ? range[random] : random;
range[random] = (pointer in range) ? range[pointer] : pointer;
return range[pointer] = num;
};
}
(Demo at jsfiddle.net)
Extended version which does only generate one "group" of unique numbers:
function makeRandomRange(x) {
var range = new Array(x),
pointer = x;
return function getRandom() {
if (range) {
pointer--;
var random = Math.floor(Math.random() * pointer);
var num = (random in range) ? range[random] : random;
range[random] = (pointer in range) ? range[pointer] : pointer;
range[pointer] = num;
if (pointer <= 0) { // first x numbers had been unique
range = null; // free memory;
}
return num;
} else {
return Math.floor(Math.random() * x);
}
};
}
(Demo)
You got some great programming answer. Here's one with a more theoretical flavor to complete your panorama :-)
Your problem is called "sampling" or "subset sampling" and there are several ways you could do this. Let N be the range you are sampling frame (i.e., N=X+1) and M be the size of your sample (the number of elements you want to pick).
if N is much larger than M, you'll want to use an algorithm such as the one suggested by Bentley and Floyd in his column "Programming Pearls: a sample of brilliance" (temporarily available without ACM's lock screen here), I really recommend this as they explicitly give code and discuss in terms of hash tables, etc.; there a few neat tricks in there
if N is within the same range as M, then you might want to use the Fisher-Yates shuffle but stop after only M steps (instead of N)
if you don't really know then the algorithm on page 647 of Devroye's book on random generation is pretty fast.
I wrote this function. It keeps its own array with a history of generated numbers, preventing initial duplicates, continuing to output a random number if all numbers in the range have been outputted once:
// Generates a unique number from a range
// keeps track of generated numbers in a history array
// if all numbers in the range have been returned once, keep outputting random numbers within the range
var UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) {
var current = Math.round(Math.random()*(maxNum-1));
if (maxNum > 1 && this.NumHistory.length > 0) {
if (this.NumHistory.length != maxNum) {
while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); }
this.NumHistory.push(current);
return current;
} else {
//unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];)
return current;
}
} else {
//first time only
this.NumHistory.push(current);
return current;
}
}
};
Here's a working Fiddle
I hope this is of use to someone!
Edit: as pointed out by Pointy below, it might get slow with a large range (here is a
fiddle, going over a range from 0-1000, which seems to run fine). However; I didn't require a very large range, so perhaps this function is indeed not suited if you look to generate and keep track of an enormous range.
You may try generating the number using the current date and time value which would make it unique. To make it within the range, you may have to use some mathematical function.

javascript: calculate x% of a number

I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)
how would I work out how much that is (eg 3580)
var result = (35.8 / 100) * 10000;
(Thank you jball for this change of order of operations. I didn't consider it).
This is what I would do:
// num is your number
// amount is your percentage
function per(num, amount){
return num*amount/100;
}
...
<html goes here>
...
alert(per(10000, 35.8));
Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number
35.8/100*10000
Best thing is to memorize balance equation in natural way.
Amount / Whole = Percentage / 100
usually You have one variable missing, in this case it is Amount
Amount / 10000 = 35.8 / 100
then you have high school math (proportion) to multiple outer from both sides and inner from both sides.
Amount * 100 = 358 000
Amount = 3580
It works the same in all languages and on paper. JavaScript is no exception.
I use two very useful JS functions:
http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/
function rangeToPercent(number, min, max){
return ((number - min) / (max - min));
}
and
function percentToRange(percent, min, max) {
return((max - min) * percent + min);
}
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:
function calculatePercent(amount, percent) {
const amountDecimals = getNumberOfDecimals(amount);
const percentDecimals = getNumberOfDecimals(percent);
const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`; // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}
function getNumberOfDecimals(number) {
const decimals = parseFloat(number).toString().split('.')[1];
if (decimals) {
return decimals.length;
}
return 0;
}
calculatePercent(20.05, 10); // 2.005
As you can see, I:
Count the number of decimals in both the amount and the percent
Convert both amount and percent to integers using exponential notation
Calculate the exponential notation needed to determine the proper end value
Calculate the end value
The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:
function getPerc(num, percent) {
return Number(num) - ((Number(percent) / 100) * Number(num));
}
// Usage: getPerc(10000, 25);
var number = 10000;
var result = .358 * number;
Harder Way (learning purpose) :
var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
const calculate = index / number * 100
if (calculate == percent) result += index
}
return result

Categories