help to turn numbers into symbols? - c++

I want this code to represent symbols and not numbers (A, O, X)?
Can someone give me a simple code to make the numbers into symbols? Thanks
int game[3][3];
int x, y;
int lines = 0;
// select a random grid
srand(time(0));
for(x = 0; x < 3; x++) {
for(y = 0; y < 3; y++) {
game[x][y] = rand() % 3;
cout << game[x][y];
if (y == 2)
cout << '\n';
}
}
for (y = 0; y < 2; y++)
if (game[0][y] == game[1][y] && game[0][y] == game[2][y])
lines++;

You can use a lookup table:
char convert_number_to_letter(unsigned number)
{
static const char characters[] = "AOX";
if (number >= sizeof(characters) - 1)
return '\0'; // or other error handling
return characters[number];
}

chat c;
switch(game[x][y])
{
case 0:
c = 'A';
break;
case 1:
c = 'O';
break;
case 2:
c = 'X';
break;
}
or
char c;
if(game[x][y] == 0)
c = 'A';
else if(game[x][y] == 1)
c = 'O';
else
c = 'X';

Use another array, filled with the desired character values, then index that array with the generated random number:
char chars[] = { 'A', 'O', 'X' };
...
for(x = 0; x < 3; x++) {
for(y = 0; y < 3; y++) {
game[x][y] = chars[rand() % 3];
...
}
}

Related

Move a Character in a 2d Array

I'm taking an intro to c++ class and I am quite stuck on a part to this project.
I need to have my character, 'H' move freely around the array. I have written a good amount of my code, but when I compile and run it, my hero isn't given the option to move. I don't know what is going wrong when I am calling my function in main. Any help would be gladly appreciated. I need his new position in the array to be maintained so that he can find the villain who is randomly placed in the array. I can work on the randint part later, but I am having a hard time simply getting 'H' to move.
Here is what I have so far:
Thank you.
#include <iostream>
using namespace std;
void printBoard(char board[][8])
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
cout << board[x][y];
}
cout << endl;
}
}
void move(char board[][8], char umove)
{
cout << "Please enter which direction you would like to move." << endl;
cin >> umove;
if (umove == 'x')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = x - 1;
}
}
}
else if (umove == 'd')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = y + 1;
}
}
}
else if (umove == 'a')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = y - 1;
}
}
}
else if (umove == 'w')
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
board[x][y] = x + 1;
}
}
}
}
char userinput()
{
char usermove;
cout << "Please enter the direction you want to go." << endl;
cin >> usermove;
return usermove;
}
int main()
{
char board[8][8];
int x;
int y;
while (true)
{
for (x = 0; x < 8; x++)
{
for (y = 0; y < 8; y++)
{
board[x][y] = 'e';
}
}
board[0][0] = 'H';
printBoard(board);
void move();
return 0;
}
}
you call void move() which is a method declaration and you must use move(...) instead for calling method. return 0 cause the app to finish which is not correct in this situation. you use infinite loop and you must use a condition for finish game.
depend on your description I suggest:
void printBoard(char board[][8]) {
// same as before
}
bool move(char board[][8], int &Hx, int &Hy) {
char umove;
cout << "Please enter which direction you would like to move." << endl;
cin >> umove;
if (umove == 'f') // f mean finish it
return false;
board[Hx][Hy] = 'e';
if (umove == 'a') // a mean left
Hy = Hy == 0 ? 7 : Hy - 1;
else if (umove == 'd') // d mean right
Hy = Hy == 7 ? 0 : Hy + 1;
else if (umove == 'w') // w mean up
Hx = Hx == 0 ? 7 : Hx - 1;
else if (umove == 's') // s mean down
Hx = Hx == 7 ? 0 : Hx + 1;
board[Hx][Hy] = 'H';
return true;
}
int main() {
char board[8][8];
int Hx = 0, Hy = 0;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
board[x][y] = 'e';
}
}
board[Hx][Hy] = 'H';
bool res = true;
while (res) {
printBoard(board);
res = move(board, Hx, Hy);
}
cout << "Game finished!";
return 0;
}
You can make char board[][] and Hx and Hy (which contain current position of H) global and avoid sending them to method but this is not good at all.
I hope this is what you want.

