How to step over a recursive call while debugging? - xcode

I have tried in two IDEs namely Clion and Xcode and I get the same results.
The debugger steps into isMatch function again even if I use stepOver. I've successfully used 'stepOver' in case of other functions but I'm not sure if it works the expected way for recursive calls. Can someone help me with this?
bool isMatch(string s, string p) {
//Base case
if(s.length() == 0 && p.length() == 0)
return true;
else if(p[1] == '*') {
int i = 0;
for (; (s[i] == p[0] || p[0] == '.') && i<s.length() ; i++) {
string temp1 = s.substr(i);
string temp2 = !p.length()? "" : p.substr(2);
if (isMatch(temp1, temp2))
return true;
}
if( isMatch(s.substr(i), !p.length()? "" : p.substr(2) ))
return true;
return false;
}
else
return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
}

Related

implement divide algorithm without using "/" for floating point

please if there is any specific algorithm for implementing the divide operator as a function, guide me about their name. I want to implement a function that takes two floating number and return the result of the divide, but in implementation, I won't use "/".
I have done this in a much simpler version when we want just the q in integer,
function divide(num0, num1) {
if ("bigint" != typeof num0 || "bigint" != typeof num1) {
throw new TypeError("The arguments should be bigint.");
}
if (num1 > num0) {
return 0;
}
for (var i = 0n; num0 >= num1; i++) {
num0 -= num1;
}
return i;
}
"I use bigint numeric type just two restrict to integer"
but I think this approach couldn't extend two return floating results. my guess is I approach binary level operation or so; thanks if learning me about any flowchart, pseudo-code, or code-snippet "in any language" to deal with this problem
I wrote this one for this question in js:
function justIntegerDivide(num0, num1) {
for (var q = 0; num0 >= num1; q++) {
num0 -= num1;
}
return [q, num0];
}
const divide = (n0, n1, afterPoint = 10) => {
if ((0 == n1 || 0n == n1) && 0 < n0) return Infinity;
if ((0 == n1 || 0n == n1) && 0 > n0) return -Infinity;
if ((0 == n1 || 0n == n1) && 0 == n0) return NaN;
if ("number" == typeof n0 && "number" == typeof n1) {
let sign = Math.sign(n0) * Math.sign(n1);
let num0 = Math.abs(n0),
num1 = Math.abs(n1);
let counter = 0;
let [q, r] = justIntegerDivide(num0, num1);
result = `${q}.`;
for (counter = 1; counter < afterPoint; counter++) {
var newReminder;
let qAfter;
previousReminder = 1 == counter ? r : newReminder;
[qAfter, newReminder] = justIntegerDivide(previousReminder * 10, num1);
result += qAfter;
if (0 == newReminder) {
return +result * sign;
}
}
return +result * sign;
} else if ("bigint" == typeof n0 && "bigint" == typeof n1) {
let sign = (n0 > 0 && n1 > 0) || (n0 < 0 && n1 < 0) ? 1n : -1n;
let num0 = n0 > 0 ? n0 : -n0;
let num1 = n1 > 0 ? n1 : -n1;
if (num0 < num1) {
return 0n;
}
for (var i = 0n; num0 >= num1; i++) {
num0 -= num1;
}
return i * sign;
} else {
throw new TypeError("Both arguments should be number or bigint");
}
};

Unable to compare pointes and integeres in c++14

