Sample MT2 Solutions
Trapezoids
trapezoids.cpp
#include <iostream>
using namespace std;
int main()
{
int b1a, b1b, b2a, b2b;
cin >> b1a >> b1b >> b2a >> b2b;
int sum1 = b1a+b1b;
int sum2 = b2a+b2b;
if( sum1 == sum2 ) {
cout << "Equal" << endl;
}
else if (sum1 < sum2) {
cout << 5*sum1/2.0 << endl;
}
else {
cout << 5*sum2/2.0 << endl;
}
return 0;
}
Reverse Digits
revdig.cpp
// Output digits of input number in reverse order.
// If number is negative, output nothing.
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num;
if(num >= 0) {
do {
cout << num % 10;
num /= 10;
} while( num > 0);
cout << endl;
}
return 0;
}
Distance
distance.cpp
#include <iostream>
using namespace std;
// Function to print out the results
// Input: isDistanced = true if all people are at least 6 feet apart
// Input: lineLength = distance from the first to last person in line
// Prints "distanced" or "not distanced" on one line and the
// line length on the next line.
void printResults(bool isDistanced, double lineLength);
int main()
{
double start, prev, next;
cin >> prev;
start = prev;
bool distanced = true;
bool first = true;
while(prev >= 0) {
cin >> next;
if(next == -1) break;
double dist = next-prev;
if( dist < 6) {
distanced = false;
}
prev = next;
}
printResults(distanced, prev-start);
return 0;
}
// Complete the definition of printResults, whose operation
// is described above the prototype
void printResults(bool isDistanced, double lineLength)
{
if(isDistanced) {
cout << "distanced" << endl;
}
else {
cout << "not distanced" << endl;
}
cout << lineLength << endl;
}
Duplicates
duplicates.cpp
#include <iostream>
using namespace std;
int main()
{
int data[250]; // n will be 250 or less
int n;
cin >> n;
for(int i=0; i < n; i++) {
cin >> data[i];
}
int num = 0;
for(int i=0; i < n; i++) {
bool foundDuplicate = false;
for(int j=0; j < n; j++) {
if(i != j && data[i] == data[j]) {
foundDuplicate = true;
break;
}
}
if(!foundDuplicate) {
num++;
}
}
if(num > 0) {
cout << "Numbers with no duplicate: " << num << endl;
}
else {
cout << "All numbers have a duplicate" << endl;
}
return 0;
}
