-1

I write a code, that finding a difference between two array sequences. There are a lot of versions that I tried and succeeded in.

#include <iostream>

int main() {
  const int N = 10;
  int inputFirst[N];
  int inputSecond[N];
  int output[N];
  int j = 0;
  for (int i = 0; i < N; i++) {
    std::cin>>inputFirst[i];
  }
  for (int i = 0; i < N; i++) {
    std::cin>>inputSecond[i];
  }
  for (int i = 0; i < N; i++) {
    if (inputFirst[i] != inputSecond[i]) {
      output[j++] = inputFirst[N - I];
    }
  }
  for (int i =0; i <j; i++) {
    std::cout<<output[i]<<" ";
  }
}

How can I change my code to get the right answer for this input case?

15 -50 68 78 194 66 752 -111 789 -1000
0 -10000 85 -50 456 -111 854 15 -752 78

I need to get this answer:

68 194 66 752 789 -1000
ocrdu
  • 2,172
  • 6
  • 15
  • 22
  • You are just checking if the number in the first array in not found in the corresponding position in the second array. Obviously you need to check if the number in the first array is not found in **any** position in the second array. For that you need another loop. The simple way is to write a function that checks one integer to see if it is anywhere in an array. Once you written that function you can then use it in the main function. That's the easy way to write programs, break the problem into smaller pieces, don't try and solve everything in in one big mess of code. – john Dec 13 '20 at 18:30

1 Answers1

3

You are comparing the items by their indexes. You should check that second sequence contains an item that is in first sequence or not. (or vice versa) If you iterate over the first sequence and check that if item appears in second sequence, you will get what you want.

In short, numbers can appear at different indexes.

Lets write a simple helper function ;

bool contains(const int* array, int size, int item)
{
    for (int i = 0; i < size; ++i)
        if(array[i]==item)
             return true;
    return false;
}

And use this helper function ;

for (int i = 0; i < N; i++) {
   if(!contains(inputSecond,N,inputFirst[i]))
        output[j++] = inputFirst[i]
  }
tango-1
  • 330
  • 1
  • 10