school/cs142/lab04/number.cpp

112 lines
2.8 KiB
C++

#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <sstream>
#include <cmath>
#include <algorithm>
using namespace std;
int bit2dec(string s);
vector<int> get_numbers(int pow, int compliment) {
string store;
vector<int> numbers;
int constant = compliment;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
for(int k = 0; k < 2; k++){
for(int l = 0; l < 2; l++){
ostringstream stream;
if(pow == 0){
stream << i << j << k << l << constant;
}
else if(pow == 1){
stream << i << j << k << constant << l;
}
else if(pow == 2){
stream << i << j << constant << k << l;
}
else if(pow == 3){
stream << i << constant << j << k << l;
}
else if(pow == 4){
stream << constant << i << j << k << l;
}
store = stream.str();
numbers.push_back(bit2dec(store));
}
}
}
}
return numbers;
}
ostream & operator<<(ostream & os, const vector<int> & nums) {
for(unsigned int i = 0; i < nums.size(); i++){
if(i % 4 == 0){
os << endl;
}
os << nums[i] << " ";
}
return os;
}
int bit2dec(string s) {
int total = 0;
int power = 0;
for(int i = s.size() - 1; i >= 0; i--) {
if(s[i] == '1') {
total += pow(2,power);
}
power++;
}
return total;
}
int main() {
srand (time(NULL));
int keep_playing = 0;
while(keep_playing == 0){
ostringstream answer;
for(unsigned int i = 0; i < 5 ; i++) {
int switcher = rand() % 2;
string check;
cout << "Is your number in this list? enter y for yes n for no" << endl;
cout << get_numbers(i, switcher) << endl;
cin >> check;
if(switcher == 0){
if(check == "y") {
answer << '0';
}
else {
answer << '1';
}
}
if(switcher == 1) {
if(check == "y") {
answer << '1';
}
else {
answer << '0';
}
}
}
string final = answer.str();
reverse (final.begin(), final.end());
cout << bit2dec(final) << endl;
cout << "Do you want to keep playing? enter y for yes, n for no" << endl;
string check;
cin >> check;
if(check == "n"){
keep_playing++;
}
}
return 0;
}