Building a Custom RNG - javascript

I am building an app for people who like to play the lottery. The app will take in data from the user such as birthdays, street addresses, license plates, lucky numbers, times, etc. The user will fill their number diary with whatever they want. I will concatenate these strings of numbers into a solo string for each user.
I then will run the following function to get the frequency of each digit 0 - 9 as it appears in the string.
var digitFreq= function(numString){
zeros = numString.split("0").length-1
ones = numString.split("1").length-1
twos = numString.split("2").length-1
threes = numString.split("3").length-1
fours = numString.split("4").length-1
fives = numString.split("5").length-1
sixes = numString.split("6").length-1
sevens = numString.split("7").length-1
eights = numString.split("8").length-1
nines = numString.split("9").length-1
numbers = numString.length;
zeroPrcnt = zeros/numbers
onePrcnt = ones/numbers
twoPrcnt = twos/numbers
threePrcnt = threes/numbers
fourPrcnt = fours/numbers
fivePrcnt = fives/numbers
sixPrcnt = sixes/numbers
sevPrcnt = sevens/numbers
eightPrcnt = eights/numbers
ninePrcnt = nines/numbers
}
This will return the frequency % of each digit in the number string. My question is how do I take these frequencies and dynamically build an RNG that uses each user's personal frequency percentages when drawing a three digit, four digit, or mega lottery number?
The user will use their RNG to generate lottery numbers to play.

You could just concatenate all entries in one string and then randomly choose a character from that string. Each number would have a probability related to the number of times it appears in the string.

Related

How to write a java script for specific Test attempts

I am having a java scripts for a game, but this game is like a test and if the user failed the game he will retake the test (redo the game), but I want a specific number of attempts only for the user to re do the test. now what I have, makes the user start from the beginning without any limitations even if he re do it for like 100 times, he will keep go back to the beginning.
I need in the fail massage to give another attempt (form like max 4 attempts) if failed once then the next fail massage to give him 3 tries and then 2 and then last one, and then he can't redo the test.
Script 1;
var player=GetPlayer();
var textArray = [];
for (var i = 1; i <= 15; i++) {
textArray.push(i);
};
var itemsLeft = textArray.length;
textArray=textArray.map(String).toString();
player.SetVar("Text_Array", textArray);
player.SetVar("Items_Left", itemsLeft);
Script 2:
//get the StoryLine player
var player=GetPlayer();
//get Storyline variable value as a string
var textArray=player.GetVar("Text_Array");
//Convert string to a numeric array
numArray=textArray.split(",").map(Number);
//Get a random number from the array and send it to StoryLine
var randNum = numArray[Math.floor(Math.random() * numArray.length)];
player.SetVar("Random",randNum);
//Remove the random number from your array and get the array's length
numArray.splice(numArray.indexOf(randNum), 1);
var itemsLeft=numArray.length;
//Convert array to a string and send it back to SL along with the array's length
textArray=numArray.map(String).toString();
player.SetVar("Items_Left", itemsLeft);
player.SetVar("Text_Array", textArray);

VueJS: Computed Calculation Assistance

