Knuth's algorithm S: Difference between revisions

→‎{{header|Java}}: Minor simplifications to both existing solutions.
(→‎{{header|Kotlin}}: Minor improvements to existing class based solution. Added alternative function based solution.)
(→‎{{header|Java}}: Minor simplifications to both existing solutions.)
Line 813:
 
=={{header|Java}}==
{{improve|Java|Unnecessary complicated, tends to be [https://en.wikipedia.org/wiki/Spaghetti_code spaghetti code]}}
A class-based solution:
<lang java>import java.util.*;
}
 
class SOfN<T> {
private static final Random rand = new Random();
}
 
private List<T> sample;
private int i = 0;
private int n;
 
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
 
public List<T> process(T item) {
if (++i <= n) {
i++;
if (i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
}
return sample;
}
}
}
 
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 109; i++) s_of_n.process(i);
List<Integer> sample = null;
for (int s : s_of_n.process(9)) bin[s]++;
for (int i = 0; i < 10; i++)
}
sample = s_of_n.process(i);
System.out.println(Arrays.toString(bin));
for (int s : sample)
bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}</lang>
 
Sample output:
Output:
 
<pre>[3011529965, 3014129690, 3005029911, 2988729818, 2976530109, 3013230250, 2976730085, 3011429857, 3007930191, 2995030124]</pre>
 
Alternative solution without using an explicitly named type; instead using an anonymous class implementing a generic "function" interface:
<lang java>import java.util.*;
 
interface Function<S, T> {
public T call(S x);
}
 
public class AlgorithmS {
private static final Random rand = new Random();
public static <T> Function<T, List<T>> s_of_n_creator(final int n) {
return new Function<T, List<T>>() {
private List<T> sample = new ArrayList<T>(n);
private int i = 0;
public List<T> call(T item) {
if (++i <= n) {
i++;
sample.add(item);
if (i <= n) {
} else if (rand.nextInt(i) < n) {
sample.add(item);
} else if sample.set(rand.nextInt(i) < n), {item);
}
sample.set(rand.nextInt(n), item);
return sample;
}
}
return sample;
};
};
}
 
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
Function<Integer, List<Integer>> s_of_n = s_of_n_creator(3);
for (int i = 0; i < 9; i++) s_of_n.call(i);
List<Integer> sample = null;
for (int i = 0; i < 10; ifor (int s : s_of_n.call(9)) bin[s]++);
}
sample = s_of_n.call(i);
System.out.println(Arrays.toString(bin));
for (int s : sample)
bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}</lang>
 
Sample output:
 
<pre>[29965, 30178, 29956, 29957, 30016, 30114, 29977, 29996, 29982, 29859]</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
9,483

edits