I am trying to fit a word to a matrix by iteration but when I enter a row = 0, the function tries to check arbit_mat[r][c - 1] == '-' in the while loop and gives error. How can I fix this issue?
if (rotation == "CW")
{
switch (direction[0]) {
case 'l':
// left situation
while ((c - 1 >= 0) & (arbit_mat[r][c - 1] == '-')) {
arbit_mat[r][c - 1] = word[idx];
idx++;
c--;
printMatrix(arbit_mat);
if (idx == word.length())
{
return arbit_mat;
}
if (c == 0)
{
break;
}
}
I have written an if statement inside the loop to solve the problem but when the row starts with 0, it gives error of:
Vector subscript out of range!
Thank you for contributing.
You want
while ((c - 1 >= 0) && (arbit_mat[r][c - 1] == '-')) {
& is the bitwise and operator
&& is the logical and operator
Related
I am trying to solve the problem "Kick Start" from round G from last year. In short you need to count the number of appearances of the substring "KICK....START" with any number of characters in between the two words. The input is a string with only capital letters.
I wrote some code and the sample works fine. But after sending the code I get a runtime error in the first test case. I Have tried many different things like using the at() function from string, or substring but nothing has solved the problem. Any ideas what the problem could be?
So my function that gets the error looks like this:
long long fragment_count = 0;
long long open_count = 0;
string text;
cin >> text;
for (int i = 0; i < text.size() - 4; ++i) {
if (text[i] == 'K') {
if (text[i + 1] == 'I' && text[i + 2] == 'C' && text[i + 3] == 'K') {
open_count++;
}
} else if (text[i] == 'S') {
if (text[i + 1] == 'T' && text[i + 2] == 'A' && text[i + 3] == 'R' && text[i + 4] == 'T') {
fragment_count += open_count;
}
}
}
cout << fragment_count << "\n";
Edit: Outside of this function is the template I use for the kickstart problems. At the start there are two lines that I read that speed up io:
ios::sync_with_stdio(0);
cin.tie(0);
Then I just read a number with cin, that signifies the test cases and call the fucntion above for every test case.
text.size() is of type std::size_t, which is an unsigned type. If the length of the text is less than 4, text.size() - 4 wraps around and becomes a huge positive number.
Replace the comparison with i + 4 < text.size().
The context: I am trying to learn dynamic programming by coming up with a recursive solution and then caching the results of sub-problems.
I've been really struggling with this LeetCode problem.
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
An empty string is also valid.
Example 1:
Input: "()", Output: True
Example 2:
Input: "(*)", Output: True
Example 3:
Input: "(*))", Output: True
I managed to come up with a recursive solution that seems to work. However, I am not able to convert it to DP, I don't even understand where I should start or what I should be caching, i.e. I don't see how the results of the recursion sub-trees are the same for different subproblems. I am aware of an existing DP solution. But I am not able to relate it to my recursive one. Is it even possible to convert this particular solution to DP? I would really appreciate suggestions.
Here is my code:
class Solution {
public:
bool checkValidString(string s) {
stack<int> paren_stack;
int ind = 0;
return check_valid_rec(s, ind, paren_stack);
}
private:
bool check_valid_rec(string& s, int ind, stack<int> paren_stack) {
if (ind >= s.size())
return paren_stack.empty();
while (s[ind] != '*' && ind < s.size()) {
if (s[ind] == '(')
paren_stack.push('(');
else {
if (!paren_stack.empty() && paren_stack.top() == '(')
paren_stack.pop();
else return false;
}
ind++;
}
if (ind >= s.size())
return paren_stack.empty();
// if '*', there are three options
// 1. ignore '*'
bool ignore = check_valid_rec(s, ind + 1, paren_stack);
// 2. replace with '('
s[ind] = '(';
bool left_replace = check_valid_rec(s, ind, paren_stack);
// 3. replace with ')'
s[ind] = ')';
bool right_replace = check_valid_rec(s, ind, paren_stack);
if (ignore || left_replace || right_replace)
return true;
else
return false;
}
};
Your solution is an example of backtracking. It does not obey the overlapping subproblems property. The dp solution link you shared contains a correct approach. That is also easy to implement as recusrion as well as dp.
If you still want to stick to your approach(or something similar), you have to adjust your way to obey the overlapping subproblems property. I have an approach in mind which you can perhaps look into:
1. Start from the end of the given string.
2. Instead of a stack, maintain the count of left and right paranthesis.
3. Psudocode for recursion:
bool foo(pos,count_left_paranthesis,count_right_paranthesis):
if count_left_paranthesis > :
return false;
if (pos < 0)
return count_left_paranthesis == count_right_paranthesis;
if string[pos] == '(':
return foo(pos-1,count_left_paranthesis+1,count_right_paranthesis);
else if string[pos] == '):
return foo(pos-1,count_left_paranthesis,count_right_paranthesis+1);
else: // string[pos] = '*'
return foo(pos-1,count_left_paranthesis,count_right_paranthesis)
|| foo(pos-1,count_left_paranthesis,count_right_paranthesis+1)
|| foo(pos-1,count_left_paranthesis+1,count_right_paranthesis)
4. Memoize the results of the subproblems.
There are easier solutions available though.
I tried the above out myself and here's a working solution. Surprisingly it even got accepted.
class Solution {
public:
map<vector<int>,bool> dp;
bool foo(const string& s, int pos, int lc, int rc)
{
if (lc > rc) return false;
if (pos<0)
{
return lc == rc;
}
vector<int> v = {pos,lc,rc};
if (dp.find(v) != dp.end()) return dp[v];
if (s[pos] == '(')
{
return dp[v] = foo(s,pos-1,lc+1,rc);
}
else if (s[pos] == ')')
{
return dp[v] = foo(s,pos-1,lc,rc+1);
}
else
{
return dp[v] = (foo(s,pos-1,lc,rc) || foo(s,pos-1,lc+1,rc) || foo(s,pos-1,lc,rc+1));
}
}
bool checkValidString(string s) {
return foo(s,s.size()-1,0,0);
}
};
another quick optimization may be to use a vector to memoize instead but i'm lazy.
well you can even start from the start of the string. Starting from the back was easier to analyze for me
Note: This by no means is the most efficient method to solve the problem, this is just to help the OP with a recursive solution and then come up with a dp solution with the means of memoization (or "caching the results of sub-problems")
At first, your stack only contain '(' so can simply be a counter.
s is "nearly" constant so you have only ind, left_counter as variable for dp:
std::vector<std::vector<bool>> dp(s.size() + 1, std::vector<bool>(s.size(), false));
and dp[0][0] got your final result.
Now initialization:
if (ind >= s.size())
return paren_stack.empty();
so dp[s.size()][0] = true;
Now, passing from one column to the next (prev in our case :) ) (trying to keep your logic as much as I can):
switch (s[ind]) {
case '*':
dp[ind][j] = dp[ind + 1][j] /* Empty */
| (j > 0 && dp[ind + 1][j - 1]) /* ) */
| (j + 1 < s.size() && dp[ind + 1][j + 1]) /* ( */
;
break;
case '(': dp[ind][j] = (j + 1 < s.size() && dp[ind + 1][j + 1]); break;
case ')': dp[ind][j] = (j > 0 && dp[ind + 1][j - 1]); break;
}
Final result:
bool is_balanced(const std::string& s)
{
if (s.empty()) return true;
std::vector<std::vector<bool>> dp(s.size() + 1, std::vector<bool>(s.size(), false));
dp[s.size()][0] = true;
for (int ind = s.size() - 1; ind >= 0; --ind) {
for (std::size_t j = 0; j != s.size(); ++j) {
switch (s[ind]) {
case '*':
dp[ind][j] = dp[ind + 1][j] /* Empty */
| (j > 0 && dp[ind + 1][j - 1]) /* ) */
| (j + 1 < s.size() && dp[ind + 1][j + 1]) /* ( */
;
break;
case '(': dp[ind][j] = (j + 1 < s.size() && dp[ind + 1][j + 1]); break;
case ')': dp[ind][j] = (j > 0 && dp[ind + 1][j - 1]); break;
}
}
}
return dp[0][0];
}
Demo
I am trying to make when user types number, program should repeat that many times chosing random if
Here is my code
cin >> d;
c = 0;
while (c < d) {
c = c++;
num = (rand() % 3) + 1;
if (num == 1) {
system("start C:\\viewver\\vw");
Sleep(2000);
}
else if (num == 2) {
system("start C:\\viewver\\vw2");
Sleep(2300);
}
else if (num == 3) {
system("start C:\\viewver\\vw3");
Sleep(1800);
}
It always chooses to open first one and then stops.
Use == not =
if (num == 1) {
system("start C:\\test\\vw");
Sleep(2000);
}
else if (num == 2) {
system("start C:\\test\\vw2");
Sleep(2300);
}
else if (num == 3) {
system("start C:\\test\\vw3");
Sleep(1800);
}
== is for comparison, = is for assignment
The reason why it always chooses the first option is because C++ (and C) has the notion of truthy values. So any value that is not 0 is considered truthy, whereas values that evaluate to 0 are considered falsy.
In your original code, when you assign num to 1, the value of num is truthy, therefore that branch is always taken
I have a buffer of random characters streaming into my Arduino from a XBee module. I want to extract the first integer that it sees (will be <= 3-digit int if that makes a difference), then move on with that number and stop looking at the rest of the incoming characters.
For reference, I'm trying to use this as part of a 2-way handshake with a node.js server that doesn't get messed up when other Arduinos are also attempting to handshake or are already connected and sending data.
I think I have a way that might work to extract an int, but it seems really ugly, so I'm thinking there must be a much shorter/cleaner way to go about this. Here's my very long code to do something that's probably pretty simple:
String intString = "";
int intStart = 0;
for (int i = 0; i < msg.length(); i++) {
while (intStart != 2) {
if (intStart == 0) {
if ((msg[i] == '0') || (msg[i] == '1') || (msg[i] == '2') ||
(msg[i] == '3') || (msg[i] == '4') || (msg[i] == '5') ||
(msg[i] == '6') || (msg[i] == '7') || (msg[i] == '8') ||
(msg[i] == '9')) {
intString += msg[i];
intStart = 1;
}
}
// previous int, next is still int
if (intStart == 1) {
if ((msg[i] == '0') || (msg[i] == '1') || (msg[i] == '2') ||
(msg[i] == '3') || (msg[i] == '4') || (msg[i] == '5') ||
(msg[i] == '6') || (msg[i] == '7') || (msg[i] == '8') ||
(msg[i] == '9')) {
intString += msg[i];
intStart = 1;
}
}
// previous int, next is not int
else if ((msg[i] != '0') && (msg[i] != '1') && (msg[i] != '2') &&
(msg[i] != '3') && (msg[i] != '4') && (msg[i] == '5') &&
(msg[i] != '6') && (msg[i] != '7') && (msg[i] == '8') &&
(msg[i] != '9')) {
intStart = 2;
}
}
}
int number = intString.toInt();
Serial.println(number);
Any suggestions/advice is greatly appreciated.
Rather than compare against every number from 0 to 9, use the standard C function isdigit().
String intString = "";
int intStart = 0;
for (int i = 0; i < msg.length(); i++) {
while (intStart != 2) {
if (intStart == 0) {
if (isdigit(msg[i])){
intString += msg[i];
intStart = 1;
}
}
// previous int, next is still int
if (intStart == 1) {
if (isdigit(msg[i])) {
intString += msg[i];
intStart = 1;
}
}
// previous int, next is not int
else if ( isdigit(msg[i]) ) {
intStart = 2;
}
}
}
"Rubber duck debugging":
Let's assume the first char of the msg is a digit:
set intStart to 0
take the first char of the msg
while intStart is not yet 2
if intStart is 0 (it is, we haven't adjusted it) and the first char of the msg is digit (we assumed it is), then append the first char to intString and make intStart = 1
if intStart == 1 (it is, we set it at the prev step) and the first char of the msg is digit (it is still the first, i didn't change), then append the first char to intString (great, now I have it twice) and set intStart=1 (hey, intStart didn't change). Else... well, we can ignore else, we are in the good conditions for then
so back to the step 3, with the intStart==1 and i still 0 and the first char of the msg still a digit.
Should I continue or are you able to do it?
In essence, with the first char of the msg a digit, you'll never get out from while (intStart != 2) until you run out of heap-space due to intString growing by repeating the same fisrt char all over.
Is that what you want?
Is it so hard to explain this to your rubber duck before asking SO?(yes, I understand, Arduino doesn't have a debugger, but you still can use Serial.print)
[Update on the comments]
Sorry if I was unclear, but it doesn't necessarily start with an integer, the integer could be in the middle of the char buffer.
The first sequence of digits in the char buffer of any length (really doesn't have to be restricted to max 3-digit, only if it makes it easier)
So, before stating to collect, we just need to position ourselves on the first digit of the string buffer
int startScan=0;
// no body for the cycle, everything works just from
// the exit condition and increment
for(
;
startScan < msg.length() && ! isdigit(msg[i]); // as long as it's not a digit
startScan++
);
// from this position, start collecting for as long as we have digits
int intValue=0;
String intString;
for(; startScan < msg.length() && isdigit(msg[startScan]); startScan++) {
intString += msg[startScan]; // take it inside the string
// careful with this one, it may overflow if too many digits
intValue = intValue*10 + (msg[startScan]-'0');
}
// if we reached here with an empty intString, we didn't find any digits
If you don't need the intString, just the intValue, don;t use the intString - at most a bool hasDigits to init to false and set to true in place of intString += msg[startScan]; (to act as a signal for the 'no digits encountered' case).
If you don't need the intValue, just wipe out from the code anithing that uses it.
So, if my understating is correct, you have the following problem:
I have a String message which starts by at most 3 decimal digits and ends possibly with other info I don't need. I want that 'at most 3 digits' prefix transformed in an integer for me to use further
If this is you problem, then try this:
int intValue=0;
String intString;
int maxLookInto=(msg.length() > 3 ? 3 : msg.length()); // at most 3 digits
for(int i=0; i<maxLookInto && isdigit(msg[i]); i++) {
// if we got here, we know msg[i] is still a digit, otherwise
// we get out of cycle ealier
intString += msg[i]; // take it inside the string
intValue = intValue*10 + (msg[i]-'0'); // transforming in base 10 in an int
}
// Do what you like with either intString (textual representation of the
// at-most-3-digits or with the same value converted already to a number
// in intValue
If Arduino doesn't have the isdigit function available, you can implement your own like
int isdigit(char c) {
// we are using ASCII encoding for characters, aren't we?
return (c>='0' && c <='9');
}
One way is to use the String object. This has a toInt method.
BTW there is an Arduino specific stack exchange. arduino.stackexchange.com
I have tried writing a loop that would refrain the user to enter a wrong kind of data (actually a boolean) into the program by using the || operator.
int Entrer()
{
int A;
do
{
cout<<"Entrez 0 ou 1."<<endl;
cin >> A;
}
while (A != (1 || 0));
return A;
}
Can somebody tell me why the program only accepts 1 and no 0 ?
do { ... } while (A != (1 || 0));
It should be while (A != 1 && A != 0);
Otherwise, A != (1 || 0) stands for A != 1 since (1 || 0) is evaluated before !=.
If you want to accept 1 and 0, you need to write the conditional as while(A != 1 && A != 0);. As your conditional written, it will evaluate the (1 || 0) first, and, as 1 is true and 0 is false, will evaluate to A != 1.