I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.
I am getting a OUTOFRANGE error with vector in c++ when using insert method. I don't know why this is happening but I was able to narrow down the problem to one line through debugging. Here is the full code.
//
#include <cstdio>
#include <iostream>
#include <vector>
#include <fstream>
#include <cassert>
#include <string>
using namespace std;
class suffixArray{
public: suffixArray(std:: string concatenated ){
vector<int> attempt1;
const int size = (int)concatenated.length();
int rank[7] = {};
char *suffixPointers[concatenated.length()];
int value[concatenated.length()];
for(int i =0; i <= size-1; i++){
suffixPointers[i] = &concatenated[i];
value[i] = (int)concatenated[i];
}
std::cout << "[";
for(int i = 0; i<= size-1; i++){
std::cout <<value[i] << " ";
}
std::cout << "]"<< std:: endl;
for(int i = 0; i<=size -1; i++){
if(i == 0){
rank[i] = i;
attempt1.push_back(i);
}
else if(value[i] > value[i-1]){
rank[i] = i;
attempt1.push_back(i);
}else{
int current =i;
int savedValue = value[i];
int prevSavedRank;
int indexcounter = i;
while(savedValue <= value[attempt1.at(indexcounter-1)] && indexcounter - 1 >= 0 ){
indexcounter--;
}
cout << indexcounter << endl;
attempt1.insert(attempt1.begin() + indexcounter ,i);
// while(savedValue <= value[rank[current-1]] && current-1 >= 0){
// prevSavedRank= rank[current-1];
// rank[current-1] = i;
// rank[current] = prevSavedRank;
// current--;
// }
}
}
int now;
for(int i = 0; i<= 3; i++){
now = attempt1[i];
std::cout << now << " ";
}
}
};
void read_file(string filename, string& contents, int& num_lines){
ifstream f;
f.open(filename.c_str());
string line;
contents = "";
num_lines = 0;
while(getline(f, line)){
contents.append(line.substr(0, line.length()));
num_lines++;
}
f.close();
}
int main(int argc, const char* argv[]) {
std:: string test = "BANANA$";
suffixArray testString (test);
string fn;
string contents;
int num_lines;
cout << "File 1:" << endl;
cin>> fn;
read_file(fn, contents, num_lines);
cout << "Read: " << fn << "\n";
cout << " * " << num_lines << " lines\n";
cout << " * " << contents.length() << " characters (excluding newlines)\n";
//cout <<" * " << contents << endl;
// char * contents_cstring = (char*)contents.c_str();
//for(int i =0; i< contents.length(); i++){
// assert(contents_cstring[i] == *(contents_cstring + 1));
// assert(contents_cstring[i] == contents.at(i));
//}
//assert(contents_cstring[contents.length()] == '\0');
return 0;
}
I have narrowed down the problem to be the problem to be from this line, but can not figure out why it is occurring, or how to fix it.
attempt1.insert(attempt1.begin() + indexcounter ,i);
Consider the first time the program reaches
int indexcounter = i;
while(savedValue <= value[attempt1.at(indexcounter-1)] && indexcounter - 1 >= 0){
indexcounter--;
}
i will be 1. indexcounter-1 will be 0. If the loop is entered,
int indexcounter = 1;
while(savedValue <= value[attempt1.at(0)] && 0 >= 0 ){
1--;
}
OK, so what happens the next time?
while(savedValue <= value[attempt1.at(-1)] && -1 >= 0 ){
0--;
}
value[attempt1.at(-1)] happens before -1 >= 0, s the trap to prevent -1 fails. Reverse the order of the tests.
while(indexcounter - 1 >= 0 && savedValue <= value[attempt1.at(indexcounter-1)])
Could be more bugs, but after that the program hangs and asks for a file that I don't have.
I am writing a program where the input data (in binary) is split into half and convert to integer to perform some calculation.
So I:
Accept binary input and store as "String"
Split string (note: to be treated as binary) into half and convert to int and store in x and y
So far i have written step 1.
int main() {
string input;
cout << "Enter data:";
getline(cin, input);
int n = input.size();
int n1 = n/2;
string a, b;
a = input.substr(0,n1);
b = input.substr(n1);
cout << "a: " << a;
cout << "b: " << b;
}
Would like to know how to achieve step 2.
Thanks in advance.
You can try this:
if(a.length() <= sizeof(unsigned int) * 8) {
unsigned x = 0;
for(int i = 0; i < a.length(); i++) {
x <<= 1; // shift byt 1 to the right
if(a[i] == '1')
x |= 1; // set the bit
else if(a[i] != '0') {
cout << "Attention: Invalid input: " << a[i] << endl;
break;
}
}
cout << "Result is " << x << endl;
}
else cout << "Input too long for an int" << endl;
It uses
shift left <<, to move the binary bits, when you go right in the ascii string;
binary or | for setting the bits.
int bin2dec(char* str) {
int n = 0;
int size = strlen(str) - 1;
int count = 0;
while ( *str != '\0' ) {
if ( *str == '1' )
n = n + pow(2, size - count );
count++;
str++;
}
return n;
}
int main() {
char* bin_str = "1100100";
cout << bin2dec(bin_str) << endl;
}
I am trying to solve this Problem.The question is as follows
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words.
Dictionary is an array of strings.
My Approach is the following recursive fn with storing of the results of recursive calls. The output is fine but I see that the stored result is never used.
My solution is hopefully correct as it passed the test cases.But I would be great if I know whether DP is used.
The code is:
#include <iostream>
#include <string.h>
using namespace std;
int r[100][100] = {0}; //To Store the calculated values
bool searchWord(char q[], char D[][20], int start, int end) {
cout << "In Search Word Loop with " << start << " " << end << endl;
char temp[end - start + 1];
int j = 0;
for (int i = start; i <= end ; ++i) {
//cout << "Looping i " << i << endl;
temp[j] = q[i];
j++;
}
// cout << "For Word " << temp << endl;
for (int i = 0; i < 12; ++i) {
// cout << "Comparing with " << D[i] << endl;
if (!strcmp(temp, D[i])) {
cout << "Found Word" << temp << " " << D[i] << endl;
return 1;
}
}
return 0;
}
bool searchSentence(char q[], char D[][20], int qstart, int qend) {
cout << "In Search Sentence Loop" << endl;
if (r[qstart][qend] != 0) {
cout << "DP Helped!!!" << endl;
return 1;
}
if (qstart == qend) {
if (searchWord(q, D, qstart, qstart))
return 1;
else return 0;
}
if (qstart > qend) return 1;
int i;
for (i = qstart; i <= qend; i++) {
if (searchWord(q, D, qstart, i)) {
r[i + 1][qend] = searchSentence(q, D, i + 1, qend);
if (r[i + 1][qend] == 1) return 1;
}
}
return 0;
}
int main() {
char D[20][20] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"};
char q[100] = "samsungmango";
int index = 0; char ch;
ch = q[0];
while (ch != '\0') {
index++;
ch = q[index];
}
if (searchSentence(q, D, 0, index - 1))
cout << "Yes" << endl;
else cout << "No" << endl;
}
Is recursion mandatory? I see, iterative DP-solution is easiest and compact:
#include <stdio.h>
#include <string.h>
int main() {
const char *D[] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango", NULL};
const char q[] = "samsungmango";
char dp[100];
short d_len[20];
memset(dp, 0, sizeof(dp));
dp[0] = 1; // 0 element is always reacheable
int i, j;
// compute dict string lengths
for(i = 0; D[i]; i++)
d_len[i] = strlen(D[i]);
// Compute splits using DP array
for(i = 0; q[i] != 0; i++)
if(dp[i]) // this index is reacheable
for(j = 0; D[j]; j++) // try to make next reacheable indexes
if(strncmp(&q[i], D[j], d_len[j]) == 0)
dp[i + d_len[j]] = 1; // That position is reacheable, too
// if EOLN(q) is reached, then yes
printf("Answer is %s\n", dp[i]? "YES" : "NO");
} // main
Your code is actually wrong. To fail your code, try input like "likeman"
Note that there are two different return values possible from function searchSentence, 0 or 1. So if you initialize the r array with 0 there's no guarantee it's a new state when r[x][y] = 0. Initialize r array with some impossible value like -1 or 2 for this program and test again. Now you can easily confirm that if r[qbegin][qend] != -1 then this state has already been checked so you can return r[qbegin][qend] from here
Updated code :
#include <iostream>
#include <string.h>
using namespace std;
int r[100][100]; //To Store the calculated values
bool searchWord(char q[], char D[][20], int start, int end)
{
cout << "In Search Word Loop with " << start << " " << end << endl;
char temp[end - start + 1];
int j = 0;
for (int i = start; i <= end ; ++i)
{
//cout << "Looping i " << i << endl;
temp[j] = q[i];
j++;
}
temp[j] = '\0';
//cout << "For Word " << temp << endl;
for (int i = 0; i < 12; ++i)
{
// cout << "Comparing with " << D[i] << endl;
if (!strcmp(temp, D[i]))
{
cout << "Found Word" << temp << " " << D[i] << endl;
return 1;
}
}
return 0;
}
bool searchSentence(char q[], char D[][20], int qstart, int qend)
{
cout << "In Search Sentence Loop" << endl;
if (r[qstart][qend] != -1)
{
cout << "DP Helped!!!" << endl;
return r[qstart][qend];
}
if (qstart == qend)
{
if (searchWord(q, D, qstart, qstart))
return 1;
else return 0;
}
if (qstart > qend) return 1;
int i;
for (i = qstart; i <= qend; i++)
{
if (searchWord(q, D, qstart, i))
{
r[i + 1][qend] = searchSentence(q, D, i + 1, qend);
if (r[i + 1][qend] == 1) return 1;
}
}
return 0;
}
int main()
{
char D[20][20] = { "i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"};
char q[100] = "ilike";
int index = 0; char ch;
ch = q[0];
memset(r, -1, sizeof(r));
while (ch != '\0')
{
index++;
ch = q[index];
}
if (searchSentence(q, D, 0, index - 1))
cout << "Yes" << endl;
else cout << "No" << endl;
}
P.S : There are some redundant lines of codes but I didn't change them and I added a null character in the end of the character array temp in function searchWord
I have one more question, I want to add a _ in front of every Capital letter which will be converted to lowercase, plus the first letter cannot be capital!! I cant figure out how to do it... :{ example:
input: loLollL, output: lo_loll_l
and I want it to go backwards too: input: lo_loll_l output: loLollL
code is here:
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
const int max = 100;
string slovo;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
// funkcia na zabezpecenie minimalneho poctu chars
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
cin >> slovo;
if(slovo.size() > max)
{
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
}
while( slovo.size() > max)
{
cin >> slovo;
}
for (int i=0; i <= slovo.size(); i++)
{
int s = slovo[i];
while (s > 'A' && s <= 'Z')
{
if(s<='Z' && s>='A'){
return s-('Z'-'_z');
}else{
cout << "chyba";
}
}
}
cout << slovo[i] << endl;
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
EDIT>
for (int i=0; i <= slovo.size(); i++)
{
while (slovo[i] >= 'A' && slovo[i] <= 'Z')
{
string s = transform(slovo[i]);
cout << s << endl;
s = untransform(s);
cout << s << endl;
}
}
This should work:
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
string
transform(const string& s)
{
const size_t n = s.size();
string t;
for (size_t i = 0; i < n; ++i)
{
const char c = s[i];
if (isupper(c))
{
t.push_back('_');
}
t.push_back(tolower(c));
}
return t;
}
string
untransform(const string& s)
{
string t;
const size_t n = s.size();
size_t i = 0;
while (i < n)
{
char c = s[i++];
if (c != '_')
{
t.push_back(c);
continue;
}
c = s[i++];
t.push_back(toupper(c));
}
return t;
}
int
main()
{
string s = transform("loLollL");
cout << s << endl;
s = untransform(s);
cout << s << endl;
}