I am VERY new to programming so this is a very 'messy'/'dirty' code.
Situation is, if I got 2 strings
e.g.
ASDFGHJKL and PFUYASD
I would like to output their positions where letters match like this:
"Match found at 0 of Strand 1 and 6 of Strand 2"
Conditions:
They must match upto three side by side characters. (the reason why the F isn't considered in the example)
Strand 1 is longer than Strand 2
So I got this code that works for finding match up to second letter. This works fine
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int y = 0;
int str1match;
int str2match;
string str1;
string str2;
cout << "string1\n";
cin >> str1;
cout << "string2\n";
cin >> str2;
int length = str1.length();
startagain:
int pos = str2.find(str1[x]);
if ((pos >= 0) && (x<length))
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
str1match = x - 2;
str2match = pos - 2;
cout << "Match at " << str1match << " of Strand 1 and at " << str2match << " of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x<length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
But I needed the code to find match until atleast 3rd letter so i thought just by adding more nested loop it will work but it doesn't. here's is the code that doesn't work:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int str1match, str2match;
string strand1, strand2;
cout << "Enter Strand 1:\n";
cin >> strand1;
cout << "Enter Strand 2:\n";
cin >> strand2;
int length = strand1.length();
startagain:
int pos = strand2.find(strand1[x]);
if ((pos >= 0) && (x < length))
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
str1match = x - 3;
str2match = pos - 3;
cout << "Match at " << str1match << "of Strand 1 and at " << str2match << "of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x < length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
bool found = false;
for(int i=0;i<strand1.size()-2;i++){
int pos = strand2.find(strand1.substr(i,3));
if(pos != string::npos){
found = true;
cout << "match at " << i << "in 1 with " << pos << " in 2" << '\n';
break;
}
}
if (!found) cout << "No match";
string.substr finds a substring starting from i
Related
I have input such as:
10000000000000-1=
and
AAAAABBBBBCCCCCDDDDDEEEEEFFFFF-ABCDEF0123456789ABCDEF=
I need to convert the hexadecimal strings digit by digit into decimal and keep track if I need to borrow. I'm not sure how to adjust the value of operand 1 when a borrow occurs. Such as in the first line when you have to borrow 13 times.
Currently, I have
#include <iostream>
#include <fstream>
using namespace std;
string decimalToHex(int);
void subtraction(string, string)
int hexadecimalToDecimal(char hexVal);
int fullSubtractor(int tempOp1, int tempOp2)
int main()
{
ifstream myFile;
string l1, l2, l3, l4, l5, l6, l7, l8; //lines
string l1op1, l1op2, l2op1, l2op2, l3op1, l3op2, l4op1, l4op2, l5op1, l5op2, l6op1, l6op2, l7op1, l7op2, l8op1, l8op2; //parsed operators
myFile.open("data.txt");
if (myFile.is_open()) //check if file opened
{
cout << "File opened successfully. " << endl;
}
else
{
cerr << "File failed to open." << endl;
return 1;
}
while (!myFile.eof())
{
myFile >> l6 >> l7; //read in line by line
}
l6op1 = l6.substr(0, l6.find("-"));
l6op2 = l6.substr(l6.find("-") + 1);
l6op2 = l6op2.substr(0, l6op2.length() - 1);
std::string l6op2_zeros = std::string((l6op1.length()) - l6op2.length(), '0') + l6op2;
cout << l6; // << subtraction(l6op1, l6op2_zeros) << endl;
subtraction(l6op1, l6op2_zeros);
cout << endl;
l7op1 = l7.substr(0, l7.find("-"));
l7op2 = l7.substr(l7.find("-") + 1);
l7op2 = l7op2.substr(0, l7op2.length() - 1);
std::string l7op2_zeros = std::string((l7op1.length()) - l7op2.length(), '0') + l7op2; //appends zeros to front of second operand to make it same length as operand 1
cout << l7; // << subtraction(l7op1, l7op2) << endl;
subtraction(l7op1, l7op2_zeros);
cout << endl;
myFile.close();
return 0;
}
int fullSubtractor(int tempOp1, int tempOp2)
{
static int borrow;
int result = 0;
if ((tempOp1 < tempOp2) || ((tempOp1 == 0) && (borrow == 1)))
{
tempOp1 += 16;
result = tempOp1 - borrow - tempOp2;
borrow = 1;
}
else
{
result = tempOp1 - tempOp2;
borrow = 0;
}
return result;
}
void subtraction(string op1, string op2)
{
string result;
int tempDifference = 0, tempHex = 0;
int j = op2.length() - 1;
for (int i = op1.length() - 1; i >= 0; i--)
{
int temp1 = hexadecimalToDecimal(op1[i]);
int temp2 = hexadecimalToDecimal(op2[j]);
tempHex = fullSubtractor(temp1, temp2);
result = decimalToHex(tempHex) + result;
cout << result << " ";
j--;
}
cout << result << endl;
//return result;
}
int hexadecimalToDecimal(char hexVal)
{
int base = 1;
int dec_val = 0;
if (hexVal >= '0' && hexVal <= '9')
{
dec_val += (hexVal - 48) * base;
base *= 16;
}
else if (hexVal >= 'A' && hexVal <= 'F')
{
dec_val += (hexVal - 55) * base;
// incrementing base by power
base *= 16;
}
return dec_val;
}
string decimalToHex(int decNum)
{
stringstream ss;
ss << hex << decNum;
string hexNum(ss.str());
//cout << hexNum << endl;
return hexNum;
}
My program is exiting without iterating. It automatically goes to "YOU WON". Without the champion function the program runs fine. Its probably some obvious error Im missing. If anyone could please I would greatly appreciate it.
#include <iostream>
#include <string>
#define GRID_SIZE 3
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void champion() {
const char *possiblities[8]{
"123"
"456"
"789"
"147"
"159"
"258"
"369"
"753"
};
for (int i = 0; i < 8; i++) {
bool winner = true;
char previous_pos = '0';
const char *possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - 1;
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if
(previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char) 'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
tictacToeMap();
playgame();
champion();
}
}
};
int main() {
TicTacToe tic;
tic.playgame();
return 0;
}
The problem is here:
if (winner = true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
You probably meant:
if (winner == true) {
std::cout << "YOU WON" << std::endl;
exit(0);
break;
}
First, do what Max Meijer said, by replacing if(winner = true) with if(winner == true). But the program is still broken. The problem is that in your string array, you are not separating each string with a comma, so when my debugger hits const char *possible_moves, it ends up just assigning the entire array concatenated together. So just separate each string in the possibilities array with a comma, like so:
const char *possiblities[8]{
"123",
"456",
"789",
"147",
"159",
"258",
"369",
"753"
};
I want the program to print "You win" when any of the instances in the champion() function are given. It only shows a winner when "123" is inputted. Whenever three X's are displayed anywhere else the program continues. For instance if three X's are given diagonally the program will still continue. Novice programmer so any criticism is greatly appreciated.
class TicTacToe {
private:
char map[GRID_SIZE][GRID_SIZE];
public:
void computers_turn() {
while (true) {
int choice = (rand() % 9) + 1;
int row = choice / 3;
int col = choice % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'O';
break;
}
}
}
void champion() {
const char* possiblities[8] = {"123", "456", "789", "147",
"258", "369", "159", "753"};
for (int i = 0; i < 8; i++) {
char previous_pos = '0';
bool winner = true;
const char* possible_moves = possiblities[i];
for (int index = 0; index < GRID_SIZE; index++) {
char character = possible_moves[i];
int entered_num = character - '0';
int grid_space = entered_num - '1';
int row = index / GRID_SIZE;
int col = index % GRID_SIZE;
char grid_coordinate = map[row][col];
if (previous_pos == '0') {
previous_pos = grid_coordinate;
} else if (previous_pos == grid_coordinate) {
continue;
} else {
winner = false;
break;
}
}
if (winner) {
puts("You win");
exit(0);
break;
}
}
}
void playgame() {
std::string input;
while (true) {
std::cout << "Go player one" << std::endl;
getline(std::cin, input);
if (input != " ") {
char entered = input.c_str()[0];
if (entered >= '1' && entered <= '9') {
int entered_num = entered - '0';
int index = entered_num - 1;
int row = index / 3;
int col = index % 3;
char grid_position = map[row][col];
if (grid_position == 'X' || grid_position == 'O') {
std::cout << "Space taken. Try again" << std::endl;
} else {
map[row][col] = (char)'X';
break;
}
} else {
std::cout << "Only numbers 1 - 9" << std::endl;
}
} else {
std::cout << "Have to enter something, try again" << std::endl;
}
}
}
void generateGrid() {
int number = 1;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
map[x][y] = std::to_string(number).c_str()[0];
number += 1;
}
}
}
void tictacToeMap() {
std::cout << std::endl;
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
std::printf(" %c ", map[x][y]);
}
std::cout << std::endl;
}
}
TicTacToe() {
generateGrid();
while (true) {
champion();
tictacToeMap();
playgame();
computers_turn();
}
}
};
int main() {
TicTacToe ticTacToe;
return 0;
}
Sorry this is my first time use stackoverflow.
I dont kow where is the mistake in my code.
Output that i want:
-1+3-5+7-9+11-13+15
RESULT : 8
But Output that is shown
-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
cout << "+";
}
if (i == 1) {
sign = 1;
cout << "-";
}
x = sign * (2 * i - 1);
cout << x;
S = S + x;
}
cout << "\n Result:" << S;
}
problem is in the if condition block where you check i==1
in that loop you are making sign=1 that should be sign=-1
How about improving the logic like following?
#include <iostream>
using namespace std;
int main()
{
int i;
bool sign = true; // signed/minus = true, non-signed/plus = false
int ans = 0;
for( i=1; i<=15; i=i+2){
if( sign == true){
cout << "-" << i;
ans = ans - i;
}
else {
cout << "+" << i;
ans = ans + i;
}
sign = !sign;
}
cout << endl << "RESULT : " << ans << endl;
return 0;
}
Try this code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
else
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
// cout << "+";
}
//else
if (i == 1) {
sign = -1;
//cout << "-";
}
x = sign * (2 * i - 1);
cout <<"\n"<<x;
S = S + x;
//cout<<"S is \n"<<S;
}
cout << "\n Result:" << S;
}
You have put wrong sign when i==1
The problem is that you're starting the calculation with a positive sign (but you're lying to yourself by printing "-").
You can simplify the code and don't need to mess around with pow if you make the obervation that
pow(-1, k) == -1 * pow(-1, k-1)
Starting at pow(-1,0) (that is, 1), you can write:
int main(int argc, char* argv[])
{
int sign = 1; // sign will always hold pow(-1, i).
int sum = 0;
for (int i = 1; i <= 8; i++)
{
sign *= -1;
if (sign > 0) // Since sign starts at -1, we know that i > 1 here
{
std::cout << "+";
}
int term = sign * (2 * i - 1);
std::cout << term;
sum += term;
}
std::cout << " = " << sum << std::endl;
}
I have a problem with the output of a binary tree. The code that I have designed for the print of a tree, in which the elements have a length of 1 character, and in my tree elements are words (at most 10 characters). Tell me pls what should I change in the code to the correct output of tree.
My code:
int maxHeight(Node *p) {
if (!p) return 0;
int leftHeight = maxHeight(p->left);
int rightHeight = maxHeight(p->right);
return (leftHeight > rightHeight) ? leftHeight + 1 : rightHeight + 1;
}
void printBranches(int branchLen, int nodeSpaceLen, int startLen, int nodesInThisLevel, const deque<Node*>& nodesQueue) {
deque<Node*>::const_iterator iter = nodesQueue.begin();
for (int i = 0; i < nodesInThisLevel / 2; i++) {
cout << ((i == 0) ? setw(startLen - 1) : setw(nodeSpaceLen - 2)) << "" << ((*iter++) ? "/" : " ");
cout << setw(2 * branchLen + 2) << "" << ((*iter++) ? "\\" : " ");
}
cout << endl;
}
void printNodes(int branchLen, int nodeSpaceLen, int startLen, int nodesInThisLevel, const deque<Node*>& nodesQueue) {
deque<Node*>::const_iterator iter = nodesQueue.begin();
for (int i = 0; i < nodesInThisLevel; i++, iter++) {
cout << ((i == 0) ? setw(startLen) : setw(nodeSpaceLen)) << "" << ((*iter && (*iter)->left) ? setfill('_') : setfill(' '));
cout << setw(branchLen + 2);
if (*iter)
cout << (*iter)->data << "(" << (*iter)->frequency << ")";
else
cout << "";
cout << ((*iter && (*iter)->right) ? setfill('_') : setfill(' ')) << setw(branchLen) << "" << setfill(' ');
}
cout << endl;
}
void printLeaves(int indentSpace, int level, int nodesInThisLevel, const deque<Node*>& nodesQueue) {
deque<Node*>::const_iterator iter = nodesQueue.begin();
for (int i = 0; i < nodesInThisLevel; i++, iter++) {
cout << ((i == 0) ? setw(indentSpace + 2) : setw(2 * level + 2));
if (*iter)
cout << (*iter)->data << "(" << (*iter)->frequency << ")";
else
cout << "";
}
cout << endl;
}
void printPretty(Node *root, int level, int indentSpace) {
int h = maxHeight(root);
int nodesInThisLevel = 1;
int branchLen = 2 * ((int)pow(2.0, h) - 1) - (3 - level)*(int)pow(2.0, h - 1);
int nodeSpaceLen = 2 + (level + 1)*(int)pow(2.0, h);
int startLen = branchLen + (3 - level) + indentSpace;
deque<Node*> nodesQueue;
nodesQueue.push_back(root);
for (int r = 1; r < h; r++) {
printBranches(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue);
branchLen = branchLen / 2 - 1;
nodeSpaceLen = nodeSpaceLen / 2 + 1;
startLen = branchLen + (3 - level) + indentSpace;
printNodes(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue);
for (int i = 0; i < nodesInThisLevel; i++) {
Node *currNode = nodesQueue.front();
nodesQueue.pop_front();
if (currNode) {
nodesQueue.push_back(currNode->left);
nodesQueue.push_back(currNode->right);
}
else {
nodesQueue.push_back(NULL);
nodesQueue.push_back(NULL);
}
}
nodesInThisLevel *= 2;
}
printBranches(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue);
printLeaves(indentSpace, level, nodesInThisLevel, nodesQueue);
}
as you can see, chars "\" and leaves are shifted by 3 positions to the left
http://i.stack.imgur.com/ADdGZ.png