シードを固定した乱数
Posted feedbacks - Java
一番乗り?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.Arrays;
import java.util.Random;
public class RandomWithSeed {
public static void main(String[] args) {
final long seed = 1234567890L;
final int count = 10;
System.out.println(Arrays.toString(getRandomValuesWithSeed(seed, count)));
System.out.println(Arrays.toString(getRandomValuesWithSeed(seed, count)));
System.out.println(Arrays.toString(getRandomValuesWithSeed(seed, count)));
}
private static int[] getRandomValuesWithSeed(
final long seed, final int count) {
Random random = new Random(seed);
int[] randomValues = new int[count];
for (int i = 0; i < randomValues.length; i++) {
randomValues[i] = random.nextInt();
}
return randomValues;
}
}
|
ちょっと遊んでみました。こちらのコードは擬似乱数を10個出力します。
1 2 3 4 5 6 7 8 9 10 11 12 13 | import java.util.Random;
public class RandomPrint {
public static void main(String[] args) {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(random.nextInt());
sb.append(" ");
}
System.out.println(sb.toString());
}
}
|
で、こちらは擬似乱数のシードを固定し、RandomPrint を数回実行し、常に同じ結果が出力されることを確認するテストケースです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import static jp.co.dgic.testing.common.virtualmock.MockObjectManager.*;
import static org.junit.Assert.*;
import java.util.*;
import jp.co.dgic.testing.common.virtualmock.*;
import org.junit.*;
public class RandomPrintTest implements IReturnValueProvider {
private int seed;
@Before
public void setUp() {
seed = new Random().nextInt();
}
@Test
public void testMain() {
// 擬似乱数のシードを固定する
setReturnValueAtAllTimes("java.util.Random", "<init>", this);
// 数回実行する
final int count = 10;
for (int i = 0; i < count; i++) {
RandomPrint.main(null);
}
// 常に同じ結果が出力されることを確認する
String arg1 = (String) getArgument("PrintStream", "println", 0, 0);
assertNotNull(arg1);
for (int i = 1; i < count; i++) {
String arg2 = (String) getArgument("PrintStream", "println", i, 0);
assertEquals(arg1, arg2);
}
}
@Override
public Object createReturnValue(Object[] arg0) {
return new Random(seed);
}
}
|




ところてん
#9451()
Rating1/1=1.00
[ reply ]