Camtech075

RNG better version

Feb 12th, 2012
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. public class RNG
  5. {
  6. // Initialize using a random seed instead of a constant.
  7. private static double a = new Random().nextDouble();
  8. private static double b = new Random().nextDouble();
  9.  
  10. // If the user determines the number of RNs, may as well conserve memory
  11. // by making the entire thing a function call.
  12. public static int[] genRandInts(int amount)
  13. {
  14. int[] output = new int[amount];
  15. for (int i = 0; i < amount; ++i)
  16. {
  17. double next = a + b;
  18. // The tertiary operator is a bit faster than an if branch, I think.
  19. next -= (next >= 1)? 1 : 0;
  20.  
  21. // These next two do the same thing, I personally prefer the above.
  22.  
  23. //if (next >= 1) { next -= 1; } // Always use -= instead of x = x - 1
  24. //while (next >= 1) { --next; }
  25. // The loop prevents a few things, but isn't really necessary with
  26. // this generator in particular. With larger programs, however, it
  27. // definitely is safer, since it catches any possible miscalculation
  28. // that leads to next being more than 2 or whatever.
  29.  
  30. a = b;
  31. // The expression 'b = next' returns the value of next. Optimizing~
  32. output[i] = (int) Math.floor((b = next)*100);
  33. }
  34. // And now you have your entire RN stack ready for you. It's almost not
  35. // worth making into a separate function call, but whatever.
  36. return output;
  37. }
  38.  
  39. public static void main(String[] args)
  40. {
  41. int num = -1;
  42. if (args.length >= 1) { num = args[0]; }
  43. else
  44. {
  45. // There are other ways of doing this, but this is my preferred way.
  46. while (num == -1)
  47. {
  48. System.out.println("How many RNs to generate?");
  49. Scanner user = new Scanner(System.in);
  50.  
  51. // Basically, you're making sure the program doesn't crash if the
  52. // user enters something like 'fish' as a value.
  53. try { num = user.nextInt(); }
  54. catch { System.out.println("That's not a number.\n"); }
  55. }
  56. }
  57.  
  58. int[] list = genRandInts(num);
  59.  
  60. for (rn : list) { System.out.println(rn); }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment