I need to build a code where it takes a 2d array of char and checks if its palindrome the second function uses the first one to see how many arrays are palindrome my issue with the code is that every time I get count is 0; I know the issue is in the second function but don't know where
#include <iostream>
using namespace std;
int CountPal(char M[][5], int rows);
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
}
int main() {
int x;
cout << "please enter the number of rows " << endl;
cin >> x;
char M[5][5];
cout << "before test" << endl;
cout << CountPal(M, x) << endl;
cout << "After test" << endl;
system("pause");
}
int CountPal(char M[][5], int rows) {
int count = 0;
cout << "please enter the string " << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 5; j++) {
cin >> M[i][j];
}
for(int i = 0; i < rows; i++) {
char* S;
S = &M[i][0];
if(pal(S) == 1) count++;
}
}
return count;
}
I think your problem is in int pal(char* S) function. You want it to return 1 if a given string of your 2d array is a palindrome to up your count by 1. And anything other than 1 would be non palindrome string.
So i think you should add a return statement after the end of your int pal(char* S) function like this;
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
return flag;
}
You could even change your function to bool data type. It's more proper because you only want to return "true" or "false" values.
Related
I am trying to implement the algorithm RLE with simple input like:
ddddddddddhhhhhhhhhhhhhhhttttttttttttt
code:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<char> read;
ifstream file;
file.open("file.txt");
if (!file) {
cout << "Unable to open";
}
char v;
while(file>>v) {
read.push_back(v);
}
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
x = read[i];
if(x != read[++i]) {
cout << x << "1";
}
while(x == read[++i]) {
count++;
}
cout << x << count;
count = 0;
}
return 0;
}
The output I am getting is:
d9d1h12h1t10t1
Please help me with the code.
Update: I have updated the question as I have realized few things.
Plus: This code produced no output, is there anything wrong which I am doing wrong?
char o;
char n;
int count=0;
for(int i=0; i<read.size(); i++) {
o = read[i];
n = read[++i];
while(o == n) {
count++;
}
cout << o << count;
if(o != n) {
cout << o << "1";
} count = 0;
}
return 0;
This loop:
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
int j=i;
x = read[i];
if(x != read[++j]) {
cout << x << "1";
}
while(x == read[++j]) {
count++;
}
cout << x << count;
}
Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:
// If there are no characters finish
if (read.empty()) {
return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1; // We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
// Get the next char
char newChar = read[i];
// If it is different, print the current count and reset the counter
if (lastChar != newChar) {
cout << lastChar << count;
count = 1;
lastChar = newChar;
} else { // Else increase the counter
count++;
}
}
// Print the last one
cout << lastChar << count;
return 0;
I cant get the char search to work. The substring function is working but the char search won't provide the right location of the char it is looking for
#include<iostream>
#include <string>
using namespace std;
int charsearch(string searchInto, char ch, int start = 0)
{
int x = 0;
long n = searchInto.length();
for (int i = 1; i < n; i++)
{
cout << ch;
if (searchInto[i] == ch)
{
i = x;
}
else
i++;
}
cout<< x;
return x;
}
int substr(string src, string tosearch, int start = 0)
{
string searchInto = src;
long n = searchInto.size();
long m = tosearch.size();
int ans = -1;
for (int i = start; i < n; ++i)
{
int p = i;
int q = 0;
bool escape = false;
while (p < n && q < m) {
if (searchInto[p] == tosearch[q]) {
if (tosearch[q] == '/' && !escape) {
++q;
} else {
++p; ++q;
}
escape = false;
} else if (!escape && tosearch[q] == '*') {
++q;
while (q < m && p < n && searchInto[p] != tosearch[q]) ++p;
escape = false;
} else if (!escape && tosearch[q] == '?') {
++p; ++q;
escape = false;
} else if (tosearch[q] == '/' && !escape) {
escape = true;
++q;
} else break;
}
if (q == m) {
return i;
}
if (q == m - 1 && tosearch[q] == '*') {
if (q > 0 && tosearch[q - 1] == '/') continue;
else return i;
}
}
return ans;
}
int main()
{
string searchInto, tosearch;
cout<< "Enter string:";
getline(cin, searchInto);
cout << "Looking for :";
getline(cin, tosearch);
if (tosearch.length() < 2)
{
char ch = tosearch.at(0);
cout << "Found at: " <<charsearch(searchInto, ch) << endl;
cout << "Used Char" << endl;
}
else
cout << "Found at: " <<substr(searchInto, tosearch) << endl;
return 0;
}
To find a character in a string, you have two interfaces.
std::string::find will return the position of a character you find:
auto pos = yourStr.find('h');
char myChar = yourStr[pos];
If the character does not exist, then std::string::npos will be returned as the std::size_t returned for position.
stl algorithm std::find, in header algorithm returns an iterator:
auto it = std::find(yourStr.begin(), yourStr.end(), 'h');
char myChar = *it;
If the character does not exist, then it == yourStr.end().
There are some silly mistakes in your CharSearch method. First of all, You have to break the loop when you got your target character. And most importantly you are not assigning x when you are finding the target. Furthermore, there is extra increment of value i inside the loop. I have modified the function. Please check it below
int charsearch(string searchInto, char ch, int start = 0) {
int x = -1;
long n = searchInto.length();
for (int i = start; i < n; i++)
{
cout << ch;
if (searchInto[i] == ch)
{
x = i; // previously written as i = x which is wrong
break; // loop should break when you find the target
}
}
cout<< x;
return x;
}
Please note that,you can either also use find method of string or std::find of algorithm to search in string.
You need to make changes as per this code
int charsearch(string searchInto, char ch, int start = 0)
{
int x = -1; // : change, if return -1, means not found
long n = searchInto.length();
for (int i = start; i < n; i++) // : change
{
cout << ch;
if (searchInto[i] == ch)
{
x = i; // : change
break; // : change
}
}
cout<< x;
return x;
}
Note : This function will return 1st match.
My assignment is to : Create a method to search an un-ordered array of integers for a value,
if the value is found return the index of its position in the array, if not found, return -1.
It is only finding the number I enter if it is in Index 0, otherwise it is saying it is not found. I am not sure what went wrong, it was working when I had initialized my own array, but now it won't since I have the user create their own array.
Any help would be great! thanks!
So far my code is:
#include <iostream>
using namespace std;
//SearchArray prototype
int SearchArray( int arInt[], int elementAmount, int intSearched);
int main()
{
int arInt[50];
int elementAmount;
int intSearched = 0;
int i;
cout << "How many elements would you like to add to your array?\n";
cin >> elementAmount;
for( i = 0; i < elementAmount; i++)
{
cout << "Enter Number: ";
cin >> arInt[i];
}
cout << "Search array for integer:\n";
cin >> intSearched;
//Call search array method
SearchArray(arInt, elementAmount, intSearched);
system("pause");
return 0;
}
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
int i;
bool foundInt = false;
for (i=0; i < elementAmount; i++)
{
if( arInt[i] == intSearched)
{
foundInt = true;
cout << "Integer was found in array at index " << i << endl;
}
else if (!foundInt)
{
cout << "Integer was not found in array\n";
system("pause");
return -1;
}
}
}
Added the following code to the SearchArray method in your code, and it works fine
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
for(int i=0; i< elementAmount; i++)
{
if (arInt[i] == intSearched)
return i;
}
// element not found!
return -1;
}
And add the following at the end of your main to retrieve the ans
int ans = SearchArray(arInt, elementAmount, intSearched);
cout<<"Indexed of the element"<<ans<<endl;
That's because you always end your search on first element. Suppose array is
arr=[3,5,7] and intSearched is 5.
Now in your SearchArray() function foundInt is initially set to false. So when i = 0 and arInt[i] == intSearched condition is not true, it goes to else statement since foundInt is false. And from there you return -1. Something like below would be simpler and do the job:
int SearchArray(int *arInt, int elementAmount, int intSearched)
{
int i;
for(i=0; i < elementAmount; i++)
{
if(arInt[i] == intSearched)
{
cout << "Integer was found in array at index " << i << endl;
return 1;
}
}
cout << "Integer was not found in array\n";
system("pause");
return 0;
}
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
I've been working on this for awhile and I have tried multiple different algorithms for the bubble sort that I have found online but none of them are working properly for me and I'm pretty close to giving up, but this is due tomorrow night. I'd really appreciate if someone could point out where im going wrong. I dont really understand this algorithm with the bool so ill try to find what i was trying before and edit it in
#include <iostream>
using namespace std;
void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);
int main()
{
int size;
int array[500];
GetInfo(array, size);
BubbleSort(array, size);
BinarySearch(array, size);
return 0;
}
void GetInfo(int array[], int& size)
{
cout << "Enter the number of naturals: ";
cin >> size;
cout << "Enter the natural numbers to sort: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
}
void BubbleSort(int array[], int size)
{
int temp;
bool check = true;
int end = 0;
while(check)
{
end++;
check = false;
for(int i = 0; i < size - end; i++)
{
if (array[i] > array[i+1]) //I'm positive this part is correct
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
check = true;
}
}
}
cout << endl << "Numbers sorted in ascending order: " << endl;
for (int i = 0; i < size; i++)
{
cout << array[i] << ' ';
}
}
void BinarySearch(int array[], int size) //this doesnt work properly atm but
{ //should be good when the sort works
int index;
int top = size - 1;
int bottom = 0;
int middle = (top) / 2;
bool found = false;
int target;
cout << endl << "Enter the number to search: ";
cin >> target;
while (found == false)
{
if (target > array[middle])
{
bottom = middle + 1 ;
middle = ((top - bottom)/2) + bottom;
}
else if (target < array[middle])
{
top = middle - 1;
middle = ((top - bottom)/2) + bottom;
}
else
{
found = true;
index = middle;
}
}
cout << "Number " << target << " is found in position " << index << endl;
}
You might meant to swap a[i] with a[i+1] while you actually swapped a[size+1]
These lines are wrong:
array[i] = array[size+1];
array[size+1] = temp;
You need:
array[i] = array[i+1];
array[i+1] = temp;