I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Related
var oneX = eval(prompt ("What's the x variable of the first set of points"));
var oneY = eval(prompt ("What's the y variable of the first set of points"));
var twoX = eval(prompt ("What's the x variable of the second set of points"));
var twoY = eval(prompt ("What's the y variable of the second set of points"));
console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);
var yRes = twoY-oneY;
var xRes = twoX-oneX;
console.log(yRes);
console.log(xRes);
var slope = xRes/yRes;
console.log("The slope is " + yRes + "/" + xRes);
This is my code. This is what the output looks like:
0.9166666666666666
0.8
2.09375
0.5714285714285714
-0.22857142857142865
1.1770833333333335
The slope is -0.22857142857142865/1.1770833333333335
However, I don't want -.22/1.177 I want -33/7 (I don't know the exact answer) I've never posted on StackOverflow before, so if I did something stupid while typing, I apologize. I'm new to programming so don't be too harsh.
The easiest way would be rounding to a certain fraction, e.g:
Math.round( slope * 10 ) + "/10"
What you're talking about is simplifying a ratio. First you multiply each number by the least common multiple to get them both into whole numbers, then divide each number by the greatest common factor to reduce them.
A full explanation of the process with examples: https://www.tutorialspoint.com/ratios_and_unit_rates/simplifying_ratio_decimals.htm
I would like to perform some calculations on an ee.Image pixel by pixel, however, the result calculated must obey a probabilistic Gaussian distribution, so some pixels will be modified and others not. I already coded a probabilistic function but I don't know how to apply it to each pixel in GEE. Is there any way to do that?
I already tried something like the following, but the same random number is used for every pixel, and that is not what I want.
Trial 1)
var result = img.where(img.lte(32 + Math.floor((Math.random() * 10) + 1)),1);
Trial 2)
var result = img.expression(
'(B1 > 32 + P) ? 1', {
'P': Math.floor((Math.random() * 10) + 1),
'B1': img.select('B1')});
Trial 3)
var result = img.expression(
'P > 10 ? 1', {
'P': MyProbabilisticFunction(),
'B1': img.select('B1')});
I also tried to use the following to generate a "probabilistic" image to perform my calculations but, since I have several classes in the same raster, the probability of the "event" is not quite right.
Trial 4)
var rd = ee.FeatureCollection.randomPoints(geometry,1000,Math.floor((Math.random() * 10) + 1));
var prob = rd.draw('000000',5,0).select('vis-red');
var result = img.where(prob.eq(0),1);
You can generate a random value per pixel using ee.Image.random().
That said, the rest of Earth Engine doesn't work the way you're attempting to use it. All image functions are "vectorized"; you don't ever get to work "pixel by pixel".
I am trying to develop the addition program using column addition in javascript, For e.g: 53,22 , we add numbers from the right 3+2 and 5+2 finally results in 75, the main problem is with large numbers i am trying to develop a program which can implement addition of large numbers.so that i don't get gibberish like 1.26E+9, when adding large numbers. i tried doing it by defining the code like below
function add(a,b)
{
return (Number(a) + Number(b)).toString();
}
console.log(add('58685486858601586', '8695758685'));
i am trying to get the added number without getting the gibberish like 5.8685496e+16
You can add them digit by digit.
function sumStrings(a, b) { // sum for any length
function carry(value, index) { // cash & carry
if (!value) { // no value no fun
return; // leave shop
}
this[index] = (this[index] || 0) + value; // add value
if (this[index] > 9) { // carry necessary?
carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go on
this[index] %= 10; // remind me later
}
}
var array1 = a.split('').map(Number).reverse(), // split stuff and reverse
array2 = b.split('').map(Number).reverse(); // here as well
array1.forEach(carry, array2); // loop baby, shop every item
return array2.reverse().join(''); // return right ordered sum
}
document.write(sumStrings('58685486858601586', '8695758685') + '<br>');
document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');
I would keep all values as numbers until done with all the calculations. When ready to display just format the numbers in any way you want. For example you could use toLocaleString.
There are several libraries for that
A good rule of thumb is to make sure you do research for libraries before you actually go ahead and create you're own proprietary implementation of it. Found three different libraries that all solve your issue
bignumber.js
decimal.js
big.js
Example
This is how to use all three of the libraries, BigNumber coming from the bignumber.js library, Decimal from decimal.js and Big from big.js
var bn1 = new BigNumber('58685486858601586');
var bn2 = new BigNumber('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Decimal('58685486858601586');
bn2 = new Decimal('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Big('58685486858601586');
bn2 = new Big('8695758685');
console.log(bn1.plus(bn2).toString());
The console's output is :
58685495554360271
58685495554360271
58685495554360271
I'm trying to understand how to user parseFloat to convert a string to a number--which by the way changes based on a users rewards club points.
Here's the code I've written so far:
var ptsBalance = jQuery('.value.large.withCommas').text(); // get current RC points balance
var strParse = parseInt(ptsBalance, 10); // * Output should be current RC balance
alert(strParse); // alert Rewards Club Balance
var bonusPoints = 70000;
var totalPts = jQuery(strParse + bonusPoints); // sum total of Bonus and Current points
jQuery(strParse).appendTo('.currentPts');
jQuery(totalPts).appendTo('.totalPts'); // insert RC points balance after 'Current Points' text
Clearly I'm not using pareFloat, but rather strParse, which is rounding my string. That said, how do I convert a string to a number that could be "10", "100", "1,000", "10,000" etc.?
Here's a link to my Fiddle: http://jsfiddle.net/bkmills1/60vdfykq/
Still learning...
Thanks in advance!
In your fiddle, change line 4 from:
var strParse = parseInt(ptsBalance, 10);
to
var strParse = parseInt(ptsBalance.replace(',',''), 10);
You may also want to remove any other symbols needed, or even use regular expressions to do just that.
I want to implement a saving system similar to Imgur where if a user presses a button a unique 5 character value is returned. Here is what I have so far:
The database backend uses auto-incrementing ID's starting at 5308416. I use a modified Radix function (see below) to convert these numerical ID's into characters. I use a reverse function to lookup character ID's back to numerical database ID's.
function genID (value)
{
var alphabet = "23456789BCDFGHJKLMNPRSTVWXYZbcdfghjkmnpqrstvwxyz";
var result = "";
var length = alphabet.length;
while (value > 0)
{
result = alphabet[value % length] + result;
value = Math.floor (value / length);
}
return result;
}
The problem is that these generated ID's are very much predictable. My question is, how can I make the generated ID's seem random but still unique (so I can look them up in the database as numbers). I was thinking of using some encryption algorithm but not sure where to start. Any help or suggestions would be appreciated (maybe there is a better way of doing this also).
Do you have to be able to go both ways (i.e. convert an integer to it's hash and back again)? If you can store the hash and lookup the content that way, then it's relatively easy to create a function that produces a hard-to-guess, but complete hash space. You use primes to generate a sequence that only repeats once all possible permutations are exhausted.
The following PHP example is from my own code, adapted from this site:
function hash($len = 6) {
$base = 36;
$gp = array(1,23,809,28837,1038073,37370257 /*,1345328833*/);
$maxlen = count($gp);
$len = $len > ($maxlen-1) ? ($maxlen-1) : $len;
while($len < $maxlen && pow($base,$len) < $this->ID) $len++;
if($len >= $maxlen) throw new Exception($this->ID." out of range (max ".pow($base,$maxlen-1).")");
$ceil = pow($base,$len);
$prime = $gp[$len];
$dechash = ($this->ID * $prime) % $ceil;
$hash = base_convert($dechash, 10, $base);
return str_pad($hash, $len, "0", STR_PAD_LEFT);
}
It would be easy enough to implement that in JavaScript, but ideally you wouldn't need too - you'd have an insert trigger on your table that populated a hash field with the result of that algorithm (adapted for SQL, of course).
A non-predictable, but unique ID can be made by combining your server-side auto-incrementing number with either a current date/time nugget or with a random number. The server-side auto-incrementing number guarantees uniqueness and the date/time nugget or random number removes the predictability.
For a unique ID in string form that takes the server-side unique number as input and where you add the date/time nugget on the client you can do this:
function genID(serverNum) {
return(serverNum + "" + (new Date).getTime());
}
Or using a random number:
function genID(serverNum) {
return(serverNum + "" + Math.floor(Math.random() * 100000));
}
But, it might be best to add the date/time element on the server and just store that whole unique ID in the database there.