Change language

PHP program for finding missing elements in an array

| |
Examples:
Input: arr [] = (1, 2, 3, 4, 6, 7, 8) Output: 5 The array minimum is 1 and maximum is 8. The missing element in range from 1 to 8 is 5. Input: arr [] = (10, 11, 14, 15) Output: 12, 13 
This problem can be solved by iterating through the array by observing related differences between elements. But in PHP we can use some built-in functions to solve the problem.For this we need the following two functions:
  • range() function : This function is used to create an array of elements of any type, such as an integer, alphabets in a given range (low to high), i.e. That is, the first item in the list is considered low, and the last - high.
  • array_diff() function : if we have an array of elements, we can find the missing elements by comparing the two arrays.
  • The idea behind solving this problem using the two built-in functions is to first use the range() function to create a new array from the starting element and the maximum an element of the original array using the max() function. We then use array_diff() to compare the newly created array and the original array, thus getting all the missing elements of the original array. // PHP code to find missing items function not_present ( $list ) { // Create an array with a range from an array // minimum to maximum. $new_array = range (min ( $list ), max ( $list )); // Find those elements that are present // in new_array, but not in this list return array_diff ( $new_array , $list ); } // Driver code print_r (not_present ( array (1, 2, 3, 4, 7, 8))); print_r (not_present ( array (10, 11, 12, 14, 15, 16))); ?> Output:
    Array ([ 4] = > 5 [5] = > 6) Array ([3] = > 13) 

    Shop

    Learn programming in R: courses

    $

    Best Python online courses for 2022

    $

    Best laptop for Fortnite

    $

    Best laptop for Excel

    $

    Best laptop for Solidworks

    $

    Best laptop for Roblox

    $

    Best computer for crypto mining

    $

    Best laptop for Sims 4

    $

    Latest questions

    NUMPYNUMPY

    psycopg2: insert multiple rows with one query

    12 answers

    NUMPYNUMPY

    How to convert Nonetype to int or string?

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Javascript Error: IPython is not defined in JupyterLab

    12 answers


    Wiki

    Python OpenCV | cv2.putText () method

    numpy.arctan2 () in Python

    Python | os.path.realpath () method

    Python OpenCV | cv2.circle () method

    Python OpenCV cv2.cvtColor () method

    Python - Move item to the end of the list

    time.perf_counter () function in Python

    Check if one list is a subset of another in Python

    Python os.path.join () method