Showing posts with label Numbers. Show all posts
Showing posts with label Numbers. Show all posts

Friday, April 1, 2011

Lottery Number Function

Again following from a previous discussions on generating unique random numbers within a range, here's a quick function you can use when the range starts from 1, just as most lottery draws do.

var getRandomLottoNumbers = function (m:Number, n:Number):Array {
m==undefined?m=6:m=m
n==undefined?n=49:n=n
for(var v=[];m;--n)Math.random()*n>m?0:v[--m]=n;return v
}

Using it is quite straightforward. Just pass two arguments to the function - the number of selections you want to make (m), and the total numbers you are selecting from (n). If you omit the arguments, the function will default to selecting 6 random numbers from a total of 49:

// generate 3 random numbers between 1 and 10
trace(getRandomLottoNumbers(3, 10));
// generate 6 random numbers between 1 and 49 (default)
trace(getRandomLottoNumbers());

Friday, July 17, 2009

Generate unique random numbers within a range

Following on from a previous post on how to generate a list of unique random numbers, this similar function will allow you to do the same...but within a predefined range of numbers:

function randListFromRange(firstNo:Number, lastNo:Number, num:Number, shuffled:Boolean):Array {
var tempArray:Array = [];
for (i = firstNo - 1; i < lastNo && num > 0; ++i) {
if (Math.floor(Math.random() * (lastNo - i)) < num) {
tempArray.push(i + 1);
num--;
}
}
if (shuffled) {
tempArray.sort(function () {
return Math.floor(Math.random() * 2) ? true : false;
});
}
return (tempArray);
}

To use this function, just provide the first and last numbers in your range, and the number of items you wish to generate from that list. For example, you might want to create an array of 7 unique random numbers that lie between 36 and 83:

// to generate an array of 7 unique sequential numbers
// between, and including, 36 and 83
var myArr:Array = randListFromRange(36, 83, 7);
trace(myArr);

As previously, the function still allows for the list of random numbers to be shuffled:

// to generate an array of 7 unique shuffled numbers
// between, and including, 36 and 83
var myArr:Array = randListFromRange(36, 83, 7, true);
trace(myArr);

Two points to note:
1. If your first number is greater than your last number, then no random numbers will be generated. For example:

var myArr:Array = randListFromRange(20, 10, 5);
trace(myArr); // outputs nothing

2. If the specified range is smaller than the desired number, the function will return every integer within that range. For example:

// attempt to generate an array of 10 unique shuffled numbers
// between, and including, 10 and 15
var myArr:Array = randListFromRange(10, 15, 10);
trace(myArr); // outputs 10, 11, 12, 13, 14, 15

Sunday, March 1, 2009

Generating a list of unique random numbers

Here's a useful function for generating a list of N random numbers from a larger list M:

function randList(max:Number, num:Number, shuffled:Boolean):Array {
var tempArray:Array = [];
for (i = 0; i < max && num > 0; ++i) {
if (Math.floor(Math.random() * (max - i)) < num) {
tempArray.push(i + 1);
num--;
}
}
if (shuffled) {
tempArray.sort(function () {
return Math.floor(Math.random() * 2) ? true : false;
});
}
return (tempArray);
}

Just provide the maximum number (M) in your list and the number of items (N) you wish to generate from that list:

// to generate an array of 10 unique sequential numbers
// between 1 and 10
var myArr:Array = randList(10, 10);
trace(myArr);
// to generate an array of 5 unique sequential numbers
// between 1 and 100
var myArr:Array = randList(100, 5);
trace(myArr);

Finally, the function also allows for the list of N random numbers to be shuffled:

// to generate an array of 10 unique shuffled numbers
// between 1 and 10
var myArr:Array = randList(10, 10, true);
trace(myArr);
// to generate an array of 5 unique shuffled numbers
// between 1 and 100
var myArr:Array = randList(100, 5, true);
trace(myArr);

Sunday, November 30, 2008

Rounding numbers

Previous posts touched on the subject of formatting numbers; either as formatting currency or separating with commas and two decimal places. Another question that's frequently asked is how to round to different numbers of decimal places?

