beginner: rolling a dice: frequency and if-else-if? - javascript

How do I show the frequency with which each face of the dice finishes uppermost?
//this program stimulates rolling a dice
var outputAreaRef = document.getElementById("outputArea");
var array=[0, 1, 2, 3, 4, 5, 6];
var i=1;
var outString="";
while (i<60000)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
i++;
}
outputAreaRef.innerHTML = " array: " + array ;

I see what you are trying to do and it may be easier to explain here.
You have a couple of issues. Your array should 6 in length, not 7 and all values MUST start with 0 or you will receive a false positive. If Zero is really One then you modify when you output, don't put it in your logic.
The method is correct to increment but the random number should be 0-5.Ultimately you could loop and output or use the console. Console is a far better way to check and debug your code than DOM injection.
If you don't know anything about it please take a look :-)
Chrome DevTools
var array=[0,0,0,0,0,0];
var i=1;
while (i<60000)
{
var number=Math.floor(Math.random()*6);
++array[number];
i++;
}
console.table(array)

It looks like you were just missing the output syntax. You'll need to output each index of your array, followed by its value. Try this:
//this program stimulates rolling a die
var outputAreaRef = document.getElementById("outputArea");
var array=[0, 1, 2, 3, 4, 5, 6];
var i=1;
var outString="";
while (i<60000)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
i++;
}
for(var i = 0; i < array.length; i++)
{
outputAreaRef.innerHTML += i + ": " + array[i] +"<br />";
}

If what I think you're looking for is correct, then this will do it. I changed some of the code to my own preference of how to accomplish this, but the concepts are the same. If you keep using an array, then you can use forEach to iterate through it.
var array = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0 };
iterations = 60000;
for (var i = 0; i < iterations; i++)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
}
document.getElementById("outputArea").innerHTML = " array: " + JSON.stringify(array) ;
for( var k in array ) {
array[k] = Math.round((array[k] / iterations) * 1000)/1000;
}
document.getElementById("frequencies").innerHTML = " array: " + JSON.stringify(array) ;
<div id="outputArea"></div>
<div id="frequencies"></div>

Related

JavaScript - Printing from Array of Objects Not Working

I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.

Changing div to lines with java script

The "output" div should be replaced with 10 lines of output. Each
line should display two numbers separated by a space. The first number should be the line number starting
with 1. So the numbers 1, 2, 3, 4... and so on. The second number should be the factorial of the line number.
(n factorial is 1 * 2 * 3 * ... * n.) That is, the numbers 1,
What should i use to create the list and to do the calculations. Tried using an array but was having difficulties in making the calculations. Any help would be appreciated
Check this one and try it
var result = '';
var lineno = 10;
for(j=1;j<=lineno;j++){
result = result + j + ' ' + fact(j) + '<br>';
}
document.getElementById("output").innerHTML = result;
function fact(n){
var i, no, fact;
f=1;
for(i=1; i<=n; i++)
{
f= f*i;
}
return f;
}
Link : https://jsfiddle.net/yrz46q85/
Counting factorial to 10 in 10 lines.
var output = document.getElementById("output");
var factorial = 1;
for(var i=1; i<=10; i++){
factorial = factorial * i;
output.innerHTML += i +". " + factorial + "</br>";
}
<div id="output"></div>

Fastest bulk insert into javascript arrays

I wanted to check to see which was faster in adding elements to an array in javascript:
Adding a list of 5 per iteration
Adding 5 single items with adding position to the subscript
Adding one single item pr iteration
I ran it on my Linux Mint 16, Firefox 37.0.2
1 and 2 turned out much better than 3.
When I ran it 1,000,000 times 1 was noticably better than 2.
However when I ran it 10,000,000 the results were reversed. What would be the explanation for that?
var amount = 1000000;
var iter = 11;
var a = new Array(amount);
var b = new Array(amount);
var results = [];
for (j=1; j<iter; j++) {
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = [2,2,2,2,2];
}
results.push("quintuple primitive insert attempt " + j + " took " +
eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i+=5) {
a[i] = 2;
a[i+1] = 2;
a[i+2] = 2;
a[i+3] = 2;
a[i+4] = 2;
}
results.push("single primitive insert with inline inc attempt " + j +
" took " + eval(new Date().getTime() - clock) + "ms");
var clock = new Date().getTime();
for (i=0; i< amount; i++) {
a[i] = 2;
}
results.push("single primitive insert with single iterator attempt " +
j + " took " + eval(new Date().getTime() - clock) + "ms");
}
The code is demonstrated here:
http://jsfiddle.net/lash/cL3wewj4/
(I also tried using homogenous and heterogenous arrays to insert content, in which 2 always was the best. The attempt is in the same jsfiddle source, commented out)
You're taking times of things that are not the same:
First off, you're taking times of creating a matrix whose elements at position i%5 = 0 contain an array of five elements. The rest of the elements (i%5 != 0) are undefined. This array has a length that depends on amount due to the fact that you're adding to the variable i five in each iteration and some elements at the end of the array might not be initialized (directly or indirectly).
for (i = 0; i < amount; i += 5) {
a[i] = [2, 2, 2, 2, 2];
}
Secondly, you're creating an array whose elements are all equal to 2.
for (i = 0; i < amount; i += 5) {
a[i] = 2;
a[i + 1] = 2;
a[i + 2] = 2;
a[i + 3] = 2;
a[i + 4] = 2;
}
Thirdly, you're doing the same as two.
for (i=0; i< amount; i++) {
a[i] = 2;
}
Since one is different than 2 and 3 the results don't make sense.

