Getting out of a while loop earlier with cout using c++ - c++

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string sentence = "some random sentence";
int i = 0; //runs through the bigger string
int j = 0; //runs through the smaller string
int k = 0; //variable to mark the position where the string starts being equal in order to delete it using substring
string remove = "random";
int a = sentence.size();
int b = remove.size();
while (i < a)
{
if (sentence[i] == remove[j])
{
if (b == j - 1)
{
cout << sentence.substr(0, k) << sentence.substr(i, (a - 1));
break;
}
else
{
i++;
j++;
}
}
else
{
i++;
j = 0;
k++;
}
}
return 1;
}
I want to remove the word random from the bigger string and print it out but when I run the code, it does not return anything. What's missing?
I already tried putting a break right below de "cout", but it does not work.
Thank you :)

As b == 6, j would have to be 7 in order for b == j-1 to become true. But remove[6] is the terminating \0 of the random string, so j can never grow beyond 6.

Here is the code I edited
if (b-1 == j)
{
cout << sentence.substr(0, k) << sentence.substr(i+2, (a - 1));
break;
}
This is assuming, you have spaces between the words.

Related

Trying to show the middle word in a string c++

I'm having trouble with getting this code to work properly.
It's purpose is to show the middle word of any given sentence. If its an even amount of words, it shows the first word out of the 2. Instead of printing the middle word, it prints the 2 middle characters. I think its only a few small things I have to add, but I'm stuck on this roadblock. Any help would be appreciated, thank you!
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string sentence="";
string letter="";
string middle="";
int count=0;
int spacecount=0;
int mid=0;
cout << "Enter a sentence:" << endl;
getline(cin,sentence); //gets user input
//for example, "hello there friend"
for(int count =0; count<sentence.length();count++){
letter=sentence.substr(count,1);
if(letter!=" "){
count++;
}
if(letter==" "){
spacecount++;
}
if(count> mid){
mid = count;
}
if (((mid = sentence.length() / 2) % 2) == 0){ //checks if amount of words is even
middle=sentence.substr(mid,2);
}
if (((mid = sentence.length() / 2) % 2) >= 1) //checks if amount of words is odd
{
middle=sentence.substr(mid,2);
}
}
reverse(middle.rbegin(),middle.rend()); //makes it so the word isnt backwards
cout <<"Middle word is: " << middle <<endl;
//shows middle word to user
//it should print "there", but it shows "he" (the two middle characters)
return 0;
}
Lets split the string into tokens and find the middle object of it?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
string input;
getline(cin, input);
vector<string> tokens;
string token;
for (size_t i = 0; i < input.length(); i++) {
char c = input[i];
if (c == ' ' || !input[i + 1]) {
if (!input[i + 1])
token += c;
tokens.push_back(token);
token = "";
continue;
}
token += c;
}
auto mid = tokens.size() % 2 == 0 ? tokens.begin() + tokens.size() / 2 - 1
: tokens.begin() + tokens.size() / 2;
cout << *mid;
return 0;
}

My Boyer-Moore algorithm only searches the first 3000ish characters in my text file

I'm trying to implement a Boyer-Moore string search algorithm. The search algorithm itself seems to work fine, up until a point. It prints out all occurrences until it reaches around the 3300 character area, then it does not search any further.
I am unsure if this is to do with the text file being too big to fit into my string or something entirely different. When I try and print the string holding the text file, it cuts off the first 185122 characters as well. For reference, the text file is Lord of the Rings: Fellowship of the Ring - it is 1016844 characters long.
Here is my code for reference:
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>
using namespace std;
# define number_chars 256
typedef std::chrono::steady_clock clocktime;
void boyer_moore(string text, string pattern, int textlength, int patlength) {
clocktime::time_point start = clocktime::now();
vector<int> indexes;
int chars[number_chars];
for (int i = 0; i < number_chars; i++) {
chars[i] = -1;
}
for (int i = 0; i < patlength; i++) {
chars[(int)pattern[i]] = i;
}
int shift = 0;
while (shift <= (textlength - patlength)) {
int j = patlength - 1;
while (j >= 0 && pattern[j] == text[shift + j]) {
j--;
}
if (j < 0) {
indexes.push_back(shift);
if (shift + patlength < textlength) {
shift += patlength - chars[text[shift + patlength]];
}
else {
shift += 1;
}
}
else {
shift += max(1, j - chars[text[shift + j]]);
}
}
clocktime::time_point end = clocktime::now();
auto time_taken = chrono::duration_cast<chrono::milliseconds>(end - start).count();
for (int in : indexes) {
cout << in << endl;
}
}
int main() {
ifstream myFile;
//https://www.kaggle.com/ashishsinhaiitr/lord-of-the-rings-text/version/1#01%20-%20The%20Fellowship%20Of%20The%20Ring.txt
myFile.open("lotr.txt");
if (!myFile) {
cout << "no text file found";
}
string text((istreambuf_iterator<char>(myFile)), (istreambuf_iterator<char>()));
cout << text;
string pattern;
cin >> pattern;
int n = text.size();
int m = pattern.size();
boyer_moore(text, pattern, n, m);
}
I have tried to do some researching about what could be the cause but couldn't find anyone with this particular issue. Would appreciate any nudges in the right direction.

