I have a book with N <10000 pages and a number x (in the range 1 <= x <= 40). I want to calculate the probability that when opening this book at random, the combination of the numbers of the open pages of the book is equal to the number.
The “combination level” can vary: from a simple sum of digits (event p.234 is true for x = 9), combinations of sums and subtractions to pairs of digits [event p.124 is true for x = 1, 2, 3 (4-1), 4, 5 (4 + 1), 6 (2 + 4), 7 (1 + 2 + 4), 8 (12-4), 12, 14, 16 (14 + 2), 23 (24-1), 24, 25 (24 + 1)]
The initial note is that if you open the book, you always get page n and page n + 1, so the probability should be calculated for a pair (2n-1,2n) for each n, 1
That's what I'm doing
static protected int sommaCifreNumero(int numero){ int retnum=0; for (char c : Integer.valueOf(numero).toString().toCharArray()){ retnum += c - 48; } return retnum; } static public float calcolaProbabilitàSemplice(int da_interrogare, int ne_interroga) { return (float)ne_interroga/(float)da_interrogare*100f; } static public float calcolaProbabilitàLibroSemplice(int nPagine, int nRegistro) { int maxNumberInterrogabile = 0; float retProb; maxNumberInterrogabile = sommaCifreNumero (nPagine); maxNumberInterrogabile = ((Integer.valueOf(nPagine).toString().length() == 2) && (Integer.valueOf(nPagine).toString().toCharArray()[1] -48 -1 + 9*1)>maxNumberInterrogabile) ? (Integer.valueOf(nPagine).toString().toCharArray()[1] -48 -1 + 9*1) : maxNumberInterrogabile; maxNumberInterrogabile = ((Integer.valueOf(nPagine).toString().length() == 3) && (Integer.valueOf(nPagine).toString().toCharArray()[2] -48 -1 + 9*2)>maxNumberInterrogabile) ? (Integer.valueOf(nPagine).toString().toCharArray()[1] -48 -1 + 9*2) : maxNumberInterrogabile; maxNumberInterrogabile = ((Integer.valueOf(nPagine).toString().length() == 4) && (Integer.valueOf(nPagine).toString().toCharArray()[3] -48 -1 + 9*3)>maxNumberInterrogabile) ? (Integer.valueOf(nPagine).toString().toCharArray()[1] -48 -1 + 9*3) : maxNumberInterrogabile; if(nRegistro>maxNumberInterrogabile) { retProb = 0.f; return 0.f; }
The first method calculates the sum of the digits of the number, the second - the probability that the number of the open page is x, or the sum of their digits. The third check is also a pair of numbers.
1) I do not take into account the note that I made earlier.
2) I ran this on a mobile device.
3) Now I really feel that the results are wrong.
I was wondering if the table of pre-calculated results would fit better. I know that N is <10000, so I can use the array [40] [10000] to store the results for loading at runtime, but I will not get involved in file manipulation in Java, in addition, I will need to save this, say, 4 different methods for calculating probability, so how much memory will it consume? And is it a problem to calculate this at runtime instead? Is there a better way (or perhaps an already written algorithm) for this?