Balance array of numbers to equal 1 [closed] - javascript

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

Related

Big O for a loop vs a javasccript method that solves a problem [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Find if the two arrays contain a similar property or value.
const one =[1,2,3,4,5]
const two = [5,6,7,8]
// a double loop that solves this problem
O(n^2)
VS
two.some(item => one.includes(item))
// this is more efficient than the double loop method
// but behind the scenes isnt javascript just looping ?
// why is this more performant ?
// and is the big O of this O(n)?
If your
a double loop that solves this problem
breaks out of the loops as soon as a match is found, then both methods are similarly inefficient - they both require iterating over all of N elements M times, worst-case, where N is the length of one array and M is the length of the other. (So, O(n * m), or O(n^2), depending on how you want to specify the lengths of the inputs.)
The advantage to the second method
two.some(item => one.includes(item))
is that it's a lot more readable than using for loops. It's not more performant - the opposite is true, for loops are generally faster than array methods.
If you wanted to reduce the complexity to O(n), instead of iterating over the second array inside a loop, use a Set lookup inside the loop, which is much faster:
const oneSet = new Set(one);
return two.some(item => oneSet.has(item));
because set lookup is sublinear, and generally O(1) - resulting in an overall complexity of O(n).

Convert from JavaScript v.splice(vi, 1) to Go [closed]

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 3 years ago.
Improve this question
I know nothing about JavaScript.
Assume that v contains a list of positive integers, vi is an index value, say current vi = 0.
I would like to know how to convert v.splice(vi, 1) to Golang
Is .splice() is equivalent to slices?
v.splice(vi, 1) removes 1 element from vi. To do the same in go, you can do:
append(v[:vi],v[vi+1:]...)
That is, first get the slice up to vi, then add all the elements after vi.
From : https://www.w3schools.com/jsref/jsref_splice.asp
Syntax
array.splice(index, howmany, item1, ....., itemX)
Parameter: index
Description. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
Parameter :howmany(Optional)
Description: The number of items to be removed. If set to 0, no items will be removed
Parameter:item1, ..., itemX (Optional)
Description: The new item(s) to be added to the array
You may visit https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_splice for trying it yourself

Pseudocode dice algorithm, need some guidance [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 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

Math method gives me the same number all over the time [closed]

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 7 years ago.
Improve this question
Recently i've been trying to do a repetitive random number in JS, but the problem is that always i have to reload the page to get a new random number, even i try to show it multiple times but the problem is that the number is the same until i refresh the page.
<?php
<script type="text/javascript" charset="utf-8">
function getNumber(){
var number = Math.random()
return number;
}
document.write(getNumber()); // NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
</script>
?>
I think it might be because you are using document.write. Use console.log instead and take a look at the console.
console.log(getNumber());
console.log(getNumber());
If you want your results in the browser get a reference to an element, or make and append one.
Math.random() returns a number between 0 and 1. Please read the docs for more information.
Rather than using document.write just update the content of your element like this:
function getNumber(){
var number = Math.random()
return number;
}
var div = document.getElementById('result');
div.innerHTML = getNumber();

Point Spending Tool - Difficulties [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 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.

Categories

Resources