Why does the sort() function changes values of numbers in this Array?

var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:" ;
var _array = ["un", "deux", "trois"] ;
var _items = new Array();
for (var t =0; t < _array.length; t++) {
found = _txtString.match(new RegExp(':' + _array[t]+ ':', 'g'));
_items[t] = parseInt(found.length);
//_items.sort();
document.write("<br />" + _items[t] + " " + _array[t]);
}
Hi,
when I run this code, results displayed are properly counted:
2 un
3 deux
2 trois
But when I uncomment the sort() line, count is wrong:
2 un
3 deux
3 trois <=
What I wanted is to sort the result returned by numeric value. What is beyound my understanding is that the sort() function changes the actual value ?! Any clue why ?
Thanks
Because you are sorting, you are changing the order of the array. So when you sort the "3" becomes the last index and it writes that out.
_items[t] = parseInt(found.length); //[2,3,2]
_items.sort(); //[2,2,3]
document.write("<br />" + _items[t] + " " + _array[t]); //here you are reading the last index which is 3
If you want to sort by the count, you need to do it after you calculate everything.
Basic idea:
var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:";
var _array = ["un", "deux", "trois"];
var _items = new Array();
for (var t = 0; t < _array.length; t++) {
found = _txtString.match(new RegExp(':' + _array[t] + ':', 'g'));
_items.push({
count: found.length,
text: _array[t]
});
}
_items.sort(function (a, b) {
return a.count - b.count;
});
for (var i = 0; i < _items.length; i++) {
console.log(_items[i].count, _items[i].text);
}
The sort command in javascript does an in-place sort, meaning it will mutate your array order. When this occurs it simply looks to me like your code is just out of sync to what you are expecting.
There is no way to avoid this unless you make a copy of the array and do a sort on the copy therefore leaving the original array as-is.

(P)RNG - Array of Random Numbers Created with a Seed

I want to create an array of random/pseudo-random numbers using a seed. I want the very same array to be created when the same seed is used and I want to have little or no visible pattern in the array. I'm working in JavaScript.
This is the random function I'm using, which I'm quite happy with (sorry, I forgot who the original author is):
function random(seed) {
if (!seed) seed = new Date().getTime();
seed = (seed*9301+49297) % 233280;
return seed/(233280.0);
}
This is the array generation:
var superSeed = random();
var nRandom = 100;
var randomArray = new Array();
for (var i = 0 ; i < nRandom ; i++){
randomArray.push(random((superSeed*10)+ (i)));
}
Somehow the pattern seems to be quite similar, no matter how often I run it. This question seems to be similar, but since it's about matrixes, I don't understand what's being said.
Thanks!
Having worked on similar things before I think we can use a fairly simple series, which takes two initial values and then you can get a lot more.
var a1,b1;
function InitSequence(v1, v2) {
a1 = Math.pow(v1, 5) / Math.pow(v1, 3);
b1 = Math.pow(v2, 8);
lastrand = (a1 + b1) & 0x7fffffff;
}
function SequenceNext() {
var alast = a1;
var nextVal = (a1 + b1) & 0x7fffffff;
b1 = alast;
a1 = nextVal;
return nextVal;
}
Then use it like this:
InitSequence(75, 21);
for (var i = 0; i < 99; i++) {
v = SequenceNext();
}
I tested it like this:
var used = new Array();
InitSequence(75, 21); // any two values will do.
// fill 10k into array.
for (var i = 0; i < 9999; i++) {
v = SequenceNext();
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
//document.write(i+": "+v+"<br>");
}
// see if there any duplicates.
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
document.write("duplicated " + xx + " :" + ndup + "<br>");
tdup += ndup;
}
}
document.write("Total dups " + tdup + "<br>");
This is using the Fibonacci series, which in mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
. I'm starting with different values - (v1^5) / (v1^3) and v2 ^ 8; otherwise it would only ever be identical.
I like the "Super 7" PRNG. It is simple, fast (although the other answer with the fib. sequence is fast as well), and has the interesting property:
In the entire range -- albeit of a meager of 32k -- there are no duplicates using the "Super 7" PRNG.
Multiple 7's can be joined to increase the number of bits and/or provide multiple seeds. This non-duplication property can exposed or folded.
(The sequence of a PRNG is always the same given a starting seed: it's the distribution and cycle lengths that are interesting -- it is these properties that may make them ideal in different cases where "true randomness" isn't desired).
Happy coding.
Maybe you should try this
function s_random() {
s_random.m = 71402523; s_random.a = 409647; s_random.c = 1508892;
s_random.seed = (s_random.seed*s_random.a + s_random.c) % s_random.m;
return s_random.seed / s_random.m;
}
/*
generate IV
s_random.seed = Math.floor((new Date).getTime()/10000);
*/
s_random.seed = 130324232;
var CheckRandom = 4999999;
var PrintSamples = 100;
var used = new Array();
for (var i = 0; i < CheckRandom; i++) {
v = (Math.ceil(Math.sqrt(s_random())* 1000000000) * 8);
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
if ( i< PrintSamples) document.write(i+": "+v+"");
}
/* see if there are any duplicates. */
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
if (ndup < PrintSamples) document.write("duplicated " + xx + " :" + ndup + "");
tdup += ndup;
}
}
document.write("Total generated " + CheckRandom + "");
document.write("Total duplicates " + tdup + "");
Just got 5 million seeded, repeatable random numbers and no duplicates. Tested several times on Mac OS X with Safari.
Cheers,
Karl

Categories

Resources