Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- public class RNG
- {
- // Initialize using a random seed instead of a constant.
- private static double a = new Random().nextDouble();
- private static double b = new Random().nextDouble();
- // If the user determines the number of RNs, may as well conserve memory
- // by making the entire thing a function call.
- public static int[] genRandInts(int amount)
- {
- int[] output = new int[amount];
- for (int i = 0; i < amount; ++i)
- {
- double next = a + b;
- // The tertiary operator is a bit faster than an if branch, I think.
- next -= (next >= 1)? 1 : 0;
- // These next two do the same thing, I personally prefer the above.
- //if (next >= 1) { next -= 1; } // Always use -= instead of x = x - 1
- //while (next >= 1) { --next; }
- // The loop prevents a few things, but isn't really necessary with
- // this generator in particular. With larger programs, however, it
- // definitely is safer, since it catches any possible miscalculation
- // that leads to next being more than 2 or whatever.
- a = b;
- // The expression 'b = next' returns the value of next. Optimizing~
- output[i] = (int) Math.floor((b = next)*100);
- }
- // And now you have your entire RN stack ready for you. It's almost not
- // worth making into a separate function call, but whatever.
- return output;
- }
- public static void main(String[] args)
- {
- int num = -1;
- if (args.length >= 1) { num = args[0]; }
- else
- {
- // There are other ways of doing this, but this is my preferred way.
- while (num == -1)
- {
- System.out.println("How many RNs to generate?");
- Scanner user = new Scanner(System.in);
- // Basically, you're making sure the program doesn't crash if the
- // user enters something like 'fish' as a value.
- try { num = user.nextInt(); }
- catch { System.out.println("That's not a number.\n"); }
- }
- }
- int[] list = genRandInts(num);
- for (rn : list) { System.out.println(rn); }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment