top2Of3_01
Home ] Up ]

 

//file:   top2Of3_01.cpp
//author: AOU

/*
Prototype:
  bool top2Of3_verify(int x, int y, int z, int a, int b)

Problem Definition:
  verify that a and b are the top two values from x,y,z
  return true if this is the case else return false
Preconditions:
  x,y,z,a,b should be in given range and defined
Postconditions:
  x,y,z,a,b should not be modified
  should return true if
       if the values of x,y,z are sorted (asc) and 
          put in v1,v2,v3 then
          a should be = v3 and b should be = v2 
     else
       return false
Examples:
  top2Of3_verify(1,2,3, -1,3) => false
  top2Of3_verify(1,2,3, 3,2)  => true
  top2Of3_verify(1,2,3, 3,1)  => false

Algorithm:
  array[0]=x
  array[1]=y
  array[2]=z

  sortAscBubble(array)

  if (a != array[2]) return false |
  if (b != array[1]) return false |or return (a==array[2] && b==array[1])
                                  |
  return true                     |

Source Code:

*/

/*
Problem Definition: 
Write a function to find the top two values out of given three values.
Type of values=?
Where are the values?
Range of values?
Order of output?
Where does the output go?

Examples:
1,2,3 => 3,2

Algorithm: Top2Of3(x,y,z,a,b)
Sort in increasing order
Output the last two values
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


*/
#include <iostream>
#include <ctime>

using namespace std;

void top2Of3(int x, int y, int z, int &a, int &b);
void swap(int &v, int &w);
void test_top2of3(void);

bool top2Of3_verify(int x, int y, int z, int a, int b);

// top2Of3_verify(1,2,3,4,5)=>false
// top2Of3_verify(1,2,3,3,2)=>true

const int MIN_NUMBER = -99;
const int MAX_NUMBER = +99;
const int TEST_COUNT = 100;

void main(void)
  {
  srand( (unsigned)time( NULL ) );
  //srand(123);

  test_top2of3();

  }

int myRand(void)
  {
  //returns a random number from [MIN_NUMBER, MAX_NUMBER

  /*

  [0,9]  rand()%(9-0+1)
  [1,9]  1 + rand()%(9-1+1)
  [-1,9] -1 + rand()%(9-(-1)+1)
  [x,y]  x + rand()%(y-x+1)

  */

  return MIN_NUMBER + rand()%(MAX_NUMBER-MIN_NUMBER+1);
  }


void test_top2of3(void)
  {
  int v1,v2,v3;
  int r1, r2;

  v1 = 1;
  v2 = 2;
  v3 = 3;
  r1 = 0;
  r2 = 0;

  for (int i=1; i<=TEST_COUNT; i++)
    {
    v1 = myRand();
    v2 = myRand();
    v3 = myRand();

    top2Of3(v1,v2,v3,r1,r2);

    cout << "v1=" << v1 << endl;
    cout << "v2=" << v2 << endl;
    cout << "v3=" << v3 << endl;
    cout << "r1=" << r1 << endl;
    cout << "r2=" << r2 << endl;
    
    if(top2Of3_verify(v1,v2,v3,r1,r2))
      cout << "works\n";
    else
      cout << "********DID NOT WORK********\n";

    cout << "-----------------------\n";
    }

  }

void swap(int &v, int &w)
  {
  int temp = v;
  v = w;
  w = temp;
  }

void top2Of3(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;
  }

bool top2Of3_verify(int x, int y, int z, int a, int b)
  {
  return true;
  }