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 6 years ago.
Improve this question
In this exercise, you will roll a pair of dice until the numbers add up to a given number. You can assume that the given number is 2, 3, 6, or 12. Using pseudocode, write an algorithm that returns the number of times the dice is rolled to achieve this number.
I have absolutely no idea how to start doing this. Can you guide me a bit?
Also what does the last sentence mean?
This should get you started. The detail the assignment calls for is likely one or two levels refined from here. For example, what does "roll a die" mean. Probably something to do with saving a random number of some sort to a variable....
define rollRequiredForA(target) {
if target is not an integer or is outside the valid bounds abort
initialize a counter to 0
loop
increase the counter by one
roll two dice
add results together
if the result equals target return counter
end loop
}
First let me address your question about the last sentence of the problem:
I'll break it down in parts.
First pseudocode is a simplification of the steps that you would need to take in solving a problem in a format that is very representative of code but is not actual code written in any programming language. For example pseudocode could be something like this:
if the earlier result is 2 then
use this list: Britney, Caitie, Sierrah
else
use this other list: Brooke, Josh, Zach
Secondly an algorithm is a set of rules to followed in calculating or solving a problem. It's like a formula for solving a problem. Some everyday examples could be:
Driving home: what route should you take? Will there be traffic on the shortest route? If so, will it slow you down more than taking a slightly longer route? These are all questions that would be asked in an algorithm.
Sorting: Typically when you sort something, you do it in a specific way even though you may not realize it such as checking each one and pulling the first out of the pile and putting it on top and then the second and then the third and so on and so forth.
Dividing and conquering: This is another very common algorithm in everyday life.
For more examples check out this quora post
So in other words, the last sentence is asking you to write a simplification of the steps that you would need to take to calculate the amount of rolls of the dice it takes to get those two dice to add up to the given number.
Now that that is out of the way, lets tackle the actual problem
To get you started, you'll have to run some sort of loop (maybe use a do-while loop?), and probably best to do it inside some sort of method. You'll need to have a counter if your dice don't add up to the target roll again and increase the counter until your roll adds up to the target, then return that value of the counter
define rolls needed(target)
initialize counter as 0
initialize sum
do this loop
increase your counter
roll your dice
add results together
while sum does not equal target
return your counter
end
Related
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 14 days ago.
This post was edited and submitted for review 14 days ago.
Improve this question
I was working trying to generate a random number the other day. The assignment is basically that, given an array with names, I was gonna log names on the console at random. I tried to generate a random number that is gonna help accessing the names working as the index of the elements (e.g., array[random_number_as_index]).
My confusion started when storing the method Math.random() in a variable and accessing that same variable, the result was the exact same number over and over. My line of code looks something like this.
const randomNumber = Math.floor(Math.random()*10));
Whereas when part of a function, e.g.,
function randomNum () {return Math.floor(Math.random()*10));}
would actually generate a random number every time the function is invoked. My expectation was that, upon accessing the variable, a random number was gonna be generated every single time, which was not the case, and only works if it is within a function.
const randomNumber = Math.floor(Math.random()*10));
Generates a random number, then assigns that random number to randomNumber.
randomNumber is a constant variable (meaning its value cannot be changed after the fact).
You're generating one random number, then saving it in a variable.
function randomNum () {return Math.floor(Math.random()*10));}
Defines a function that returns a random number when called.
Each invocation of randomNum generates a new random number.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to write a function that given an array like
var a = [
0.0015974718789698097
,0.755383581038094
,0.13950473043946954
,0.0011978091842754731
,0.005126875727346068
,0.0042250281407886295
,0.0001720958819913952
,0.0047584144830165875
,0.0835073272489086
,0.00016098907002300275
,0.0028037075787230655
,0.0014378579473690483
,0.00012411138102484662
]
or
var a = [
0.33333333333333333
,0.33333333333333333
,0.33333333333333333
]
or
var a = [
0.166666666666666
,0.166666666666666
,0.3
,0.3333333333333333
]
It round each number to 3 decimal places while keeping the sum of all the values is still equal to 1.0.
The way I imagine it would do this is by taking the difference of the new sum and the expected sum and distribute the difference while maintaining the relative distribution as close as possible. I can only think of an iterative approach and wanted to see what other solutions people can come up with
It's important to notice that the very last value of 0.00012411138102484662 will round to 0.000 but that doesn't it mean it should never get a piece of the difference, because the distribution it wants to maintain is the unrounded distribution, not the current distribution after rounding to 3 decimal places nor after iteration of balancing
If you are planning on rounding each of the values in the array to the 3rd decimal and adding them all up, Then here's what you need to do. You will need to get each number of the array into a loop and make that number to the fixed 3rd decimal by doing .toFixed(3) and parsing that to a float and adding it to a variable which will loop and the variable's value will change. Like this:
var int = 0;
a.forEach(number => { int += parseFloat(number.toFixed(3)) })
int // 1
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this code to add elements to my table and that part works perfectly fine. However, I want to add up the values of the last column in order to later print that on another part of the page. parseInt doesn't work for some reason (the values don't come back as integers and stay as strings, is there anything I have done wrong? Again, adding to the table works perfectly fine.
var hourC = 0;
var hourC =+ parseInt($(".hourCount").text(), 10);
alert(hourC);
Edit:
When I print the values of the variable hourC they don't add up to the previous value, they just stay next to each other. Example: 1 + 1 = 11 rather than 2. I don't see where my issue is and the answer for debugging didn't help since I still got the same result.
Final Edit:
I achieved what I wanted now through a different medium, I created an array and pushed the values into the array and then I used "join" to solve the issue.
If interested in what I was asking for here is a fiddle with the final result. (You can just change the console.log to alert)
Basic debugging skills.
parseInt works -- its a well tested function. If it broke in a browser, a lot of people would notice.
However, you haven't given any way to figure out what is going on with your code, since the real problem MUST be here:
$(".hourCount").text()
That must not contain whatever value you think it does.
Split your code up and use the debugger, or even console log, to see what the values are.
var hourC = 0;
var strValue = $(".hourCount").text();
alert(["strValue = ", strValue]);
hourC = parseInt(strValue, 10);
alert(hourC);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Struggling to get my head around the logic/syntax needed here, so hoping someone cleverer than me can help :-)
I'm trying to replicate the functionality of the 'Bedrooms' slider shown here: https://www.redrow.co.uk/search?utf8=%E2%9C%93&category=&item_id=&search_type=text&advanced_search=true&term=birmingham&x=0&y=0&distance=20&min-beds=1&price-min=0&price-max=100000000&house_type=
You'll see that a search brings back a list of property developments which have various attributes, one of which is the number of bedrooms houses in that development could have, eg. "2, 3 & 4 bedroom homes" or "1, 3 & 4 bedroom homes".
In the search filters at the top of the page there is a 'Bedrooms' slider. The maximum value is fixed to 6+ but the minimum value is user selectable. So when the slider handle is on, say '3', that filters down to all developments with properties that have 3 bedrooms or more. The part I'm having trouble with is that a development - as an example shown in the results above, let's say the 'Chestnut Walk' development - has 3 and 4 bedroom properties, but it also has 2 bedroom properties which would be filtered out by placing the slider at '3'.
In my JSON object I have an array of available bedrooms for each development, so for example a development with "2, 3 & 4 bedroom homes" would have an array of ['2','3','4']. What I think I need to do is check if any of the values in the array fall within the minimum and maximum number of bedrooms as per the slider - but as a bit of a JS novice I can't for the life of me work out how I would do that efficiently. Can anyone help?!
if you have the minLimit as the minimum number of rooms selected in slider then :
for(var i=0; i<noOfRoomsArray.length; i++){
if(noOfRoomsArray[i] >= minLimit){
//this is a valid choice of client
}
}
You can use the js math function min() and max() on arrays.
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 9 years ago.
Improve this question
I've made this small tool but I'm not sure how to achieve what I need.
I would like it to subtract from the "Points Left" when adding to the others.
(Not going below zero into the negative, only 30 points).
I would also like to prevent going BELOW the initial numbers in "Weapon Power" and "Magic Power".
(I would like to be able to only spend a maximum of 25 points into one "power")
I think it kind of explains itself so maybe I'm just confusing you more.
Any ideas?
DEMO
You need to give your number input elements distinct ids, because when you do document.getElementById, it will only return you the first element with the given ids.
Then, you need to give another distinct ID to the "points left" field for each character, and update that one. To do that, you'll need to pass to add and substract the correct value ( add(warrior, 'weapon'), add(wizard, 'magic')).
You need to be able to get your IDs from your warrior or wizard object, so you could try doing this:
var wizard = {
weapon:"idOfWeaponField", magic:"idOfMagicField", points:"idOfPointsField"
};
where the string values are the ids of your elements.
Then, within your add function, you can access your id like this
function add(character, statName){
var myID = character[statName];
}
and update the correct input value.
EDIT: code here.
I would also like to prevent going BELOW the initial numbers in "Weapon Power" and "Magic Power". >(I would like to be able to only spend a maximum of 25 points into one "power")
Basically, you've seen what I did with the points left, when I said if(pointsVal.value == 0) return; ? You should be able to implement any constraint you like using that.
I modified mine to give an example where the limits are at their initial values.
If you only want to spend a given number of points on one of the powers, you'll have to substract the limit from the current number and return from add() without changing the value if the number exceeds the threshold. That should be pretty easy with what you have now, since you don't have to change the character object to do it.