I'm trying to program a code decoder. But I get the following error for all the comparisons in the if statements:
'error: ISO C++ forbids comparison between pointer and integer
[-fpermissive]'
The examples for the input string are ".-.--" and "-..-.--".
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
int c[100], t = 0, l, i = 0;
l = s.length();
cin >> s;
if (s[0] == '.') {
c[0] = 0;
t += 1;
while (i < l) {
if (s[i] == '-' && s[i + 1] == '.') {
c[t] = 1;
t += 1;
i += 2;
}
if (s[i] == '.') {
c[t] = 0;
t += 1;
i++;
}
if (s[i] == '-' && s[i + 1] == '-') {
c[t] = 2;
t += 1;
i += 2;
}
}
}
if (s[0] == '-' && s[1] == '.') {
c[0] = 1;
t += 1;
while (i < l) {
if (s[i] == '-' && s[i + 1] == '.'
'){
c[t] = 1; t += 1; i += 2;
}
if (s[i] == '.') {
c[t] = 0;
t += 1;
i++;
}
if (s[i] == '-' && s[i + 1] == '-') {
c[t] = 2;
t += 1;
i += 2;
}
}
}
if (s[0] == '-' && s[1] == '-') {
c[0] = 2;
t += 1;
while (i < l) {
if (s[i] == '-' && s[i + 1] == '.') {
c[t] = 1;
t += 1;
i += 2;
}
if (s[i] == ".") {
c[t] = 0;
t += 1;
i++;
}
if (s[i] == "-" && s[i + 1] == "-") {
c[t] = 2;
t += 1;
i += 2;
}
}
}
for (i = 0; i < t; i++) {
cout << s[t];
}
return 0;
}
How do I resolve this issue?
You were using single quotes until you got here:
if(s[i]=="-"&&s[i+1]=="-"){
You need to change it to single quotes so you have an int to int comparison.
if(s[i]=='-'&&s[i+1]=='-'){
When you say
"-"
you are creating a pointer.
When you say
'='
you are creating an int.
(" ") is a string literal which is char const * which is a pointer and (' ') is char which get promoted to int, so you can't compare them. They must be type compatible.

How to call a function recursively when using a WHILE loop and break it properly?

I am trying to transform a string by removing a letter A with an adjacent letter B or by removing a letter C toghether with an adjacent letter D.
For example 1, given a string "CBACD", it should be transformed as
CBACD -> CCD -> C
Example 2: given a string "CABABD", it should return nothing as the transformation goes like below:
CABABD -> CABD -> CD ->
Example 3: "ACBDACBD", There are no corresponding adjacent characters to A & C so the entire string should be returned
"ACBDACBD" -> "ACBDACBD"
I have written the following code to do the operation:
object RemoveCharsABCD {
val s = scala.io.StdIn
def adjacent(s: String): String = {
val charSet = ArrayBuffer("AB","BA","CD","DC")
var i = 0
var ret:String = ""
while(i < s.length-1) {
if(charSet.contains(s"${s.charAt(i)}${s.charAt(i+1)}")) {
s.slice(i+2, s.length)
i += 2
if(i == s.length-1) ret = s"$ret${s.charAt(i).toString}"
} else {
ret = s"$ret${s.charAt(i).toString}"
i += 1
if(i == s.length-1) ret = s"$ret${s.charAt(i).toString}"
}
}
println("Ret: " + ret)
ret
}
def main(args: Array[String]): Unit = {
println("Enter a String: ")
var s = scala.io.StdIn.readLine().toString
adjacent(s)
}
}
The above code works fine for the first iteration which is: CABABD -> CABD
For the inputs: ACBDACBD, CBACD, the output is correct but for ACBDACBD, the output is CD.
I called the method adjacent before the print statement as below:
if(ret.length >= 2) {
adjacent(ret)
}
println("Ret: " + ret)
But this goes to infinite loop and give stackoverflow exception.
I am unable to call the method: adjacent recursively so that it can work until the end of the string ?
Could anyone let me know how can I properly call the method: adjacent recursively so that the entire string is processed until the end ?
Seems pretty straight forward.
#annotation.tailrec
def adjacent(s: String): String = {
val next = s.replaceAll("AB|BA|CD|DC", "")
if (s == next) s else adjacent(next)
}
adjacent("CBACD") //res0: String = C
adjacent("CABABD") //res1: String =
adjacent("ACBDACBD") //res2: String = ACBDACBD
This could be done in Java, as follows :
public static String remove(String str)
{
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
int i = 0, k = 0;
while (i < str.length())
{
if ( chars[i] == 'B' && (k > 0 && chars[k - 1] == 'A') ||
chars[i] == 'A' && (k > 0 && chars[k - 1] == 'B') ||
chars[i] == 'C' && (k > 0 && chars[k - 1] == 'D') ||
chars[i] == 'D' && (k > 0 && chars[k - 1] == 'C'))
{
--k;
++i;
}
else {
chars[k++] = chars[i++];
}
}
return new String(chars).substring(0, k);
}
private static String stringAfterRemove(String str,int val,int lengthOfString) {
String nStr = str.replaceAll("CD", "").replaceAll("DC", "").replaceAll("AB", "").replaceAll("BA", "");
if(val==lengthOfString)
return str;
return stringAfterRemove(nStr,++val,lengthOfString);
}
In main method, initialize int val =0.
public static String solution(String str) {
String next = str.replaceAll("AB|CD|DC|BA", "");
if(str.equals(next))
return str;
else
return solution(next);
}

For a given string which contains only digits , what's the optimal approach to return all valid ip address combinations?

Example:
Given “25525511135”
Output : [“255.255.11.135”, “255.255.111.35”]. (sorted order)
Kindly let me know if we could do a depth first search over here ?(that's the only thing striking me )
Why is it important to have an 'optimal' approach for answering this?
There are not many permutations so the simple approach of checking every combination that fits into the IP format and then filtering out those that have out of range numbers will easily work.
It's unlikely to be a bottle neck for whatever this is part of.
You probably want a dynamic programming algorithm for the general case (something like
http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/).
Instead of testing whether prefixes can be segmented into words in the dictionary, you'd be testing to see whether the prefixes are prefixes of some valid IPv4 address.
Brutal DFS is acceptable in this problem:
class Solution{
private:
vector<string> ans;
int len;
string cur, rec, str;
bool IsOk(string s) {
if(s[0] == '0' && s.size() > 1) return false;
int sum = 0;
for(int i = 0; i < s.size(); i ++) {
if(s[i] == '.') return false;
sum = sum * 10 + s[i] - '0';
}
if(sum >= 0 && sum <= 255) return true;
return false;
}
void dfs(int x, int cnt) {
if(x == len) {
if(str.size() != len + 4) return ;
string tmp(str);
tmp.erase(tmp.size() - 1, 1);
if(cnt == 4) ans.push_back(tmp);
return ;
}
if(cnt > 4 || str.size() > len + 4) return ;
string tmp = cur;
cur += rec[x];
if(!IsOk(cur)) {
cur = tmp;
return ;
}
dfs(x + 1, cnt);
string tmp2 = cur + '.';
str += tmp2;
cur = "";
dfs(x + 1, cnt + 1);
str.erase(str.size() - tmp2.size(), tmp2.size());
cur = tmp;
}
public:
vector<string> restoreIpAddresses(string s) {
this->len = s.size();
this->rec = s;
cur = str = "";
ans.clear();
dfs(0, 0);
return ans;
}
};
Here is a recursive solution on JavaScript. The result is not sorted.
// Task from https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/
// Given a string containing only digits, restore it by returning all possible valid IP address combinations.
//
// Example:
// Input : 25525511135
// Output : [“255.255.11.135”, “255.255.111.35”]
//
(function () {
function getValidIP(str) {
const result = [];
const length = str.length;
check(0, 0, '');
function check(start, level, previous){
let i = 0;
let num;
if (level === 3) {
num = str.substring(start);
if (num && num < 256) {
result.push(`${previous}.${num}`);
}
return;
}
num = str.substring(start, start + 1);
if (num == 0) {
check(start + 1, level + 1, level === 0 ? `${num}`: `${previous}.${num}`);
} else {
while (num.length < 4 && num < 256 && start + i + 1 < length) {
check(start + i + 1, level + 1, level === 0 ? `${num}`: `${previous}.${num}`);
i++;
num = str.substring(start, start + i + 1);
}
}
}
return result;
}
console.log('12345:')
console.time('1-1');
console.log(getValidIP('12345'));
console.timeEnd('1-1');
console.log('1234:')
console.time('1-2');
console.log(getValidIP('1234'));
console.timeEnd('1-2');
console.log('2555011135:')
console.time('1-3');
console.log(getValidIP('2555011135'));
console.timeEnd('1-3');
console.log('222011135:')
console.time('1-4');
console.log(getValidIP('222011135'));
console.timeEnd('1-4');
})();

Find text path through character matrix with recursive algorithm

I'm trying to solve this question: http://www.spoj.com/problems/ALLIZWEL/
Find whether there is a path in the given matrix which makes the
sentence “ALL IZZ WELL”.
There is a path from any cell to all its neighbouring cells.
A neighbour may share an edge or a corner.
Input Specification:
The first line consists of an integer t representing the number of test cases.
The first line of each test
case consists of two integers R and C representing the number of rows and number of columns in the matrix.
Output Specification:
For each test case print “YES” if there is a path which makes the sentence “ALLIZZWELL”.
Else print “NO”.
For sample test cases, open the link.
My code:
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <stack>
#include <queue>
#include <climits>
#include <set>
using namespace std;
char matrix[101][101];
bool var;
int r,c;
bool check (string str,int pos, bool visited[101][101],int i, int j);
int main (void)
{
int t,i,j;
cin>>t;
bool ans;
while (t != 0)
{
int r,c,flag=0;
cin>>r>>c;
for ( i = 0; i < r; i++ )
{
for ( j = 0; j < c; j++ )
{
cin>>matrix[i][j];
}
}
string str = "ALLIZZWELL";
int pos = 1;
for ( i = 0; i < r; i++ )
{
for ( j = 0; j < c; j++ )
{
bool visited[101][101];
for ( i = 0; i < 101; i++ )
for ( j = 0; j < 101; j++ )
visited[i][j] = false;
visited[i][j] = true;
if (matrix[i][j] == 'A') // for all possible starting positions
ans = check(str,pos,visited,i,j);
if (ans == true)
{
cout<<"YES\n";
flag = 1;
break;
}
if (flag == 1)
break;
}
}
if (flag == 0)
cout<<"NO\n";
t--;
}
return 0;
}
bool check (string str,int pos, bool visited[101][101],int i, int j) // checking for all possible test cases
{
bool result = false;
if (pos == str.length() + 1)
return true;
if (i+1 < r && visited[i+1][j] != true && matrix[i+1][j] == str[pos])
{
visited[i+1][j] = true;
result = result || check(str,pos+1,visited,i+1,j);
if (result == false)
visited[i+1][j] = false;
}
else if (i-1 >= 0 && visited[i-1][j] != true && matrix[i-1][j] == str[pos])
{
visited[i-1][j] = true;
result = result || check(str,pos+1,visited,i-1,j);
if (result == false)
visited[i-1][j] = true;
}
else if (j+1 < c && visited[i][j+1] != true && matrix[i][j+1] == str[pos])
{
visited[i][j+1] = true;
result = result || check(str,pos+1,visited,i,j+1);
if (result == false)
visited[i][j+1] = true;
}
else if (j-1 >= 0 && visited[i][j-1] != true && matrix[i][j-1] == str[pos])
{
visited[i][j-1] = true;
result = result || check(str,pos+1,visited,i,j-1);
if (result == false)
visited[i][j-1] = true;
}
else if (i+1 < r && j+1 < c && visited[i+1][j+1] != true && matrix[i+1][j+1] == str[pos])
{
visited[i+1][j+1] = true;
result = result || check(str,pos+1,visited,i+1,j+1);
if (result == false)
visited[i+1][j+1] = true;
}
else if (i+1 < r && j-1 >= 0 && visited[i+1][j-1] != true && matrix[i+1][j-1] == str[pos])
{
visited[i+1][j-1] = true;
result = result || check(str,pos+1,visited,i+1,j-1);
if (result == false)
visited[i+1][j-1] = true;
}
else if (i-1 >= 0 && j+1 < c && visited[i-1][j+1] != true && matrix[i-1][j+1] == str[pos])
{
visited[i-1][j+1] = true;
result = result || check(str,pos+1,visited,i-1,j+1);
if (result == false)
visited[i-1][j+1] = true;
}
else if (i-1 >= 0 && j-1 >= 0 && visited[i-1][j-1]!= true && matrix[i-1][j-1] == str[pos])
{
visited[i-1][j-1] = true;
result = result || check(str,pos+1,visited,i-1,j-1);
if (result == false)
visited[i-1][j-1] = true;
}
return false;
}
The code is quite self-explanatory: I am trying all possible cases.
I am getting a WA in the third test case, i.e.
2 9
A.L.Z.E..
.L.I.W.L.
I tried debugging but I couldn't narrow down my problem.
The main problems are:
Using i and j in the loop clearing visited (as well as the outer loops)
Using r and c as global variables in check, but writing them as local variables in main
Always returning false from check (instead of result)
Only trying the first choice in check (turn "else if" into "if")
Not clearing the value in ans
Only breaking out of the inner loop, not both the i and j loop
Terminating the search when pos gets to str.length()+1 instead of str.length()
It often helps to put some print statements in recursive functions like these, try them out on a simple example, and see whether the sequence of calls matches your expectations.

Resources