The standard answer is to use powers of 10 as per the following examples. To round to two decimal places use:
roundedNumber =  Math.round(yourNumber * 100)/100;

For three decimal places, use:
roundedNumber =  Math.round(yourNumber * 1000)/1000;

However, an easier way is to create a quick function to perform the work for you:

function roundDecimal(num:Number, places:Number):Number {
// defaults to two decimal places
if (places == null) {
places = 2;
}
power = Math.pow(10, places);
return Math.round(num * power) / power;
}

Use it as follows:

trace(roundDecimal(3.14159265358979, 5)); // Outputs 3.14159
trace(roundDecimal(3.14159265358979, 3)); // Outputs 3.142

Wednesday, August 6, 2008

Formatting currency

Following on from the previous entry about formatting numbers, it's a simple task to convert the same function into one that accepts currency symbols:


function formatCurrency(num:Number, comma:Boolean, currency:String):String {
// return a zero value if num is not valid
if (isNaN(num)) {
return "0.00";
}
// return a blank value if currency is not valid
if (currency == undefined) {
currency = "";
}
// round num to the nearest 100th
num = Math.round(num * 100) / 100;
// convert num to a string
var num_str:String = String(num);
// seperate any decimals from the whole numbers
var num_array = num_str.split(".");
// if there are no decimals add them using "00"
if (num_array[1] == undefined) {
num_array[1] = "00";
}
// if the decimals are too short, add an extra "0"
if (num_array[1].length == 1) {
num_array[1] += "0";
}
// separate whole numbers with commas
// if required (comma = true)
if (comma) {
var whole_array:Array = new Array();
var start:Number;
var end:Number = num_array[0].length;
while (end > 0) {
start = Math.max(end - 3, 0);
whole_array.unshift(num_array[0].slice(start, end));
end = start;
}
num_array[0] = whole_array.join(",");
}
// construct a return string joining
// the whole numbers with the decimals
// and prefixing a currency symbol
return (currency + num_array.join("."));
}
trace(formatCurrency(1234.5, true, "£"));
// outputs £1,234.50
trace(formatCurrency(1234.5, true, "\u00a5"));
// outputs ¥1,234.50

Formatting numbers

This one comes up a lot - how to format a number with commas and decimal points? Just pass your number into this function and it will return a formatted string. Including commas is optional.


function formatNumbers(num:Number, comma:Boolean):String {
// return a zero value if num is not valid
if (isNaN(num)) {
return "0.00";
}
// round num to the nearest 100th
num = Math.round(num * 100) / 100;
// convert num to a string
var num_str:String = String(num);
// seperate any decimals from the whole numbers
var num_array = num_str.split(".");
// if there are no decimals add them using "00"
if (num_array[1] == undefined) {
num_array[1] = "00";
}
// if the decimals are too short, add an extra "0"
if (num_array[1].length == 1) {
num_array[1] += "0";
}
// separate whole numbers with commas
// if required (comma = true)
if (comma) {
var whole_array:Array = new Array();
var start:Number;
var end:Number = num_array[0].length;
while (end > 0) {
start = Math.max(end - 3, 0);
whole_array.unshift(num_array[0].slice(start, end));
end = start;
}
num_array[0] = whole_array.join(",");
}
// construct a return string joining
// the whole numbers with the decimals
return (num_array.join("."));
}
trace(formatNumbers(1234));
// outputs 1234.00
trace(formatNumbers(1234.56));
// outputs 1234.56
trace(formatNumbers(1234.5, true));
// outputs 1,234.50
trace(formatNumbers(-1234.56789, true));
// outputs -1,234.57

Monday, August 4, 2008

Numbers to words in Flash

It is sometimes necessary to convert a given number into its equivalent value in words.

