Wednesday, March 9, 2011

GIQ: random number range

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

This is my solution, thrown together quickly, in java of course, bear in mind that the algorithm is simply to loop over the first function (1-5) 7 times, adding in the result to a running total, then do a modulo 7 for the grand result of the second function...

import java.util.Random;
public class rand {

int A = 5;
int B = 7;
int sample = 50;

public rand(){
}

public void init() {
System.out.println(""+getAppletInfo());
if (A<=0) throw new IllegalArgumentException("A must be >= 0");
if (B<=0) throw new IllegalArgumentException("B must be >= 0");
int[] dist = new int[B];
for(int j=0; j<B; j++) {
dist[j] = 0;
}
for(int i=0; i<sample; i++) {
int next = randB();
dist[next-1] += 1;
System.out.println(".."+next);
}
System.out.println("Distribution...");
for(int j=0; j<B; j++) {
System.out.println("j:"+j+",count:"+dist[j]);
}
}

Random random = new Random();
int randA () {
return random.nextInt(A) + 1;
}

int randB () {
int r = 0;
for(int i=0; i<B; i++) {
r += randA() - 1;
}
return r % B + 1;
}

public String getAppletInfo() {
return "randB from randA by Douglas A. Bauman";
}

static public void main(String[] args) {
rand rr = new rand();
try {
rr.A = Integer.parseInt(args[0]);
try {
rr.B = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
} catch (RuntimeException e) {
}
} catch (NumberFormatException e2) {
} catch (RuntimeException e2) {
}
rr.init();
}
}

No comments:

Post a Comment