(Algorithm) When we do not have an official detector, the logarithm can solve the detection of our own code. The meaning and usage of the logarithm are accepted below.

  • The role of the logarithm

When we practice algorithm questions, the questions are solved, and we usually rely on the online detector for inspection, so can we not rely on it? The logarithm was born from this, and it is used as a tool for us to check whether our code is qualified.

For example, we need to sort an array. I have many methods. I can recurse, bubble, or directly brute force. I compare and traverse one by one (this is the most correct method I can determine, but it The time complexity may also be the largest). When writing a recursion, it is not sure whether it is completely sorted correctly, you can make a random array generator, and then use our recursion and our safe brute force solution (or the sorting sort that comes with the system) at the same time Sort the array, then compare the two sets of arrays bit by bit, if the result is True , pass.

The following uses a logarithm code for sorting detection to combine references

public static main(strin[] args){
  int testTime = 5000;
  int maxSize = 100;
  int maxValue = 100;
  boolean succed = true;
  for(int i = 0; i < testTime; i++){
    int[] arr1 = generateRandomArray(maxSize,maxValue);
    int[] arr2 = copyArray(arr1);
    insertionSort(arr1);
    comparator(arr2);
    if(!isEqual(arr1,arr2)){
      succed = false;
    }    
  }
  system.out.printl(succed?"Nice!":"Oh! My God!");
}

testTime defines the number of times I want to test, maxSize defines the maximum length of the random array, and maxValue is the maximum random number of the array. where generateRandomArray is my random array generator which will be written outside.

arr2 as another copy of the array, insertionSort is the system's own sorting, use it and our own sorting algorithm comparator to sort at the same time, and then compare bit by bit ( isEqual ), as long as there is one bit in the two sorted arrays If the numbers above are different, false will be output .

This ensures that even if there is no online test for a topic, we can still practice it

Supongo que te gusta

Origin blog.csdn.net/qq_48860282/article/details/123726361
Recomendado
Clasificación