At first this might appear to be a daunting and complex task but, fortunately, the method for formulating spoken numbers in English can be broken down into a set of simple rules. These rules are then applicable for any number, regardless of its size:

  1. if the number value is zero then the number in words is 'zero' and no other rules apply.
  2. all numbers can be split into groups of three digits starting from the right-hand side. Each group of three digits can then be processed individually to obtain their hundreds, tens and unit word equivalents.
  3. if the hundreds portion of a three-digit group is not zero, the number of hundreds is added as a word. If the three-digit group is exactly divisible by one hundred, the text hundred is appended. If not, the text hundred and is appended, for example three hundred or one hundred and forty six.
  4. if the tens section of a three-digit group is two or higher, the appropriate -ty word (twenty, thirty, etc.) is added to the text and followed by the name of any non-zero third digit. If the tens and the units are both zero, then no text is added. For all other values, the name of the one or two-digit number is added as a special case.
  5. each group of three digits can be recombined with the addition of any relevant scale number (thousand, million, billion) separated by a comma, unless the group is blank in which case it's not included at all. The exception to this rule is when the final group of three digits does not include any hundreds and there is more than one non-blank group. In this case, the final comma is replaced with and, for example one million and forty six.
  6. negative numbers are preceded by a word to indicate this negativity, for example Minus

The following function obeys all of the above rules by, firstly, splitting any given number into groups of three digits which are stored as individual elements in an array. Secondly, it then converts each of the elements from this array into its equivalent value in words, using the rules outlined above, and stores them into a new array. Finally, it takes the new array, recombines all of the elements, and applies any additional formatting to produce the returned string:


function NumberToWords(num:Number, display:Number, minus:String):String {
if (minus == null) {
minus = "Minus";
}
var smallNumbers:Array = new Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
var tenNumbers:Array = new Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");
var scaleNumbers:Array = new Array("", "Thousand", "Million", "Billion");
if (num == 0) {
return smallNumbers[0];
}
var digitGroups:Array = new Array();
var positive:Number = Math.abs(num);
for (var i:Number = 0; i < 4; i++) {
digitGroups[i] = Math.floor(positive % 1000);
positive /= 1000;
}
groupText = new Array();
for (var i:Number = 0; i < 4; i++) {
groupText[i] = digitGroupToWords(digitGroups[i]);
}
function digitGroupToWords(threeDigits) {
groupText[i] = "";
var hundreds:Number = Math.floor(threeDigits / 100);
var tensUnits:Number = Math.floor(threeDigits % 100);
if (hundreds != 0) {
groupText[i] += smallNumbers[hundreds] + " Hundred";
if (tensUnits != 0) {
groupText[i] += " and ";
}
}
var tens:Number = Math.floor(tensUnits / 10);
var units:Number = Math.floor(tensUnits % 10);
if (tens >= 2) {
groupText[i] += tenNumbers[tens];
if (units != 0) {
groupText[i] += " " + smallNumbers[units];
}
} else if (tensUnits != 0) {
groupText[i] += smallNumbers[tensUnits];
}
return groupText[i];
}
var combined:String = groupText[0];
var appendAnd:Boolean;
appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100);
for (var i:Number = 1; i < 4; i++) {
if (digitGroups[i] != 0) {
var prefix:String = groupText[i] + " " + scaleNumbers[i];
if (combined.length != 0) {
prefix += appendAnd ? " and " : ", ";
}
appendAnd = false;
combined = prefix + combined;
}
}
if (num < 0) {
combined = minus + " " + combined;
}
switch (display) {
case 0 :
// Upper case
combined = combined.toUpperCase();
break;
case 1 :
// Sentence case
combined = combined.substr(0, 1) + combined.substring(1).toLowerCase();
break;
case 2 :
// Lower case
combined = combined.toLowerCase();
break;
default :
// Capitalised
break;
}
return combined;
}

The function accepts three arguments:

  1. the number to be converted into words, e.g. 474635
  2. a value representing the case of the returned string of words:
    0 = upper case, e.g. ONE HUNDRED AND EIGHT
    1 = sentence case, e.g. One hundred and eight
    2 = lower case, e.g. one hundred and eight
    3 = capitalised, e.g. One Hundred and Eight
    The default is 3
  3. the prefix to signify a negative number, e.g. Negative
    The default value is Minus
Examples of the function's usage are shown here:


// default use
trace(NumberToWords(123456789));
// lower case
trace(NumberToWords(123456789, 1));
// upper case with an alternative negative prefix
trace(NumberToWords(-123456789, 0, "negative"));