// file project04.cpp
// date 09/14/2007
// author AOU
#include <iostream>
#include <ctime>
using namespace std;
/*
Problem:
Write a function that will find the highest two
values out of the three values given
given: x, y, z
expected: a, b such that a and b are top two values of x, y, z
and a>=b
Examples:
Input (3,1,2) => (3,2)
Input (1,1,2) => (2,1)
Input (5,5,5) => (5,5)
Algorithm:
input x,y,z
output a,b
option1: use any sort to put x,y,z in increasing order, a=z,b=y
if x>y then swap(x,y)
if x>z then swap(x,z)
if y>z then swap(y,z)
a=z
b=y
option2: compare values 9x,y,z) and calculate a,b
if x>=y and x>=z then
a=x
if y>=z then b=y else b=z
else if y>=x and y>=z then
a=y
if x>=z then b=x else b=z
else
a=z
if x>=y then b=x else b=y
end if
option3: use any sort to put x,y,z in increasing order, a=z,b=y
do the following 2 times
if x>y then swap(x,y)
if y>z then swap(y,z)
end do
a=z
b=y
*/
void findMax2(int x, int y, int z, int &a, int &b);
void findMax2v2(int x, int y, int z, int &a, int &b);
void findMax2v3(int x, int y, int z, int &a, int &b);
void swap(int &p, int &q);
void main(void)
{
cout << time(NULL) << endl;
srand(time(NULL));
int x, y, z;
int v1, v2;
for (int i=1; i<=100; i++)
{
x = rand()%100;
y = rand()%100;
z = rand()%100;
findMax2(x,y,z,v1,v2);
cout << "(x, y, z)=" << "(" << x << ", " << y << ", " << z << ")\n";
cout << " (v1, v2) =" << "(" << v1 << ", " << v2 << ")\n";
findMax2v2(x,y,z,v1,v2);
cout << " (v1, v2) =" << "(" << v1 << ", " << v2 << ")\n";
findMax2v3(x,y,z,v1,v2);
cout << " (v1, v2) =" << "(" << v1 << ", " << v2 << ")\n";
cout << endl;
}
}
void findMax2(int x, int y, int z, int &a, int &b)
// based on option3
{
for (int i=1; i<=2; i++)
{
if (x>y) swap(x,y);
if (y>z) swap(y,z);
}
a=z;
b=y;
}
void swap(int &p, int &q)
{
int temp = p;
p = q;
q = temp;
}
void findMax2v2(int x, int y, int z, int &a, int &b)
{
if (x>y) swap(x,y);
if (x>z) swap(x,z);
if (y>z) swap(y,z);
a=z;
b=y;
}
void findMax2v3(int x, int y, int z, int &a, int &b)
{
a=911;
b=911;
if ((x>=y) && (x>=z))
{
a=x;
if (y>=z) b=y; else b=z;
}
else if ((y>=x) && (y>=z))
{
a=y;
if (x>=z) b=x; else b=z;
}
else
{
a=z;
if (x>=y) b=x; else b=y;
}
}
/*
bool checkMax2(int x, int y, int z, int a, int b)
make sure [a, b] is a subset of [x, y, z]
make sure a >= b
make sure a is max of [x,y,z]
make sure b is max of [x,y,z]-[a]
*/
|