vendredi 27 novembre 2020

Test cases and benchmark for algorithm correctness and efficiency

Write a function: function smallestInt(A);

that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

Example: given A = [1, 3, 6, 4, 1, 2], the function should return 5.

Given A = [1, 2, 3], the function should return 4. Given A = [-1, -3], the function should return 1.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].

Write test cases to validate that your implementation conforms to the specification.

Additionally, implement the benchmark function to test the performance of your solution. The benchmark should be able to run in the browser and be capable of outputting a reasonably reliable score when comparing solutions in the same environment.

Here is my code, I did it in Vue:

<template>
  <div align="center">
    <button @click="runTests()">Run Tests</button>
    <button @click="runBenchmark()">Run Benchmark</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      result: null,
    };
  },
  props: {
    msg: String,
  },
  methods: {
    smallestInt(A) {
      let N;
      let i = 1;
      // Remove duplicate numbers from the array.
      // Set only lets you store unique values.
      // Then convert it back to an array using the spread operator
      A = [...new Set(A)];
      // N is an integer within the range [1..100,000];
      A = A.filter((x) => x >= 1 && x <= 100000)
      A = A.sort((a, b) => a - b);

      while (!N) {
        if (A[i - 1] !== i) {
          N = i;
        }
        i++;
      }
      this.result = N;
    },
    runTests() {
      console.clear();
      const testArray = [-2,0,1,2,3,4,7];
      this.smallestInt(testArray);
      // print results to console
      console.log(this.result);
    },
    runBenchmark() {
      console.clear();

      // print result to console
    },
  },
};
</script>

Is there a way to make this more efficient than O(n)? Also I'm not very experienced writing test cases or benchmarks, what would be the strategy for writing test cases for this. And I have no idea how to go about a benchmark, any tips? Thanks!

Aucun commentaire:

Enregistrer un commentaire