Trying to find leaf nodes in a Quadtree (C++) [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am making a Quadtree in C++. I need to find the leaf nodes of the tree. To do this I have this function that needs to return a vector of the leaf nodes. For now everything else seems to work, but this function doesn't and I don't understand why.
vector<QuadTree*> find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {
if (quad->is_leaf) {
list_of_leaves.push_back(quad);
}
else {
for (int i = 0; i < 4; i++) {
find_leaves(quad->children[i], list_of_leaves);
}
}
return list_of_leaves;
}
Before doing it in C++ I did it in Python (which I know much better). This function does the same thing but in Python and works just fine :
def find_leaves(quad, list_of_leaves = []):
if quad.is_leaf:
list_of_leaves.append(quad)
else:
for i in quad.children:
find_leaves(i, list_of_leaves)
return list_of_leaves
In both these codes quad is a node of the tree. Does anyone see where the error is, or does anyone know another way to find leaf nodes in a QuadTree? Thank you for your help.

You are returning an empty vector, a temporary instead of the original.
Try this instead:
void find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {
if (quad->is_leaf) {
list_of_leaves.push_back(quad);
}
else {
for (int i = 0; i < 4; i++) {
find_leaves(quad->children[i], list_of_leaves);
}
}
}

Related

What's the difference b/w map[key] vs map.count(key) ? (particularly in this code) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
So I was Solving a leetcode Problem and one dumb mistake made in debugg for more than an hour.
Leetcode Question
Answers(both working and not working)
Working code:
`
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> map;
for(string s:words){
map[s]++;
}
bool isOdd = false;
int ans = 0;
for(auto i:map){
string rv = i.first;
reverse(rv.begin(),rv.end());
if(i.first[0]==i.first[1]){
if(i.second%2==0)
ans+=i.second;
else{
ans+= i.second-1;
isOdd = true;
}
}
else if(i.first[0]<i.first[1] && map.count(rv)){
ans += 2*min(i.second,map[rv]);
}
}
if(isOdd){
ans++;
}
return 2*ans;
}
};
Not working code:
`
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> map;
for(string s:words){
map[s]++;
}
bool isOdd = false;
int ans = 0;
for(auto i:map){
string rv = i.first;
reverse(rv.begin(),rv.end());
if(i.first[0]==i.first[1]){
if(i.second%2==0)
ans+=i.second;
else{
ans+= i.second-1;
isOdd = true;
}
}
else if(i.first[0]<i.first[1] && map[rv]){
ans += 2*min(i.second,map[rv]);
}
}
if(isOdd){
ans++;
}
return 2*ans;
}
};
The only difference between both code is map[rv] ==> map.count(rv)
test case which is giving error:
["oo","vv","uu","gg","pp","ff","ss","yy","vv","cc","rr","ig","jj","uu","ig","gb","zz","xx","ff","bb","ii","dd","ii",
"ee","mm","qq","ig","ww","ss","tt","vv","oo","ww","ss","bi","ff","gg","bi","jj","ee","gb",
"qq","bg","nn","vv","oo","bb","pp","ww","qq","mm","ee","tt","hh","ss","tt","ee","gi","ig","uu","ff","zz",
"ii","ff","ss","gi","yy","gb","mm","pp","uu","kk","jj","ee"]
Can anyone please help me?
I've tried googling this stuff but couldn't find it. then i've tried asking few people on discord. but no progress.
I just wanna know why above(not working part) code in not working.
What is the deal with map[key] and map.count(key)?
When should i use which one?
std::map.count() will check, if an element with a given key exists. It will not modify the container. Please see here. It is even defined as constto indicate that fact.
The std::maps index operator is different. It
returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
So, if the key does not exist, it will add an entry to the map, with this new key.
Therefore your second code cannot work.
map[rv] isn't a regular getter. It inserts default element if key is not found.
so you mutate (unordered_map) map whereas you iterate on it (which (might) invalidate iterator, making you loop undefined behavior).