Error for c++ example

I want to input alphabet to binary code, and output the alphabet from generated binary code.
Example
1 --> a
01 --> b
001 --> c
0001 --> d
00001 --> e
000001 --> f
a => 1
b => 01
c => 001
d => 0001
e => 00001
-------------Encode.cpp--------------------
#include "Encode.h"
Encode::Encode()
{
}
Encode::~Encode()
{
}
void Encode::inputWord()
{
cout << "Input word: ";
cin.getline(word, 255);
return;
}// User input a word
char * Encode::getBuf(void)
{
return buffer;
}// return buffer to Decode::setBuf(char* buf)
void Encode::printEncResult()
{
int size = strlen(word);
int buffersize = 0;
cout << "Encoding result" << endl; // print similar binary
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
cout<<buffer[buffersize++];
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
cout<<buffer[buffersize++];
}
cout << buffer[buffersize++];
}
}
}// output similar binary
int Encode::encodeWord(void)
{
int buffersize = 0;
int size = strlen(word);
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
buffer[buffersize++] = '0';
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
buffer[buffersize++] = '0';
}
buffer[buffersize++] = '1';
}
}
return 0;
}// change word to similar binary
--------Decode.cpp-------------
#include "Decode.h"
Decode::Decode()
{
}
Decode::~Decode()
{
}
void Decode::setBuf(char * buf)
{
int i = 0;
int size = 0;
while (*(buf + i) == '1' || *(buf + i) == '0')
{
i++;
}
size = i;
for(int i = 0; i < size; i++)
{
buffer[i] = buf[i];
}
return;
}// set buffer from Encode::getBuf(void)
void Decode::printWord() // print similar binary
{
int i = 0;
int size = 0;
int check = 1;
while (check)
{
if (word[i] >= 'a' && (int)word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for (int i = 0; i < size; i++)
{
if (word[i] >= 'a' && (int)word[i] <= 'z') // **this part is also strange** I can not shoten the code.
cout<<word[i];
}
cout << endl;
}
int Decode::decodebin(vector<char> buffer)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while (buffer[i] == '1' || buffer[i] == '0')
{
i++;
}
size = i;
for (int j = 0; j < size; j++) // nested loop does not work. I want save words in order
{
for (i = 0; i < size; i++)
{
if (buffer[i] == '0')
++printval;
else
{
word[j] = printval; // In this part, word[0] does not have any value.
printval = 'a';
}
}
}
return 0;
}
In this code, I want save values in order, but word[0] does not have any value. Moreover, If I input 'bb' then, 'bbbb' saved ins word array.
There are some problems and consideration you need to take care of:
as Fei Xiang said in the comments don't use magic numbers, use characters since you have a character array.
int printWord function you actually get the word and print the same word, there is no conversion as your problem statement. your didn't take buffer into account.
you are using some data validation to get your array size, this could end up a disaster(UB). you need to pass your array size to your function or use std::vector(Recommended).
in this statement if ((int)word[i] >= 97 || (int)word[i] <= 122) as I said don't use magic number and || should be change to && otherwise you end up in an infinity loop.
Anyway by keeping your approach(using array) and function signature here's what you can do :
int Decode::decodebin(void)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while(buffer[i] == '1' || buffer[i] == '0')
{
i++;
size = i;
}
for(int i = 0; i < size; i++)
{
if(buffer[i] == '0')
++printval;
else
{
cout << printval;
printval = 'a';
}
}
return 0;
}
void Decode::printWord()
{
int i = 0;
int size = 0;
int check = 1;
while(check)
{
if(word[i] >= 'a' && word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for(int i = 0; i < size; i++)
{
int distance = word[i] - 'a';
for(int j = 0; j < distance; ++j)
cout << '0';
cout << '1';
}
cout << endl;
}
EDIT BASED ON OP REQUIREMENT IN COMMENTS:
using std::vector you can implement your needs like this :
#include <iostream>
#include <vector>
class Decode
{
public:
void decodebin(std::vector<char> buffer)
{
char printval = 'a';
for(unsigned int i = 0; i < buffer.size(); i++)
{
if(buffer[i] == '0')
++printval;
else
{
word.push_back(printval);
printval = 'a';
}
}
}
void printWord(void)
{
for(auto iter = word.begin(); iter != word.end(); ++iter)
std::cout << *iter;
std::cout << std::endl;
}
private:
std::vector<char> word;
};
int main()
{
Decode decoder;
std::vector<char> buffer = {'0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '1'};
decoder.decodebin(buffer);
decoder.printWord();
return 0;
}
Here decodebin stores the given input into word member variable of Decode class. Then printWord function print word values on the screen.
std::vector has all the power of C-style array and it's nicer and easier to use. You can retrieve it's size whenever you want and you don't have to worry about the memory it's allocating.

Strange pass by reference issue in a simple program

I am implementing Sudoku solver and using 2D vector and passing it around using reference but still, when at the end of the main I try to print the 2D vector it prints the initial 2D vector.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
void display(vector<vector<int>>& _board) {
for (auto row: _board) {
for (auto col: row) {
cout << col << " ";
}
cout << endl;
}
}
bool isBoardSolved(vector<vector<int>>& _board) {
for (auto row: _board) {
for (auto col: row) { //style[1] of 2D vector traversal
if (col == 0) {
return false;
}
}
}
return true;
}
map<int, int> findOptions(vector<vector<int>>& _board, int _row, int _col) {
map<int, int> options;
int x, y;
for (int digit = 1; digit < 10; ++digit) {
options[digit] = 0; //state 0 means available as options
}
//col in a row
for (y = 0; y < 9; ++y) {
if (_board[_row][y] != 0) {
options[_board[_row][y]] = 1;
}
}
//row in a col
for (x = 0; x < 9; ++x) {
if (_board[x][_col] != 0) {
options[_board[x][_col]] = 1;
}
}
//in a rectangular 3*3 matrix
if (_row <= 2)
x = 0;
else if (_row > 2 && _row <= 5)
x = 3;
else
x = 6;
if (_col <= 2)
y = 0;
else if (_col > 2 && _col <= 5)
y = 3;
else
y = 6;
for (int i = x; i < x + 3; ++i) {
for (int j = y; j < y + 3; ++j) {
if (_board[i][j] != 0) {
options[_board[i][j]] = 1;
}
}
}
return options;
}
void solveBoard(vector<vector<int>>& _board) {
int row = 0;
int col = 0;
bool flag = false;
if (isBoardSolved(_board)) {
// cout << "Solved Sudoku Board" << endl;
// display(_board); //gives correct answer when I print it here
return;
}
else {
for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
flag = false;
for (int y = 0; y < 9; ++y) {
if (_board[x][y] == 0) {
row = x;
col = y;
flag = true;
break;
}
}
if (flag)
break;
}
}
auto options = findOptions(_board, row, col);
for (auto digit: options) {
if (digit.second != 1) {
_board[row][col] = digit.first;
solveBoard(_board);
}
}
_board[row][col] = 0;
}
int main(int argc, char *argv[]) {
vector<vector<int>> board(9, vector<int>(9, 0));
board[0][3] = 3;
board[0][6] = 2;
board[2][1] = 7;
board[2][2] = 8;
board[2][3] = 0;
board[2][4] = 6;
board[2][6] = 3;
board[2][7] = 4;
board[3][1] = 4;
board[3][2] = 2;
board[3][3] = 5;
board[3][4] = 1;
board[4][0] = 1;
board[4][1] = 0;
board[4][2] = 6;
board[4][6] = 4;
board[4][7] = 0;
board[4][8] = 9;
board[5][4] = 8;
board[5][5] = 6;
board[5][6] = 1;
board[5][7] = 5;
board[6][1] = 3;
board[6][2] = 5;
board[6][4] = 9;
board[6][6] = 7;
board[6][7] = 6;
board[7][3] = 7;
board[8][2] = 9;
board[8][5] = 5;
cout << "Given Sudoku Board" << endl;
display(board);
solveBoard(board);
cout << "Solved Sudoku Board" << endl;
display(board); //gives unchanged answer when i print it here
}
What is wrong I am doing and how to correct it.
When I try this :
void change(vector<vector<int>>& _b){
_b[0][1] = 99;
}
int main(){
vector<vector<int>> b(1, vector<int>(9, 1));
cout<<b[0][1]<<endl;
change(b);
cout<<b[0][1];
return 0;
}
This displays the changed value for 2D vecor b.
You are not exiting the recursion call stack correctly in solveBoard(). Note the new bool function signature for solveBoard() being returned to signal up the invocation chain to exit early. Also note the three different return points now depending on where you are.
bool solveBoard(vector<vector<int>>& _board) {
int row = 0;
int col = 0;
bool flag;
if (isBoardSolved(_board)) {
// cout << "Solved Sudoku Board" << endl;
// display(_board); //gives correct answer when I print it here
return true;
}
else {
for (int x = 0; x < 9; ++x) { //not using the style[1] because I need explicit index of empty slot
flag = false;
for (int y = 0; y < 9; ++y) {
if (_board[x][y] == 0) {
row = x;
col = y;
flag = true;
break;
}
}
if (flag)
break;
}
}
auto options = findOptions(_board, row, col);
for (auto digit : options) {
if (digit.second != 1) {
_board[row][col] = digit.first;
if (solveBoard(_board))
return true;
}
}
_board[row][col] = 0;
return false;
}

heap corruption after deleting dynamic array

I know that this question was asked many times but I couldn't find the solution for my error
I am trying to make a program to check whether the matrix given is symmetric or not the user enters the number of test cases then the size then the matrix and the output is whether it's symmetric or not
the program works fine until I try a size more than 3 it breaks with this error and when debugging it seems that it breaks at delete[]arrL
#include <iostream>
#include <string>
using namespace std;
int n(char s)
{
switch (s)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
}
}
int getnumber(string a)
{
string num = "";
for (int i = 0; i < a.size(); i++)
{
if (isdigit(a[i]))
num += a[i];
}
if (num.size() == 1)
{
return n(num[0]);
}
if (num.size() == 2)
{
return (n(num[0]) * 10) + (n(num[1]));
}
if (num.size() == 3)
{
return (n(num[0]) * 100) + (n(num[1]) * 10) + (n(num[2]));
}
}
bool matrix2(long int**p, int r)
{
int c = 0, u = 0, ss = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
if (p[i][j]<0)
return false;
}
}
long int*arrL = new long int[r];
long int*arrR = new long int[r];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < i; j++)
{
arrL[c++] = p[i][j];
ss++;
}
}
for (int i = 0; i < r; i++)
{
for (int j = i + 1; j < r; j++)
{
arrR[u++] = p[i][j];
}
}
for (int i = 0; i < ss; i++)
{
int q = ss - i - 1;
long int a = arrR[i];
long int b = arrL[q];
if (!(a == b))
{
delete[]arrL;
delete[]arrR;
return false;
}
}
delete[]arrL;
delete[]arrR;
return true;
}
int main()
{
int t;
cin >> t;
for (int num = 0; num < t;num++)
{
int yy = num + 1;
string dimension;
cin.ignore();
getline(cin, dimension);
int r = getnumber(dimension);
long int**p = new long int*[r];
for (int w = 0; w < r; w++){
p[w] = new long int[r];
}
for (int w = 0; w < r; w++)
{
for (int ww = 0; ww < r; ww++)
{
cin >> p[w][ww];
}
}
bool result = matrix2(p, r);
if (result)
{
cout << "Test #" << yy << ": Symmetric." << endl;
}
else
{
cout << "Test #" << yy << ": Non-symmetric." << endl;
}
for (int i = 0; i < r; i++)
{
delete[]p[i];
}
delete[] p;
}
return 0;
}
arrL and arrR are allocated of size r, but then
arrL[c++] = p[i][j];
is executed more than r times, so c exceeds r, so you've corrupted your heap.

