I am trying to create my own Random Number Generator in Java and have been using the Lagged Fibonacci formula.
It works when I want to grab one random number, but when I want to generate multiple random numbers it is just pulling the same random number for all iterations rather than holding on to the new array to generate the next random number.
public class RNumbers {
public static void main(String[] args) {
RandomNumberGenerator rd = new RandomNumberGenerator();
int number = rd.getNumber();
System.out.println(number);
for (int i = 0; i <= 100; i++) {
int number2 = rd.getNumber();
System.out.println(number2);
}
}
}
public class RandomNumberGenerator {
public static int getNumber() {
long seed = System.currentTimeMillis(); // start seed number for formula
int length = (int) (Math.log10(seed) + 1); // number of digits int the seed number
int j = 3; // will always grab the 3rd value from the seed
int k = 7; // will always grab the 7th value from the seed
int mod = 10; // will always be the mod number for formula
int[] arr = new int[length + 1]; // array for seed numbers
String stseed = String.valueOf(seed); // seed to String for adding digits to array
// Take the seed number and turn it into an array of single digit numbers to mimic a sequence
for (int i = 0; i <= length - 1; i++) {
arr[i] = Character.getNumericValue(stseed.charAt(i));
}
// calculate random number with inputs
int number = (arr[length - j] + arr[length - k]) % mod;
// add random number to the end of the array in the temp index
arr[length] = number;
// update array by shifting all indexes down
for (int i = 0; i <= length - 1; i++) {
arr[i] = arr[i + 1];
}
return number;
}
}
Each time you call getNumber() you re-initialize the state of the generator. If you call this multiple times within the same millisecond, you'll initialize it to the same state every time, so you'll end up with the same value. (Even if you call it multiple times over a longer time period, only some of the digits will change, so you still may end up with the same result.)
You need to cache the state, and initialize it once:
public class RandomNumberGenerator {
private static long seed ; // start seed number for formula
private static int length ; // number of digits int the seed number
private static final int j = 3; // will always grab the 3rd value from the seed
private static final int k = 7; // will always grab the 7th value from the seed
private static final int mod = 10; // will always be the mod number for formula
private static int[] arr ; // array for seed numbers
static {
seed = System.currentTimeMillis();
length = (int) (Math.log10(seed) + 1) ;
arr = new int[length + 1] ;
String stseed = String.valueOf(seed); // seed to String for adding digits to array
// Take the seed number and turn it into an array of single digit numbers to mimic a sequence
for (int i = 0; i <= length - 1; i++) {
arr[i] = Character.getNumericValue(stseed.charAt(i));
}
}
public static int getNumber() {
// calculate random number with inputs
int number = (arr[length - j] + arr[length - k]) % mod;
// add random number to the end of the array in the temp index
arr[length] = number;
// update array by shifting all indexes down
for (int i = 0; i <= length - 1; i++) {
arr[i] = arr[i + 1];
}
return number;
}
}
I'd recommend not making everything static (especially since you don't use it in a static fashion in your main method):
public class RandomNumberGenerator {
private long seed ; // start seed number for formula
private int length ; // number of digits int the seed number
private static final int j = 3; // will always grab the 3rd value from the seed
private static final int k = 7; // will always grab the 7th value from the seed
private static final int mod = 10; // will always be the mod number for formula
private int[] arr ; // array for seed numbers
public RandomNumberGenerator() {
seed = System.currentTimeMillis();
length = (int) (Math.log10(seed) + 1) ;
arr = new int[length + 1] ;
String stseed = String.valueOf(seed); // seed to String for adding digits to array
// Take the seed number and turn it into an array of single digit numbers to mimic a sequence
for (int i = 0; i <= length - 1; i++) {
arr[i] = Character.getNumericValue(stseed.charAt(i));
}
}
public int getNumber() {
// calculate random number with inputs
int number = (arr[length - j] + arr[length - k]) % mod;
// add random number to the end of the array in the temp index
arr[length] = number;
// update array by shifting all indexes down
for (int i = 0; i <= length - 1; i++) {
arr[i] = arr[i + 1];
}
return number;
}
}
Related
I'm trying to practice with arrays in prep for my Java SE 11 test and I need help getting my random name generator to work. Right now, I'm not concerned about the name being "valid" (a truly random name like Xvtwg is fine).
I have built a loop where a random value between 3 and 10 is generated (length of name) and then a random index between 0 and 25 is chosen for each loop pass to grab a random letter of the alphabet. All of this works, and I am able to take the output array from the loop and turn it into a concatenated string in the loop. The problem occurs later when I need to call the local variable nameFinal as a value for the set function.
I have tried to declare the output string both inside and outside the loop but both ways I return "nameFinal cannot be resolved to a variable." I have also tried moving my output array outside of the loop (and redefining its output), but return the same variable."
I added in a try/catch block to try to illustrate this issue better. Here is my code:
public class Tester {
public static void main(String[] args) {
//Build random values
Random rand = new Random();
//Name random index 3-10 char
int nmax = 10;
int nmin = 3;
int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
//Create random name from total number of letters
//Define Array of letters
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
//Create random index to pull a random letter over the length of the random index
int lmax = 25;
int lmin = 0;
//I have also tried declaring newName and nameFinal here
for(int i = 0; i <= rand1; i++) {
int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
String[] newName;
newName[i] = letters[i];
String nameFinal = Arrays.toString(newName);
}
//Concatenate array of random letters into a "name"
try{
String nameFinal = Arrays.toString(newName);
System.out.println(nameFinal);
}catch(Exception e) {
e.PrintStackTrace()
}
//Implementation omitted
}
}
I have changed your code a bit. Hope this will help you!
public static void main(String[] args) {
//Build random values
Random rand = new Random();
Test test = new Test();
test.randomName();
test.createAge();
test.createSSN();
}
//Name random index 3-10 char
public void randomName() {
int nmax = 10;
int nmin = 3;
int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
//Create random name from total number of letters
//Define Array of letters
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
//Create random index to pull a random letter over the length of the random index
int lmax = 25;
int lmin = 0;
ArrayList<String> name = new ArrayList<>(5);
for(int i = 0; i <= rand1; i++) {
int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
name.add(letters[rand1]);
}
System.out.println(name.toString());
}
//Age random number between 1 and 100
private void createAge(){
int amax = 100;
int amin = 1;
int rand2 = (int)(Math.random() * (amax - amin + 1) + amin);
}
//SSN random 9 digit number
private void createSSN(){
int smax = 999999999;
int smin = 100000000;
int rand3 = (int)(Math.random() * (smax - smin + 1) + smin);
}
}
I have to write a function that multiplies two numbers represented by two int arrays (so I can't use ArrayLists or something).
Each digit of a number is represented by an int between 0 and 9 in the array, no element should be greater than that.
The first element of the array represents the last digit of the number and so on, therefore the number 1234 would be {4,3,2,1} as an array in this function.
I thought multiplying those arrays that way would be similar to long multiplication, so I tried to implement it in a similar way: You multiply every digit of the first array with every digit of the second one and store the rest if the result is equal or greater to 10 and then add it to the next digit. However, I seem to have done something wrong in the code (maybe the calculation of the rest??) because the result of my function is not correct: I tested it with 190 times 86 (represented by the arrays {0,9,1} and {6,8}) and get 15342 ({2,4,3,5,1}) instead of the actual result 16340 (which would be {0,4,3,6,1}).
Can somebody here help me out with this please? This is my code:
import java.util.Arrays;
public class MultiplyArrays {
static int[ ] times(int[ ] a, int[ ] b) {
int[] arr = new int[a.length + b.length - 1];//arr should be the result of a*b. The result shouldn't be shorter than that
int tmp = 0;//stores the rest of two-digit numbers
for(int i = b.length - 1; i >= 0; i--){
for(int j = 0; j < a.length; j++){//should multiply all digits of a with the current index of b
arr[i + j] = (arr[i + j] + (b[i] * a[j] + tmp)) % 10;//sets the value of the (i+j)th index in arr to the multiplication of two numbers from a and b adding the rest tmp.
if((arr[i + j] + b[i] * a[j] + tmp) < 10){//if this number is less than 10, there is no rest
tmp = 0;
}
else{//otherwise, the rest should be the second digit
tmp = (((arr[i + j] + (b[i] * a[j] + tmp))) - ((arr[i + j] + (b[i] * a[j] + tmp)) % 10)) / 10;//something in the formula for the rest is wrong, I guess
}
}
}
if(tmp != 0){//if the last number of the array containing the result is calculated and there still is a rest, a new array with one more digit is created
int[] arr2 = new int[arr.length + 1];
for(int i = arr.length - 1; i >= 0; i--){//the new array copies all numbers from the old array
arr2[i] = arr[i];
arr2[arr2.length - 1] = tmp;//the last space is the rest now
}
return arr2;
}
else{//if there is no rest after calculating the last number of arr, a new array isn't needed
return arr;
}
}
public static void main(String[] args) {//test the function with 190 * 86
int[] a = {0,9,1};
int[] b = {6,8};
System.out.println(Arrays.toString(times(a,b)));
}
}
Maybe this comes from the fact that your indices in the for-loops of the times()-method are incrementing AND decrementing.
The i is going down and the j is going up.
Also, in the second for loop, you should only increment to 'a.length - 1', not to 'a.length'.
Arbitrary precision multiplication is more complex than it seems, and contains corner cases (like one and zero). Fortunately, Java has an arbitrary precision type; BigInteger. In order to use it here, you would need to create two additional methods; one for converting an int[] to a BigInteger, and the second the convert a BigInteger to an int[].
The first can be done with a single loop adding each digit at index i (multiplied by 10i) to a running total. Like,
private static BigInteger fromArray(int[] arr) {
BigInteger bi = BigInteger.ZERO;
for (int i = 0, pow = 1; i < arr.length; pow *= 10, i++) {
bi = bi.add(BigInteger.valueOf(arr[i] * pow));
}
return bi;
}
And the second can be done a number of ways, but the easiest is simply to convert the BigInteger to a String to get the length() - once you've done that, you know the length of the output array - and can populate the digits in it. Like,
private static int[] toArray(BigInteger bi) {
String s = bi.toString();
int len = s.length();
int[] r = new int[len];
for (int i = 0; i < len; i++) {
r[i] = s.charAt(len - i - 1) - '0';
}
return r;
}
Finally, call those two methods and let BigInteger perform the multiplication. Like,
static int[] times(int[] a, int[] b) {
BigInteger ba = fromArray(a), bb = fromArray(b);
return toArray(ba.multiply(bb));
}
Running your original main with those changes outputs (as expected)
[0, 4, 3, 6, 1]
Well, your thought would work with addition, but on multiplication you multiply each digit of one with the whole number of the other and step one digit to the left (*10) each time you change the multiplication digit of the first number.
So you might brought something into confusion.
I just solved it in a more structured way, running the debugger will hopefully explain the process. In the solutions you can remove the trailing / leading zero by checking the digit if 0 and replace the array with one of length - 1.
The solutions are:
With conditions mentioned (numbers in reverse order):
public static void main(String[] args) {
int[] a = {3,2,1};
int[] b = {9,8};
System.out.println("Result is: " + Arrays.toString(calculate(a, b)));
}
private static int[] calculate(int[] a, int[] b) {
// final result will be never longer than sum of number lengths + 1
int[] finalResult = new int[a.length + b.length + 1];
int position = 0;
for(int i = 0; i < a.length; i++) {
int[] tempResult = multiplyWithOther(a[i], b);
addToFinalResult(finalResult, tempResult, position);
position++;
}
return finalResult;
}
private static int[] multiplyWithOther(int number, int[] otherArray) {
// The number cannot be more digits than otherArray.length + 1, so create a temp array with size +1
int[] temp = new int[otherArray.length + 1];
// Iterate through the seconds array and multiply with current number from first
int remainder = 0;
for(int i = 0; i < otherArray.length; i++) {
int result = number * otherArray[i];
result += remainder;
remainder = result / 10;
temp[i] = result % 10;
}
// Add remainder (even if 0) to start
temp[temp.length - 1] = remainder;
return temp;
}
private static void addToFinalResult(int[] finalResult, int[] tempResult, int position) {
int remainder = 0;
for(int i = 0; i < tempResult.length; i++) {
int currentValue = tempResult[i];
int storedValue = finalResult[i + position];
int sum = storedValue + currentValue + remainder;
remainder = sum / 10;
finalResult[i + position] = sum % 10;
}
finalResult[position + tempResult.length] = remainder;
}
And with numbers in normal order in array:
public static void main(String[] args) {
int[] a = {1,2,3,6};
int[] b = {8, 9, 1};
System.out.println("Result is: " + Arrays.toString(calculate(a, b)));
}
private static int[] calculate(int[] a, int[] b) {
// final result will be never longer than sum of number lengths + 1
int[] finalResult = new int[a.length + b.length + 1];
int positionFromEnd = 0;
for(int i = 1; i <= a.length; i++) {
int[] tempResult = multiplyWithOther(a[a.length-i], b);
addToFinalResult(finalResult, tempResult, positionFromEnd);
positionFromEnd++;
}
return finalResult;
}
private static int[] multiplyWithOther(int number, int[] otherArray) {
// The number cannot be more digits than otherArray.length + 1, so create a temp array with size +1
int[] temp = new int[otherArray.length + 1];
// Iterate through the seconds array and multiply with current number from first
int remainder = 0;
for(int i = 1; i <= otherArray.length; i++) {
int result = number * otherArray[otherArray.length - i];
result += remainder;
remainder = result / 10;
temp[otherArray.length - i +1] = result % 10;
}
// Add remainder (even if 0) to start
temp[0] = remainder;
return temp;
}
private static void addToFinalResult(int[] finalResult, int[] tempResult, int positionFromEnd) {
int remainder = 0;
for(int i = 1; i <= tempResult.length; i++) {
int currentValue = tempResult[tempResult.length - i];
int storedValue = finalResult[finalResult.length - positionFromEnd - i];
int sum = storedValue + currentValue + remainder;
remainder = sum / 10;
finalResult[finalResult.length - positionFromEnd - i] = sum % 10;
}
finalResult[finalResult.length - positionFromEnd - tempResult.length - 1] = remainder;
}
So I'm trying to reverse a number in java using a forloop, I get the right value but I'm not sure if thats the best way of doing it.
package forloops;
/*
% prints the last number in the sequence
/ prints every number except for the last one
*/
public class modulusForLoops {
public static void main(String[]args) {
int orig = 123456789;
int num = orig;
for (int i = 0; i < 1; i++) {
num = orig % 10; //9
int secondDigit = orig / 10; //12345678
int secondDigitPrinted = secondDigit % 10; //8
int thirdDigit = secondDigit / 10; //1234567
int thirdDigitPrinted = thirdDigit % 10; //7
int fourthDigit = thirdDigit / 10; //123456
int fourthDigitPrinted = fourthDigit % 10; //6
int fifthDigit = fourthDigit / 10; //12345
int fifthDigitPrinted = fifthDigit % 10;
int sixthDigit = fifthDigit / 10; //1234
int sixthDigitPrinted = sixthDigit % 10; //4
int seventhDigit = sixthDigit / 10; //123
int seventhDigitPrinted = seventhDigit % 10; //3
int eigthDigit = seventhDigit / 10; //12
int eigthDigitPrinted = eigthDigit % 10; //2
int lastDigit = eigthDigit / 10; //1
System.out.println(orig + " reversed is " + num + secondDigitPrinted + thirdDigitPrinted + fourthDigitPrinted + fifthDigitPrinted + sixthDigitPrinted + seventhDigitPrinted + eigthDigitPrinted + lastDigit);
}
}
}
You could simply convert it to String and using java.lang.StringBuilder reverse the string.
int orig = 123456789;
String numString = Integer.toString(orig);
String reversed = "";
for (int i = numString.length() - 1; i >= 0; i--) { // loop through the string from back to front
reversed += numString.charAt(i); // add each character to the resulting string
}
System.out.println(reversed);
Or alternatively
int orig = 123456789;
String numString = Integer.toString(orig); // convert int to String
String reversed = new StringBuilder(numString).reverse().toString(); // reverse string
System.out.println(reversed);
Let's stick with the logic you have in mind to reverse any number. For better understanding, let's list out the algorithm steps that you are using.
Repeat below steps until there are no digits left in the given number:
I) get the last digit from the number, i.e. lastDigit = number % 10
II) remove the last digit from the number, i.e. numberWithoutLast = number / 10
When we want to go through a sequence of steps multiple times, i.e. repeat them, we make use of the looping structures like for, while or do...while
Therefore, if we were to rewrite your program-the loop part-it would be as follows:
public static void main(String[] ar) {
int orig = 123456789;
int lastDigit = 0;
/* we'll use the copy of original number for step I & II
* instead of messing with the original number
*/
int numberWithoutLast = orig;
String reversed = ""; // we'll use this to store every last digit
for(int i = 0;
i < Integer.toString(orig).length(); /* this will repeat the loop for number of digits in "orig" */
i++) {
lastDigit = numberWithoutLast % 10;
reversed += Integer.toString(lastDigit);
numberWithoutLast = numberWithoutLast / 10;
}
// lastly we print the reversed number
System.out.println("Reversed Number: " + reversed);
}
This was the manual way of reversing an integer. For an automatic way, you can have a look at #Andreas's answer.
Just in case you want to know how to do it by modulus and loop. The idea is to pop the unit digit from the source and push it to the destination in every iteration, in a number way.
int orig = 123456789; //assume > 0
int num = 0;
for(int temp = orig;temp > 0;temp/=10)
{
num = num * 10 + temp % 10;
}
System.out.println(orig + " reversed is " + num);
This question is extremely specific. I have found dozens of places telling you how to generate random permutations in Java, but it never got as far as calculating the probability of the Chi Square Distribution. Let me tell you that setting it up seemed fair enough, with many tutorials online, but one thing about this code that has really nagged me was the fact that in the second part of the assignment, I'm supposed to generate a random permutation of a string from index j where j is chosen randomly between the range of 0 and i. One method is supposed to output a probability of 1.0 all the time, which is biased and unfair, while the second method generates a probability of any number between 0 and 1.0. I've got the first part of that in part 1, but the second part I am having trouble making it not display 1.0 all the time. The assignment says that i simply steps through the array. In this circumstance, two styles of permutation generation were tried:
Method 1:
public static String generatePermutation(String prefix, String t){
int n = 6;
String s = "";
StringBuilder test = new StringBuilder(t);
if (n == 0){
System.out.println(prefix);
}
else {
for(int i = 0; i < n; i++){
int j = randInt(0, i);
char temp = test.charAt(j);
test.setCharAt(j, test.charAt(i));
test.setCharAt(i, temp);
}
s = test.toString();
return s;
}
return s;
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Method 2:
public static String generatePermutation(String prefix, String t){
char[] letters = t.toCharArray();
shuffle(letters);
String s = new String(letters);
return s;
}
public static void shuffle(char[] array){
int n = array.length;
Random rand = new Random();
while(n > 1){
int k = rand.nextInt(n--);
char temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Both methods did not seem to give me a random number probability between 0 and 1.0. The current code for part 2 of the assignment is structured like this:
package math3323assignment7;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Collections;
import org.apache.commons.math3.distribution.ChiSquaredDistribution;
import com.google.common.collect.Multiset;
import com.google.common.collect.TreeMultiset;
public class assignment7part2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "ABCDEF";
Map<String, Integer> counts = new HashMap<>();
Integer count;
int expected = (int)factorial(s.length());
for(int i = 0; i < 720000; i++){
String t = generatePermutation("",s);
count = counts.get(t);
if(count == null){
count = 1;
}
else {
count = count + 1;
}
counts.put(t, count);
System.out.println(t);
}
for(Entry<String, Integer> entry : counts.entrySet()){
System.out.println(entry.getValue() + " times: " + entry.getKey());
}
double chistat = 0.0;
for(Entry<String, Integer> entry: counts.entrySet()){
double di = entry.getValue() - expected;
chistat += di*di/expected;
}
ChiSquaredDistribution chisq = new ChiSquaredDistribution(719.0);
double prob = chisq.cumulativeProbability(chistat);
System.out.printf("ChiSquare statistic = " + chistat + " the probability is " + prob);
}
public static String generatePermutation(String prefix, String t){
char[] letters = t.toCharArray();
shuffle(letters);
String s = new String(letters);
return s;
}
public static long factorial(int n){
if (n <= 1){
return 1;
}
else {
return n * factorial(n-1);
}
}
public static void shuffle(char[] array){
int n = array.length;
Random rand = new Random();
while(n > 1){
int k = rand.nextInt(n--);
char temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
As you can see, the Apache Math Distribution class from the Apache API is being used to create the Chi Square Distribution. A separate for loop is being used to calculate the Chi Square statistic. Unfortunately, when I run the program, the output always has a similar vein right at the very end to this:
Prints all random permutations 720,000 times
Counts all the times each permutation occurs, and print out the numbers
ChiSquare statistic = 79360.74444444438 the probability is 1.0
I want the final part to print out like this:
ChiSquare statistic = 79360.74444444438 the probability is 0.64
May you please help me fix this to where the final result of the second part of the program looks like the above line?
The expected value you are using is incorrect. Your output should demonstrate a count that is somewhere around 1000 for each random permutation. One would expect each to be exactly 1000 in a non-random setting, because 720000 / 1000 = 720 which is what you are computing with
int expected = (int)factorial(s.length());
Instead try
int expected = 1000;
I would like to generate random numbers in ascending order, for instance: 0, 2, 3, 5 .. 100, but not 2, 0, 5 ..
This is what I came up with so far:
public static int vol=5;
public static void main(String[] args) {
int randno = getRandNum();
vol = vol+randno;
System.out.println(getRandNum());
}
private static int getRandNum() {
Random r = new Random();
for (int i =0; i<10; i++)
{
int v=r.nextInt(vol);
System.out.println("r"+v);
}
return vol;
}
How could I achieve the goal stated above?
/**
* Generates random numbers, returning an array of ascending order.
* #param amount The amount of numbers to generate.
* #param max The maximum value to generate.
* #return An array of random integers of the specified length.
*/
public static int[] generateIncreasingRandoms(int amount, int max) {
int[] randomNumbers = new int[amount];
Random random = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = random.nextInt(max);
}
Arrays.sort(randomNumbers);
return randomNumbers;
}
You could use it like so:
// Generates 10 random numbers of value 0 to 100,
// printing them in ascending order
for (int number : generateIncreasingRandoms(10, 100)) {
System.out.print(number + " ");
}
Or if you're a micro-optimization kind of person and do not wish to sort,
/**
* Generates random numbers, returning an array of ascending order.
* #param amount The amount of numbers to generate.
* #param max The maximum value to generate.
* #return An array of random integers of the specified length.
*/
public static int[] generateIncreasingRandomWithoutSorting(int amount, int max) {
int[] randomNumbers = new int[amount];
double delta = max / (float)amount;
Random random = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = (int)Math.round(i*delta + random.nextDouble() * delta);
}
return randomNumbers;
}
Use case:
// Generates 10 random numbers of value 0 to 100,
// printing them in ascending order
for (int number : generateIncreasingRandomWithoutSorting(10, 100)) {
System.out.print(number + " ");
}
The reason that each number is between 0-10, 10-20, 20-30.. in this use case is that if I simply allow for the entire range and you get a 100 on the first try you're going to end up with an entire array of 100s.
Being more controlled, with this solution you are not really getting what you're asking for ("10 numbers of 0 to 100 sorted ascendingly") since it modifies the range for each consecutive number. (like any other solution that doesn't require sorting)
Ben Barkay's answer is good, but if you don't want to create a set of numbers in one step, but you want to get one number after another, you can do something like this:
private static final int MAX = 5;
private Random rand = new Random();
private int maxRand = 0;
public int getIncreasingRandomNumber() {
maxRand = rand.nextInt(MAX);
return maxRand;
}
what about this?
public class increasing {
public static void main (String[] args) {
Random r = new Random();
int totalNums = 100;
int count = 0;
int lastVal = 0;
int currVal = 0;
while(count < totalNums) {
currVal = r.nextInt(200);
lastVal = lastVal + currVal;
System.out.println(lastVal + ",");
count++;
}
}
}