// Programmer: Simon Thougaard
// File: conversion.cpp
// Purpose: Source file, implementing functions for converting numbers
// from different number bases
using namespace std;
#include<iostream>
#include <cstdlib>
#include "conversion.h" // Associated header
void displayMenu()
{
cout << "Please select one of the following options:" << endl;
cout << "\t1) Enter x" << endl;
cout << "\t2) Enter n" << endl;
cout << "\t3) Check valid pair" << endl;
cout << "\t4) Force valid n" << endl;
cout << "\t5) Force valid x" << endl;
cout << "\t6) Convert" << endl;
cout << "\t7) Quit" << endl;
}
void promptForX(int & x, bool & xSet)
{
short attempts = 0;
xSet = false;
do
{
cout << "Please enter a new x between " << MIN_X
<< " and " << MAX_X << " :" << endl;
cin >> x;
if(x >= MIN_X && x <= MAX_X)
{
// If x is valid, we quit the loop
xSet = true;
cout << "x has been set to " << x << endl;
}
attempts++;
} while(!xSet && attempts < MAX_ATTEMPTS);
return;
}
void promptForN(short & n, bool & nSet)
{
short attempts = 0;
nSet = false;
do
{
cout << "Please enter a new n between " << MIN_N
<< " and " << MAX_N << " :" << endl;
cin >> n;
if(n >= MIN_N && n <= MAX_N)
{
// If n is valid, we quit the loop
nSet = true;
cout << "n has been set to " << n << endl;
}
attempts++;
}while(!nSet && attempts < MAX_ATTEMPTS);
return;
}
bool checkValidPair(const int x, const short n)
{
bool validPair = true;
int divisor = 1;
short digit;
// Loop over the digits right to left, or until we find a bad digit
while(validPair && divisor <= MAX_DIVISOR)
{
digit = (x/divisor) % 10; // Calculate current digit
if(digit >= n)
{
validPair = false; // Invalid digit discovered
}
divisor *= 10;
}
return validPair;
}
short forceN(const int x)
{
short new_n = 0;
int divisor = 1;
short digit;
// Loop over each digit
for(int i = 0; i < 5; i++)
{
digit = (x/divisor) % 10; // Calculate current digit
if(digit >= new_n)
{
// Update new_n to smallest valid n
new_n = digit + 1;
}
divisor *= 10;
}
return new_n;
}
int forceX(const int x, const short n)
{
short new_x = 0;
int divisor = 1;
short digit;
// Loop over each digit
for(int i = 0; i < 5; i++)
{
digit = (x/divisor) % 10; // Calculate current digit
if(digit >= n)
{
// Generate random valid digit
digit = (rand()%n);
}
new_x += digit * divisor; // Update new_x
divisor *= 10;
}
return new_x;
}
int convert(const int x, const short n)
{
int result = 0;
int divisor = 1;
int multiplier = 1;
short digit;
// Loop over each digit
for(int i = 0; i < 5; i++)
{
digit = (x/divisor) % 10; // Calculate current digit
result += digit * multiplier; // Update the result value
multiplier *= n; // Update multiplier from 1 to n, n^2, n^3...
divisor *= 10;
}
return result;
}