Give the range of integers. Find and print absolute values of the two numbers with the least difference.
Input format: The first line is N - the number of integers in the list.
Next lines are N integers separated by spaces.
Constraint: 1 <N <100; Integers in segments [-10000, 10000]
Output format: The absolute value of the two numbers in the range is the smallest difference.
(a) store the numbers in a std::vector<int>; (b) std::sort() the vector; (c) apply std::unique() to check if all numbers are uniqe, else 0 is our answer – http://en.cppreference.com/w/cpp/algorithm/unique; (d) in case all numbers are unique, since the vector is sorted now you only need to check absolute values of the difference of adjacent numbers
I think I'd go with Enoizat's advice (choice of a set as a container that is ... not the romantic attachment to one!)
- it will do the sorting for you as you insert elements;
- you can stop reading any more integers if it finds any that are already in the set and you can immediately report 0 as the minimum difference
// Give the range of integers. Find and print absolute values of the two
// numbers with the least difference.
// Input format: The first line is N - the number of integers in the list.
// Next lines are N integers separated by spaces.
// Constraint: 1 <N <100; Integers in segments [-10000, 10000]
// Output format: The absolute value of the two numbers in the range
// is the smallest difference.
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <set>
bool isInRange(int value);
void waitForEnter();
int main()
{
int howmany {};
do {
std::cout << "How many numbers do you want to evaluate (1-100)? ";
std::cin >> howmany;
std::cin.ignore(1);
if(100 < howmany || howmany < 1) {
std::cout << "Accepted value ranges from 1 to 100.\n";
}
} while(howmany < 1 || 100 < howmany);
std::cout << "Please insert your numbers separated by spaces.\n""Numbers can range from -10000 to 10000.\n""> ";
std::set<int> sequence;
for(int i{}; i<howmany; i++) {
int tmp;
std::cin >> tmp;
std::cin.ignore(1);
if(!isInRange(tmp)) {
std::cout << "Number out of range found: " << tmp
<< "\nExiting program\n";
return 1; // bad user input
}
if(!(sequence.insert(tmp)).second) {
std::cout << "Duplicate found: " << tmp
<< "\nTherefore smallest distance is 0\n";
return 2; // duplicate number
}
}
int distance {abs(-10000 - 10000) + 1};
for(auto it{sequence.cbegin()}, it2{std::next(it)};
it!=sequence.cend() && it2!=sequence.cend();
it = it2++) {
int tmp = abs(*it - *it2);
if(distance > tmp) { distance = tmp; }
}
std::cout << "\nSmallest distance between your numbers is " << distance
<< '\n';
waitForEnter();
return 0;
}
bool isInRange(int value)
{ return (-10000 <= value && value <= 10000); }
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}