forked from maxhli/fakebigdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigit-distribution.js
59 lines (48 loc) · 2.39 KB
/
digit-distribution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* This file holds code for determining the distribution of all 10 digits 0-9
that comprise an integer in base 10. */
//Create a big-integer class
//Currently not in use.
var bigInt = require("big-integer");
//This function reads in an integer and returns an array of length 10, representing the percentages
//of the integer comprised by the digits 0-9. Thus, the element at index 0 represents the percentage of
//the integer made up of the digit 0.
//
//NOTE: "Javascript numbers larger than 9007199254740992 and smaller than -9007199254740992 are not precisely
//represented numbers and will not produce exact results. If you are dealing with numbers outside that range,
//it is better to pass in strings."
//-Peter Olson, creator of the big-integer class.
function digitDistribution(num) {
//Check to make sure that the input is an integer in base 10:
if(isNaN(num))
return "Improper input to function digitDistribution. Please input an integer in base 10.";
//Get string representation of input:
var str = num.toString();
//Check to see if the input contains a "-" or a "+" prefix; if so, remove it before continuing:
if(str.indexOf('-') >= 0 || str.indexOf('+') >= 0)
str = str.substring(1);
//Initialize a count array for frequencies of digits 0-9:
var countArray = [0,0,0,0,0,0,0,0,0,0];
//Initialize a percentage array to be determined by the count array:
var percentageArray = [0,0,0,0,0,0,0,0,0,0];
//Count the frequency of each digit 0-9 in the input number:
for(var i = 0; i < str.length; i++) {
countArray[str.charAt(i)]++;
}
//Turn counts into percentages (rounded to 2 decimal places) and puts them in the percentageArray:
for(var i = 0; i < 10; i++) {
percentageArray[i] = roundToTwo(countArray[i] / str.length * 100);
}
//Return the frequency percentages:
return percentageArray;
}//End function digitDistribution
//This helper function simply rounds the input number to two decimal places, and is
//used in the digitDistribution function:
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}//End function roundToTwo.
//Test cases:
console.log(digitDistribution(12313234245599));
console.log(digitDistribution(-9988776234234));
console.log(digitDistribution(+3434234230998));
console.log(digitDistribution("-99878777657678979808987988912322342354564567434"));
console.log(digitDistribution("+23489249091237834901230938428350943982234823849237491248239847293866"));