Binary Search - Output is not displaying after code compiles and runs

I'm just now learning about binary search in class and the code below is simply an example because I'm trying to understand it better. So with that said this code is compiling but not displaying any output and because of my lack of knowledge of Binary search I do not know why there isn't any output. Can someone please point in the direction of really well written tutorials, please? Or help indicate what is wrong with the code.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>
using namespace std;
int SIZE = 10;
int main()
{
int thisArray[] = { 99,86,44,55,78,63,0,32,11 };
int num = 0;
int n = 0;
int first;
int last;
int middle;
first = 0;
last = n - 1;
middle = (first + last) / 2;
cout << "Enter the total number of elements\n";
cin >> n;
cout << "Entered " << n << "number.\n";
for (int i = 0; i < n; i++) {
cin >> thisArray[i];
}
cout << "Enter a number to find.\n";
cin >> num;
while (first <= last) {
if (thisArray[middle] < num) {
first = middle + 1;
}
else if (thisArray[middle] == num ) {
cout << num << " found at location " << middle + 1 << "\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last) / 2;
}
return 0;
}
edit:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>
using namespace std;
int SIZE = 10;
int main()
{
//this is my binary search
int thisArray[10] = { 0,11,32,44,55,63,78,86,99 };
int i = 0; //index of the array
int n = 0; //variable of number that will be looked for
int first = 0;
int last = SIZE - 1;
int middle;
int pos = -1;
bool found = false;
int count = 0;
while (found) {
cout << "Enter a number to look for.\n";
cin >> n;
while (first <= last) {
middle = first + last / 2;
if (thisArray[middle] == n) {
pos = middle;
cout << "item found at " << middle + 1 << "\n";
exit(0);
}
else if (thisArray[middle] > n) {
last = middle - 1;
}
else {
first = middle + 1;
}//endif
}//end while
}//end big while
//if()
return 0;
}
I got it. Thanks for the help everyone!
It's not outputting anything because first == 0 and last == -1. Hence first <= last is never true and the loop body is never executed.
you know what ? how can you even be using binary search if the array is not sorted properly to use binary search property ... and please , stop answering question like Jack meagher style, I hate answer that isn't directly addressing the problem , its kinda restating the question ...
Simple
Change last = n - 1; to last = SIZE - 1;
Or calculate last = n - 1; after u have accepted the value of n
Also the array needs to be sorted!
Figured it out. Now though the code was an example that I had found the for loop was not working correctly for me, so I got rid of it. And for iteration I implemented a do-while loop. However, the code the works now.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>
using namespace std;
int SIZE = 10;
int main()
{
//this is my binary search
int thisArray[10] = { 0,11,32,44,55,63,78,86,99 };
int i = 0; //index of the array
int n = 0; //variable of number that will be looked for
int first = 0;
int last = SIZE - 1;
int middle;
int pos = -1;
bool found = false;
int count = 0;
do {
cout << "Enter a number to look for.\n";
cin >> n;
while (first <= last) {
middle = first + last / 2;
if (thisArray[middle] == n) {
pos = middle;
cout << "item found at " << middle + 1;
exit(0);
}
else if (thisArray[middle] > n) {
last = middle - 1;
}
else {
first = middle + 1;
}//endif
}//end while
} while (found = true);
return 0;
}

How to get every possible string of n characters in c++?

I know it is possible to use n nested for loops to get the result. This however isn't very flexible. If I wanted to get every string of n+2 characters I would have to write an extra two for loops.
I'm pretty sure I should use a parameter called n_Letters and use some kind of recursion. Any ideas? This is how my code looks right now. It gives all the 3 character combinations.
#include <iostream>
#include <string>
using namespace std;
void StringMaker(){
for(int firstLetter = 97; firstLetter < 123; firstLetter++){
char a = firstLetter;
for(int secondLetter = 97; secondLetter < 123; secondLetter++){
char b = secondLetter;
for(int thirdLetter = 97; thirdLetter < 123; thirdLetter++){
char c = thirdLetter;
cout << a << b << c << endl;
}
}
}
}
int main() {
StringMaker(); // I could add a parameter n_Letters here
}
This is a simple tree traversal problem that can easily be solved using recursion. Using a counter (count) and accumulator (partial) recur on your function for each letter until count is zero then print partial.
#include <iostream>
#include <string>
void StringMaker(int count, std::string partial = "") {
if (count == 0) {
std::cout << partial << '\n';
}
else {
for (char letter = 'a'; letter <= 'z'; ++letter) {
StringMaker(count - 1, partial + letter);
}
}
}
int main() {
StringMaker(3);
return 0;
}
Edit: It seems their are some concerns with my answer regarding memory allocations. If it's a concern for you, consider this alternative solution. Increment the first character if it isn't 'z', otherwise set it to a and repeat with the the second character. Do this until the last character is set from z to a. This acts as a sort of base 26 counter with count digits.
#include <iostream>
#include <string>
void StringMaker(size_t count)
{
std::string data(count, 'a');
size_t i = 0;
do
{
std::cout << data << '\n';
for (i = 0; i < count; ++i)
{
auto & next_char = data[i];
if (next_char < 'z') {
++next_char;
break;
}
else {
next_char = 'a';
}
}
} while (i != count);
}
int main() {
StringMaker(3);
return 0;
}
Here is my just-for-fun solution:
void StringMaker(int n)
{
int base = ('z' - 'a' + 1);
std::string str(n, '\0');
for(int i = 0; i < int_pow(base, n); ++i)
{
for(int j = 0; j < n; ++j)
{
str[n - j - 1] = 'a' + i / int_pow(base, j) % base;
}
cout << str << '\n';
}
}
Suppose we have i written in numerical system with base 26 (from a to z), so increment i with n = 4 give us aaaa, aaab and so on

least number of digits without duplicates

I am a C++ noob. I have a list of numbers that I put into a Vector. All numbers are 9 digit integers and are unique. I want to know what is the least amount of digits (starting from the right) that can be used to uniquily identify each number in the set. right now there are only 6 numbers, but the list could potentially grow into the thousands. I have posted my code thus far (not working.)
EDIT output is the following...
digit is 1
digit is 1
digit is 1
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
This is mostly a learning exercise. Please be generous and explicit with your comments and solutions.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector.at(j) % (10^k));
}
sort(newv.begin(), newv.end());
for (int i = 0; i < (newv.size() - 1); i++) {
if (newv.at(i) == newv.at(i + 1)) {
//there is a duplicate for this digit. Set flag.
myflag = true;
}
if (myflag == false) {
numberFound = true;
cout << "digit is " << k << endl;
} else {
k++;
}
}
}
// for (int i = 0; i < myVector.size(); i++) {
// cout << "||" << myVector.at(i) << "||" << endl;
// }
//
// for (int i = 0; i < newv.size(); i++) {
// cout << "---" << newv.at(i) << "---" << endl;
// }
return 0;
}
Check the below code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
int p = 1;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
newv.clear();
p = p * 10;
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector[j] % p);
}
sort(newv.begin(), newv.end());
myflag = false;
for (int i = 0; i < (newv.size() - 1); i++) {
if ( newv[i] == newv[i+1]) {
//there is a duplicate for this digit. Set flag.
myflag = true;
break;
}
}
if (myflag == true){
k ++;
}else{
numberFound = true;
cout << "digit is " << k << endl;
break;
}
}
return 0;
}
Sample Input:
123451789
123456687
125456789
123456780
Output:
digit is 4