Mini Poker Consecutive Values
National Olympiad — Municipal round (2012 season)
Submission name: minipoker.cpp
Problem summary
Given five values, print them sorted if they form five consecutive integers. Otherwise print only their maximum.
Input
Five integers between 1 and 13.
Output
The five sorted consecutive integers, or just the maximum.
Constraints
Exactly five values, each in [1,13].
Worked example
Input and output for the worked example discussed below.
Input
1 5 2 4 3
Output
1 2 3 4 5
Solution analysis
- Sort the five values. Sorting exposes both the maximum, at the last position, and every possible gap between neighbouring values.
- The values are consecutive exactly when all four adjacent differences equal 1. This also rejects repeated values; checking only maximum−minimum=4 would not do that.
- The sample sorts to 1,2,3,4,5, so print all five. The alternative sample 1,1,4,1,4 has repeated values and gaps, so print its maximum 4 instead.
Why it works
A strictly consecutive sorted sequence has every adjacent difference 1. Conversely, if every difference is 1, each sorted value equals the first plus its index, which is precisely a set of five consecutive integers. The sorted final value is the maximum in every case.
Watch out. Duplicates are not consecutive. Do not print the entire sorted list when the check fails. Five values are read even though there is no leading count.
Commented C++17 solution
An independently written complete program with standard headers.
#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<limits>
#include<map>
#include<numeric>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main(){
array<int,5>values;
for(int&value:values){
cin>>value;
}
sort(values.begin(),values.end());
bool consecutive=true;
for(int index=1;index<5;index++){
// Every sorted neighbour must differ by exactly one.
if(values[index]!=values[index-1]+1){
consecutive=false;
}
}
if(!consecutive){
cout<<values.back()<<'\n';
}
else{
for(int index=0;index<5;index++){
if(index>0){
cout<<' ';
}
cout<<values[index];
}
cout<<'\n';
}
}