0

I want to have a function that would browse through the natural numbers array of any size ({0,1,2....}) and find a missing value.

What i mean is that if the array is e.g : {0,1,3,4,5} i want the function to return 2, if array is {1,3,0,4} i want the function to return 2 and so on...

My attempt is:

int missing(int* t, int r) {
    int i;
    int sum=0;
    sum=(r+1)*(r+2)/2;
    for(i=0;t[i];i++){
        sum-=t[i];
    }
    return sum;
}

The idea was to first calculate the sum from 1 to n and than subtract from this sum each number in an array separately. However the program returns total sum without subtraction of the numbers in an array.

Why it is not working correctly?

1
  • for(i=0;t[i];i++) this makes no sense at all - did you mean for(i = 0; i < r; i++)? Commented Nov 7, 2016 at 19:23

2 Answers 2

2

Use condition i < r instead t[i]. First value of sequence is zero, therefore loop is not traversed

Moreover you can use optimized version of algorithm (unfortunately I don't have opportunity to test code -- it is just idea for only sorted array)

int res = 0;
for (int i = 0; i < r && t[i] == res; ++i, ++res) ;
Sign up to request clarification or add additional context in comments.

Comments

-1

This function allows you to find missing numbers within the given array.

<?PHP

function FindMissingArr($args)
{
    $max = max($args);
    $min = min($args);


    $range = range($min, $max);

    $find = [];

    $result = array_diff($range, $args);

    foreach ($result as $key => $value) {
        array_push($find, $value);
    }

    return $find;
}~

$arr = array(1, 5, 8, 21);
print_r(FindMissingArr($arr));

?>

Result:

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 6 [4] => 7 [5] => 9 [6] => 10 [7] => 11 [8] => 12 [9] => 13 [10] => 14 [11] => 15 [12] => 16 [13] => 17 [14] => 18 [15] => 19 [16] => 20 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.