Home > database >  How to make an array reject a duplicate as the user inputs them
How to make an array reject a duplicate as the user inputs them

Time:03-15

I have to ask the user to put in an array size and then to ask the user to fill it out. When the user puts in a duplicate, the program should say "invalid" and the user is asked to replace the number. I am supposed to use traversing array search.

Like this example here:

Enter list size: 4
Enter value for index 0: 1
Enter value for index 1: 1
Invalid. Enter a new number: 2
Enter value for index 2: 5
Enter value for index 3: 6

This is my code so far:

#include <iostream>

using namespace std;

int main() {
  int size;
  cout << "Enter list size: ";
  cin >> size;
  int array1[size];

  for (int i = 0; i < size; i  ) {
    cout << "Enter value for index " << i << ": ";
    cin >> array1[i];
    for (int j = i   1; j < size; j  ) {
      if (array1[i] == array1[j]) {
        cout << "Invalid! Enter a new value for index " << i << ": ";
        cin >> array1[i];
      }
    }
  }
  return 0;
}

CodePudding user response:

It does what was specified but the exercise probably was to write std::ranges::find.

#include <iostream>
#include <vector>
#include <cstddef>
#include <algorithm>

int main() {
    size_t size;
    std::cout << "Enter list size: ";
    std::cin >> size;

    std::vector<int> arr;
    arr.reserve(size);

    while(arr.size() < size) {
        int t;
        std::cout << "Enter value for index " << arr.size()   1 << ": ";
        std::cin >> t;
        if (std::ranges::find(arr, t) == arr.end()) {
            arr.push_back(t);
        } else {
            std::cout << "Invalid! ";
        }
    }
}

CodePudding user response:

Try this approach, Every time user enter value helper function will check duplicate from already filled array

#include<iostream>

// Helper Function that will check duplicate from array
bool IsDuplicate (int arr[] ,const int idxSoFar, int element){
    for(int i =0 ; i < idxSoFar ; i  = 1 )
        if( arr[i] == element){
          std::cout << "Invalid! Enter a new value for index "<< idxSoFar   1 << " : ";     
          return  arr[i] == element;
        }
   return false;       
}

int main () {
   int size;
   std::cout << "Enter list size: ";
   std::cin >> size;
   int array1[size];

   for (int i = 0; i < size; i  ) {
     std::cout << "Enter value for index " << i << ": ";
     do
       std::cin >> array1[i];
     while(IsDuplicate(array1 , i , array1[i]));
   }
   return 0;
}
  •  Tags:  
  • c
  • Related