All files / sorts BogoSort.test.js

0% Statements 0/22
0% Branches 0/2
0% Functions 0/4
0% Lines 0/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                                                                                         
import BogoSort from './BogoSort';
import Action from '../../components/sorts/BarChartActions';
import isSorted from '../../utils/isSorted';
import getRandomInt from '../../utils/getRandomInt';
 
describe('BogoSort.js', () => {
  it('should sort the given random input', () => {
    const numTests = 1000;
    const inputSize = 5;
    for (let i = 0; i < numTests; i += 1) {
      const randomNumbers = new Array(inputSize)
        .fill(null)
        .map((_) => getRandomInt(0, 100));
      const sortedOutput = BogoSort(randomNumbers, true);
      expect(isSorted(sortedOutput)).toBe(true);
    }
  });
  test.each([
    // No input
    [[], []],
    // Sorted input
    [[1, 2, 3, 4, 5], []],
    // Reverse input
    [[5, 4, 3, 2, 1], []],
    // Only one number
    [[4], []],
    // Repeating numbers
    [[1, 2, 1], []],
    // Random input
    [[3, 8, 2, 7, 1], []],
  ])('steps lead to a sorted result, input %#: %p', (input, expectedOutput) => {
    const inputCopy = Array.from(input);
    // steps cannot be tested because they are randomized.
 
    const steps = BogoSort(input);
 
    // apply exchange actions
    for (let i = 0; i < steps.length; i += 1) {
      if (steps[i].do[0].action === Action.EXCHANGE) {
        const a = steps[i].do[0].elements[0];
        const b = steps[i].do[0].elements[1];
        // exchange
        const t = inputCopy[a];
        inputCopy[a] = inputCopy[b];
        inputCopy[b] = t;
      }
    }
 
    // check if result is sorted
    expect(isSorted(inputCopy)).toBe(true);
  });
});