Funções de teste probabilísticos
-
22-07-2019 - |
Pergunta
Eu preciso de uma função que retorna um array em ordem aleatória. Eu quero garantir que é randomish mas não tenho idéia de como um iria sobre escrever os testes para garantir que a matriz é realmente aleatória. Posso executar o código de um monte de vezes e ver se tenho a mesma resposta mais de uma vez. Enquanto as colisões são improváveis ??para grandes matrizes é altamente provável para pequenas matrizes (digamos dois elementos).
Como devo ir sobre ele?
Solução
Basicamente, o truque consiste em extrair a aleatoriedade fora da classe que você está testando. Isso permitirá que você para testar a classe injetando a fórmula para a aleatoriedade do seu teste que naturalmente não seria aleatório em tudo.
C # exemplo:
public static List<int> Randomise(List<int> list, Func<bool> randomSwap)
{
foreach(int i in list)
{
if (randomSwap)
{
//swap i and i+1;
}
}
return list;
}
Pseudo Uso:
list = Randomise(list, return new Random(0, 1));
Outras dicas
Cedric recomenda uma abordagem em que você executar os tempos função suficiente para obter um estatisticamente amostra significativa e verificar as propriedades de vocês amostras.
Assim, para baralhar, você provavelmente vai querer verificar que a relação entre os elementos têm muito pequena covariância, que a posição esperada de cada elemento é N / 2, etc.
Outros artigos têm recomendado usando uma semente fixado para o gerador de números aleatórios, zombando do gerador de números aleatórios. Estes são recomendações finas, e muitas vezes eu segui-los. Às vezes, porém, vou testar a aleatoriedade vez.
Dada uma matriz de destino que você deseja preencher aleatoriamente a partir de uma matriz de origem considerar fazer o seguinte. Carregar a matriz de origem com inteiros consecutivos. Crie uma terceira matriz chamada 'soma' e carregá-lo com zeros. Agora preencher aleatoriamente o alvo e depois adicionar cada elemento da meta para o elemento correspondente de soma. Faça isso mais mil vezes. Se a distribuição é muito aleatório, então as somas devem ser todos praticamente o mesmo. Você pode fazer um simples -delta Você também pode fazer uma média e stdev dos elementos do array soma e fazer uma comparação delta deles também. Se você definir os limites direito, e fazer iterações suficientes, isso será suficiente muito bem. Você pode ser tentado a pensar que ele pode lhe dar um falso negativo, mas se você definir os limites corretamente será mais provável para um raio cósmico para alterar a execução do programa.
Em primeiro lugar você deve usar uma semente fixado para o gerador de números aleatórios, ou de outra maneira o teste pode falhar aleatoriamente (ou seja, às vezes eles podem estar em ordem - que é o problema com aleatoriedade). Então você poderia fazer algumas verificações simples, por exemplo, que os valores não estão em ordem, e que em cada corrida os valores são diferentes.
Aqui está um exemplo de testes que eu escrevi para o meu próprio Shuffle implementação saco .
import jdave.Specification;
import jdave.junit4.JDaveRunner;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* @author Esko Luontola
* @since 25.2.2008
*/
@RunWith(JDaveRunner.class)
public class ShuffleBagSpec extends Specification<ShuffleBag<?>> {
public class AShuffleBagWithOneOfEachValue {
private ShuffleBag<Integer> bag;
private List<Integer> expectedValues = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
public ShuffleBag<Integer> create() {
bag = new ShuffleBag<Integer>(new Random(123L));
for (Integer value : expectedValues) {
bag.add(value);
}
return bag;
}
public void onFirstRunAllValuesAreReturnedOnce() {
List<Integer> values = bag.getMany(10);
specify(values, does.containExactly(expectedValues));
}
public void onFirstRunTheValuesAreInRandomOrder() {
List<Integer> values = bag.getMany(10);
specify(values.get(0), does.not().equal(0));
specify(values.get(0), does.not().equal(1));
specify(values.get(0), does.not().equal(9));
specify(values, does.not().containInOrder(expectedValues));
specify(values, does.not().containInPartialOrder(1, 2, 3));
specify(values, does.not().containInPartialOrder(4, 5, 6));
specify(values, does.not().containInPartialOrder(7, 8, 9));
specify(values, does.not().containInPartialOrder(3, 2, 1));
specify(values, does.not().containInPartialOrder(6, 5, 4));
specify(values, does.not().containInPartialOrder(9, 8, 7));
}
public void onFollowingRunsAllValuesAreReturnedOnce() {
List<Integer> run1 = bag.getMany(10);
List<Integer> run2 = bag.getMany(10);
List<Integer> run3 = bag.getMany(10);
specify(run1, does.containExactly(expectedValues));
specify(run2, does.containExactly(expectedValues));
specify(run3, does.containExactly(expectedValues));
}
public void onFollowingRunsTheValuesAreInADifferentRandomOrderThanBefore() {
List<Integer> run1 = bag.getMany(10);
List<Integer> run2 = bag.getMany(10);
List<Integer> run3 = bag.getMany(10);
specify(run1, does.not().containInOrder(run2));
specify(run1, does.not().containInOrder(run3));
specify(run2, does.not().containInOrder(run3));
}
public void valuesAddedDuringARunWillBeIncludedInTheFollowingRun() {
List<Integer> additionalValues = Arrays.asList(10, 11, 12, 13, 14, 15);
List<Integer> expectedValues2 = new ArrayList<Integer>();
expectedValues2.addAll(expectedValues);
expectedValues2.addAll(additionalValues);
List<Integer> run1 = bag.getMany(5);
for (Integer i : additionalValues) {
bag.add(i);
}
run1.addAll(bag.getMany(5));
List<Integer> run2 = bag.getMany(16);
specify(run1, does.containExactly(expectedValues));
specify(run2, does.containExactly(expectedValues2));
}
}
public class AShuffleBagWithManyOfTheSameValue {
private ShuffleBag<Character> bag;
private List<Character> expectedValues = Arrays.asList('a', 'b', 'b', 'c', 'c', 'c');
public ShuffleBag<Character> create() {
bag = new ShuffleBag<Character>(new Random(123L));
bag.addMany('a', 1);
bag.addMany('b', 2);
bag.addMany('c', 3);
return bag;
}
public void allValuesAreReturnedTheSpecifiedNumberOfTimes() {
List<Character> values = bag.getMany(6);
specify(values, does.containExactly(expectedValues));
}
}
public class AnEmptyShuffleBag {
private ShuffleBag<Object> bag;
public ShuffleBag<Object> create() {
bag = new ShuffleBag<Object>();
return bag;
}
public void canNotBeUsed() {
specify(new jdave.Block() {
public void run() throws Throwable {
bag.get();
}
}, should.raise(IllegalStateException.class));
}
}
}
Aqui está a implementação, no caso de você querer vê-lo também:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @author Esko Luontola
* @since 25.2.2008
*/
public class ShuffleBag<T> {
private final Random random;
/**
* Unused values are in the range {@code 0 <= index < cursor}.
* Used values are in the range {@code cursor <= index < values.size()}.
*/
private final List<T> values = new ArrayList<T>();
private int cursor = 0;
public ShuffleBag() {
this(new Random());
}
public ShuffleBag(Random random) {
this.random = random;
}
public void add(T value) {
values.add(value);
}
public T get() {
if (values.size() == 0) {
throw new IllegalStateException("bag is empty");
}
int grab = randomUnused();
T value = values.get(grab);
markAsUsed(grab);
return value;
}
private int randomUnused() {
if (cursor <= 0) {
cursor = values.size();
}
return random.nextInt(cursor);
}
private void markAsUsed(int indexOfUsed) {
cursor--;
swap(values, indexOfUsed, cursor);
}
private static <T> void swap(List<T> list, int x, int y) {
T tmp = list.get(x);
list.set(x, list.get(y));
list.set(y, tmp);
}
public void addMany(T value, int quantity) {
for (int i = 0; i < quantity; i++) {
add(value);
}
}
public List<T> getMany(int quantity) {
List<T> results = new ArrayList<T>(quantity);
for (int i = 0; i < quantity; i++) {
results.add(get());
}
return results;
}
}
Não há necessidade de teste de aleatoriedade - que já está implícito em sua escolha de algoritmo e gerador de números aleatórios. Utilizar a Fisher-Yates / Knuth baralhar algoritmo:
http://en.wikipedia.org/wiki/Knuth_shuffle
A implementação Java a partir dessa página Wikipedia:
public static void shuffle(int[] array)
{
Random rng = new Random(); // java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
n--; // n is now the last pertinent index
int k = rng.nextInt(n + 1); // 0 <= k <= n.
// Simple swap of variables
int tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
}