Program received signal EXC_BAD_ACCESS - Mac OS X

When I'm comparing an element in std::vector to char, I randomly get this error sometimes when running to program (about once every five times):
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
0x0000000100017c49 in randomCaveGenerator (p=#0x7fff5fbff51c, q=#0x7fff5fbff518, seed=1234567) at src/main.cpp:198
198 if (lm.map[1][i][j] == '0')
v is defined as a std::vector with all elements filled. I know this error usually means it is pointing to a null pointer but I know there shouldn't be one.
I'm using Mac OS X 10.8, gdb to debug, and Apple LLVM version 4.2 (based on LLVM 3.2svn) to compile.
Edit
The code that I'm using:
typedef std::vector< std::vector<char> > MapGrid;
struct LevelMap
{
std::string name;
std::vector<MapGrid> map;
sf::Vector2u size;
};
LevelMap randomCaveGenerator(int p=64, int q=64, unsigned long seed=1)
{
if (p < 64)
p = 64;
if (q < 64)
q = 64;
int groundLevel = 12;
srand(seed);
sf::Vector2u size(p, q);
std::vector<MapGrid> mapG(3);
for (int i = 0; i < 3; i++)
{
mapG[i] = MapGrid(size.x, std::vector<char>(size.y));
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
mapG[i][x][y] = '0';
}
}
}
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
mapG[0][x][y] = 'v'; // Void Tile
}
}
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
mapG[2][x][y] = '0'; // Air Tile
}
}
for (int y = groundLevel; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
int e = 23;
if (2+(rand()%e)< e/2)
mapG[1][x][y] = 'd';
else
mapG[1][x][y] = '0';
}
}
LevelMap lm;
lm.name = "Random Map";
lm.map = mapG;
lm.size = size;
for (int i = 0; i < 12; i++)
doSimStep(lm);
for (int i = 1; i < lm.size.x - 2; i++)
{
for (int j = 1; j < 12+groundLevel; j++)
{
if (lm.map[1][i][j] == '0') // PART WHERE THE ERROR IS
continue;
else
{
lm.map[1][i][j] = 'g';
lm.map[2][i][j-1] = 'w';
i++;
j = 1;
}
}
}
for (int i = 1; i < lm.size.x - 2; i++)
{
for (int j = groundLevel; j < lm.size.y - 2; j++)
{
if (lm.map[1][i][j] == 'd')
{
if (rand()%120 == 0)
lm.map[2][i][j] = 'p';
}
}
}
for (int i = 0; i < lm.size.y; i++)
{
lm.map[1][0][i] = 'X';
lm.map[1][lm.size.x-2][i] = 'X';
lm.map[2][0][i] = '0';
lm.map[2][lm.size.x-2][i] = '0';
}
for (int i = 0; i < lm.size.x; i++)
{
lm.map[1][i][0] = 'X';
lm.map[1][i][lm.size.y-2] = 'X';
lm.map[2][i][0] = '0';
lm.map[2][i][lm.size.y-2] = '0';
}
return lm;
}
With no source code apart from the error message
if (v[i] == '0')
I can only imagine i >= v.size()
You might want to consider using iterators to access your vector, so you don't step off the end.