longest common substring in array of strings runtime problem [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
string longestCommonPrefix(vector<string>& strs) {
string res = "";
int i, j;
bool flag = true;
for(int i=0; i<strs[0].size(); i++)
{
for(int j=0; j<strs.size()-1; j++)
{
if(strs[j][i] == strs[j+1][i])
{
flag = true;
}
else
return res;
}
if(flag == true)
{
res += strs[0][i];
}
}
return res;
}
I was doing this leetcode question where we had to find the longest common prefix of given array of strings and then i got stuck at this i cant understand what is the meaning of this error, most of the test cases are passed so i don't think logic is wrong.Is there any corner cases i am missing?
Runtime Error Message:
Line 924: Char 9: runtime error: reference binding to null pointer of type 'std::__cxx11::basic_string, std::allocator >' (stl_vector.h)
Last executed input:
[]
Thanks in advance
Its null pointer exception. So you should check if str is null i.e. str=='" for each string in vector.
and return answer accordingly.

Declare int variable aux a.length = (); Or use o.length () in all loops? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I wonder which is faster: Say I'm working with some text (30 characters), which would be better? And with a lot of text which would be better?
1-
int tam = text.length();
for(int i=0;i<tam;i++)
{
//something here//
}
2-
for(int i=0;i<a.length();i++)
{
//something here//
}
and also comparing these two:
1-
for (int i = 0; i < b.length(); i++)
{
aux = a.find(b[i]);
if (aux == -1)
{
sucess = 0;
break;
}
else
{
a.erase(aux,1);
}
}
2-
for (int i = 0; i < b.length(); i++)
{
if (a.find(b[i]) == -1)
{
sucess = 0;
break;
}
else
{
a.erase(a.find(b[i]),1);
}
}
Both first are the better approach.
On the first example you are checking if i<a.length() is true on every cycle. That means that you are going to execute a.length() for every iteration. If the variable a is not changed, it is unnecessary and the better approach is to calculate before and use that value.
Note that if the variable a is changed inside, placing i<a.length() might be the correct approach. It depends on your problem.
On the second example it is the same basics. You avoid useless calculations because you won't need to calculate a.find(b[i]) again inside the else.
As a general rule of thumb, as computations get bigger, more complex, and more frequent you want to minimize your unnecessary calculations. This means that storing something that needs to be calculated in a variable may speed up the process.
In both of your examples, for extremely large numbers,
int scratch = big.length();
for(int i=0;i<scratch;i++){
//body//
}
is usually faster.
In the future, general questions like this tend to belong in something like the Code Review Stack Exchange.

How can I rewrite this function in non-recursive form? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
How can I rewrite this function in non-recursive form?
void generate(int pos)
{
if (pos == n + 1)
{
print_table();
}
else
{
for (int i = 1; i <= n; i++)
{
if (!used[i])
{
used[i] = true;
perm[pos] = i;
generate(pos + 1);////recursion
used[i] = false;
}
}
}
}
This code appears to call print_table() for each permutation of the numbers 1,...,n. There is a built-in tool for this in C++.
#include <algorithm>
void generate() {
int n = 10; // or whatever
std::vector<int> perm(n);
for(int i=0; i<n; i++) perm[i] = i+1;
do {
print_table(perm);
} while(std::next_permutation(perm, perm+n));
}
Your code seems to be a standard recursive algorithm for generating all permutations of a list of elements. Rather than trying to mechanically massage the recursive algorithm into an iterative one (which would probably require a stack of some sort), you might want to look at iterative algorithms for listing off all permutations of a list. For example, C++ provides the std::next_permutation algorithm, which you can use to list permutations. For reference, I have a simple implementation of this algorithm along with commentary explaining how it works.
Hope this helps!

return statement not returning values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
check(a,b->junior);
b=b->next;
}
}
void main()
{
l = check(d,ceo);
cout<<l->name;
}
now initially the value of l->name is being printed but finally in main value of l is not being returned.
this means that it is reaching the return statement but l is not being returned.
can someone explain why?
What is happening is this, it is matching in one of the recursive calls to check and you then discard the return value. You need to change the function to look like this:
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
l = check(a,b->junior); // <----- line changed
if (l)
return l; // If we found something, return it.
b=b->next;
}
return 0; // <----- Always return a value
}
Also, there are various stylistic issues with your code, it would be clearer if you made changes something like this so that your variable and function names are useful:
emp* emp::findEmployeeByName(string name,emp* root)
{
if(root->name==a)
{
cout<<root->name;
return root;
}
// What on earth is ->j? Give your members meaningful names
for (employee* worker=l->j; worker; worker = worker->next)
{
emp* match = findEmployeeByName(name,worker->junior); // <----- line changed
if (match)
return match; // If we found something, return it.
}
return 0; // <----- Always return a value
}