The Gift Password
Autumn Tournament (2011)
Submission name: gift.cpp
Problem summary
A six-character lock password alternates uppercase letters and digits, starting with a letter. Its three distinct letters are in alphabetic order and its three distinct digits are in decreasing order. Given the letters followed by the digits in arbitrary order, reconstruct the password.
Input
Three distinct uppercase Latin letters followed by three distinct digits. The sample has no spaces.
Output
The six password characters with no spaces.
Constraints
Exactly three distinct uppercase Latin letters and three distinct decimal digits.
Worked example
Original statement sample, translated without changing its numeric data.
Input
WKN387
Output
K8N7W3
Solution analysis
- Read the six characters separately; character extraction also handles the unspaced sample. Store the first three as letters and the remaining three as digits.
- Sort the letters increasingly and the digits increasingly. Emit each letter followed by the digit from the opposite end of the sorted digit array.
- WKN becomes KNW and 387 becomes 378. Pairing increasing letters with decreasing digits gives K8N7W3.
Why it works
Sorting gives exactly the prescribed order within each character type. Alternating the ith letter with the ith largest digit puts every type in its prescribed positions, so the emitted password satisfies all conditions and is unique.
Watch out. Digits must decrease while letters increase. Do not print separators between characters.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
char letters[3],digits[3];
for(char&letter:letters){
cin>>letter;
}
for(char&digit:digits){
cin>>digit;
}
sort(letters,letters+3);
sort(digits,digits+3);
for(int i=0;i<3;i++){
// Reverse the digit order while interleaving the types.
cout<<letters[i]<<digits[2-i];
}
cout<<'\n';
}