fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Program
  9. {
  10. public static void main (String[] args) throws Exception {
  11. new Program().run();
  12. }
  13.  
  14. void run() {
  15. int a = 4;
  16. int b = 17;
  17. int n = 3;
  18. try {
  19. int[] array = Generate(a, b, n);
  20. for (int x : array)
  21. System.out.printf("%d ", x);
  22. }
  23. catch (Exception e) {
  24. System.out.printf("Exception: " + e.getMessage());
  25. }
  26. }
  27.  
  28. int[] Generate(int a, int b, int n) {
  29. int max = (b + 2) - (a - 2) + 1 - 4 * n;
  30. if (n > max)
  31. throw new IllegalArgumentException("Задача неразрешима");
  32. int[] result = ReservoirSampling(n, max);
  33.  
  34. // выборка неотсортирована, сортируем
  35. Arrays.sort(result);
  36.  
  37. // и возвращаем нужные индексы:
  38. for (int i = 0; i < n; i++)
  39. result[i] += a + (4 * i);
  40.  
  41. return result;
  42. }
  43.  
  44. int[] ReservoirSampling(int n, int max) {
  45. Random r = new Random(); // этот экземпляр нужно сделать глобальным
  46. int[] result = new int[n];
  47. for (int i = 0; i < n; i++)
  48. result[i] = i;
  49.  
  50. for (int i = n; i < max; i++) {
  51. int j = r.nextInt(i + 1);
  52. if (j < n)
  53. result[j] = i;
  54. }
  55. return result;
  56. }
  57. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
5 11 16