I need to be able to convert a string (IP address) such as this 10.120.0.1 to a string (ISIS Network ID) such as this 49.0001.0101.2000.0001.00. The middle section 010 1.20 00.0 001 corresponds to the first string (I've spaced them out to show the IP address is inside it). You can see that there are 4 digits in each ISIS Network ID hextet that need to correspond to 3 digits in the IP Address octet. A number of 53 for example would have a leading 0 to make 3 digits.
All the IP addresses start with 10.120. so I just need to inject the last 2 octets from the IP Address into the ISIS Network ID.
I need this to be dynamic so when someone types in another ip address into a loopbackIP input, it automatically updates the isisNetworkID field.
I have this:
49.0001.0101.{{ isisNetworkID }}.00
This needs to take the value from an input v-model="loopbackIP" that I have and translate the remaining values to sit in the middle of that isisNetworkID following this format - xxxx.xxxx.
I've got this computed calculation but I'm not sure how to make 4 digits equal 3...
const loopbackIP = '10.120.0.1';
const isisNetworkID = computed(() => {
let idaho = '10.120.';
if (loopbackIP.indexOf(idaho)) {
return loopbackIP.slice(7);
} else {
console.log('Nothing is happening');
}
});
I hope this makes sense...
I think I understand what you're trying to achieve. Let's break it down into digestible parts. You have an IP address of:
10.120.0.1
And you want to transform it such that each part is padded to 3 digits:
['010', '120', '000', '001']
This can be done by splitting the string by the . character, and the using String.prototype.padStart(). We then join the array back into a string:
'010120000001'
||||
^^^^ -> to be deleted
We know that the first 4 digits is not needed, since it's already part of your template, so we can remove them using String.prototype.substring(4). That leaves us with:
'20000001'
Now it is just the matter of splitting it into 4 characters per item:
['2000', '0001']
...and rejoining it with . character:
'2000.0001'
...and interpolating it back into the string. I have a proof-of-concept example below, which should output the desired string:
const loopbackIP = '10.120.0.1';
const parts = loopbackIP.split('.').map(x => x.padStart(3, '0'));
// Remove the first 4 characters
let isisNetworkId = parts.join('');
isisNetworkId = isisNetworkId.substring(4);
const output = `49.0001.0101.${isisNetworkId.match(/.{4}/g).join('.')}.00`;
console.log(output);
So if you want to translate it to your VueJS code, it should look no different that this:
const loopbackIP = '10.120.0.1';
const isisNetworkID = computed(() => {
const loopbackIP = '10.120.0.1';
const parts = loopbackIP.split('.').map(x => x.padStart(3, '0'));
let isisNetworkId = parts.join('');
isisNetworkId = isisNetworkId.substring(4);
// Rejoin, split into items of 4-character long, rejoin by period
return isisNetworkId.match(/.{4}/g).join('.');
});

How to pick a corresponding array entry given a randomly selected value

I'm trying to make a story generator for future playthroughs of some of my favourite games. To this end, I want to be able to randomly pick a combat style from an array (which I have succeeded in), but then also pick a corresponding explanation of that style to display in a paragraph.
I have:
function randomValueFromArray(array){
return array[Math.floor(Math.random()*array.length)];
}
function result() {
var jobItem = randomValueFromArray(insertJob);
document.getElementById('jobDisplay').innerHTML = jobItem;
var newStory = storyText;
var jobexpItem = randomValueFromArray(insertJobexp),
yItem = randomValueFromArray(insertY),
zItem = randomValueFromArray(insertZ);
newStory = newStory.replace(':insertJob:', jobItem);
newStory = newStory.replace(':insertJobexp:', jobexpItem);
newStory = newStory.replace(':inserty:', yItem);
newStory = newStory.replace(':insertz:', zItem);
}
referring to my arrays, containing lists of potential characteristics.
The jobItem selected might be number 10 on a list of 30. I want to then select entry number 10 in the jobexpItem array, which is an explanation of the entry selected in jobItem. These are listed in different areas for simplicity - I have a table with only the basic descriptors, and a paragraph with explanations included (where the storyText is displayed).
At the moment, I have jobexpItem as a random value just for troubleshooting. How would I link jobexpItem's value to the corresponding random jobItem value chosen?

Masking credit card number if a CC number entered

var cardNumber = '4761640026883566';
var cardNumberDashed = '4761-6400-1234-2345';
var cardNumberSpaced = '4761 6400 1234 3523';
var ensureOnlyNumbers = R.replace(/[^0-9]+/g, '');
var maskAllButLastFour = R.replace(/[0-9](?=([0-9]{4}))/g, '*');
var hashedCardNumber = R.compose(maskAllButLastFour, ensureOnlyNumbers);
document.body.innerHTML = hashedCardNumber(cardNumber) + '<br/>' +
hashedCardNumber(cardNumberDashed) + '<br/>' +
hashedCardNumber(cardNumberSpaced);
My situation is a bit complicated, I have a <textarea> that I use as a message field in a chat window. I want to mask all credit card numbers that was sent on this chat, but NOT every number, because I do need a membership numbers from clients which is 10-15 digits numbers.
<textarea id="postMessage"></textarea>
I followed the code in this jsfiddle: http://jsfiddle.net/7odv6kfk/ but it works only on input fields that have credit card numbers.
How can I do that?
Thank you!
http://jquerycreditcardvalidator.com/
this library may help you it can detects only credit card number and avoid other numbers
var result = $('#cardnumber').validateCreditCard({ accept: ['visa', 'mastercard'] })
Here you can find valid CC number formats and regular expressions matching them:
http://www.regular-expressions.info/creditcard.html
The problem is that old VISA cards have 13 digits, American Express have 15 digits and some JCB cards have 15 digits. This conflicts with your membership numbers. Do you need to support 16-digit CC numbers then?
The following code shows how to replace 16-digit CC numbers with asterisks:
var re = /\b(\d[ -]?){15}\d\b/g;
var text = "My CC number is 4761640026883566 (or 4761-6400-1234-2345, or 4761 6400 1234 3523). My membership number is 1234567890123."
document.body.innerHTML = text.replace(re, "****");
Output:
My CC number is **** (or ****, or ****). My membership number is 1234567890123.

Split an IP address into Octets, then do some math on each of the Octets

I actually have this working, but its very ugly, and its keeping me awake at night trying to come up with an eloquent piece of code to accomplish it.
I need to take a series of strings representing IP Ranges and determine how many actual IP address that string would represent. My approach has been to split that into 4 octets, then attempt to split each octet and do the math from there.
e.g.: 1.2.3.4-6 represents 1.2.3.4, 1.2.3.5, and 1.2.3.6, thus I want to get the answer of 3 from this range.
To further complicate it, the string I'm starting with can be a list of such ranges from a text box, separated by newlines, so I need to look at each line individually, get the count of represented IP address, and finally, how many of the submitted ranges have this condition.
1.1.1.4-6 /* Represents 3 actual IP Addresses, need to know "3" */
2.2.3-10.255 /* Represents 8 actual IP Addresses, need to know "8" */
3.3.3.3 /* No ranges specified, skip this
4.4.4.4 /* No ranges specified, skip this
Net result is that I want to know is that 2 lines contained a "range", which represent 8 IP addresses (3+8)
Any eloquent solutions would be appreciated by my sleep schedule. :
)
There you go:
var ips = ["1.2.3.4", "2.3.4-6.7", "1.2.3.4-12"];
for(var i=0; i<ips.length; i++) {
var num = 1;
var ip = ips[i];
var parts = ip.split('.');
for(var j=0; j<parts.length; j++) {
var part = parts[j];
if(/-/.test(part)) {
var range = part.split('-');
num *= parseInt(range[1]) - parseInt(range[0]) + 1;
}
}
alert(ip + " has " + num + " ips.");
}​
This code also handles ranges like 1.2.3-4.0-255 correctly (i.e. 256*2=512 ips in that range). The list items that have no ranges yield a total of 1 ips, and you can ignore them based on the resulting num if you don't need them.
You'll probably need to slightly modify my example, but I'm confident you won't have any trouble in doing so.
Ok, this is how I would do it
var addr = '1.1.3-10.4-6';
function getNumAddresses(input) {
var chunks = input.split('.');
var result = 1;
for (var i = 0; i < 4; i++) {
if (chunks[i].indexOf('-') != -1) {
var range = chunks[i].split('-');
result *= parseInt(range[1]) - parseInt(range[0]) + 1;
}
}
return result;
}
alert(getNumAddresses(addr));

Categories