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

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!

Related

Why is my binary search algorithm so slow despite theoretically being O(log n) time? [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 months ago.
Improve this question
I implemented a binary search, and in theory should run in O(log N) time, and this holds up when counting the number of times it is looped through. However, when it is run, it seems to be extremely slow.
int binary_search(int i, vector<int> list) {
int min_ = 0;
int max_ = list.size();
while (max_ != min_+1) {
if (list[(max_+min_)/2] > i) {
max_ = (max_+min_)/2;
} else if (list[(max_+min_)/2] <= i) {
min_ = (max_+min_)/2;
}
}
return min_;
}
Can anyone explain why my algorithm is so slow?
For starters, you're making a copy of the vector<int> list that is passed in. Change it to be pass by reference:
Instead of this:
int binary_search(int i, vector<int> list) {
This:
int binary_search(int i, const vector<int>& list) {

Trying to find leaf nodes in a Quadtree (C++) [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 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);
}
}
}

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 to iterate on a subset of an STL Map in C++ [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 6 years ago.
Improve this question
I don't understand how to iterate only on a portion of an Stl map and not from begin to end like in standard traversate. Here is my code:
auto end = temp_map.rbegin() + THRESHOLD_NUM;
for (auto rit = temp_map.rbegin(); rit != end; ++rit)
{
int s = rit->second;
for (int k = 0; k < MAX_ROWS; k++)
{
array_dist_it[k] = abs(input[k] - input_matrix[k][s]);
}
float av_real = mean(MAX_ROWS, array_dist_it);
float score_real = score_func(av_real);
rank_function(score_real, s);
}
}
I think that the problem is related to the syntax of the for loop and in particular to the iterator. The error is about an invalid operator.
A std::map has a BidirectionalIterator. It supports incrementing and decrementing but not addition or subtraction. If you need to advance and iterator N times then you can use std::next. Using that instead of
auto end = temp_map.rbegin() + THRESHOLD_NUM;
You would have
auto end = std::next(temp_map.rbegin(), THRESHOLD_NUM);

Same average function c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
I'm trying to compare averages of an array and to detect if there is any similar averages,
for example if I have these averages 25,30,70,30,60 so the function should return true because 30 is twice there ,but it seems what I'm doing is wrong
bool sameAverage(Student Array[],int size)
{
bool isSame=false;
for (int i=0;i<size;i++)
{
for (int j=0;j<size;j++)
{
if (Array[i].getAverageGrade==Array[j].getAverageGrade)
isSame=true;
}
}
return isSame;
}
it is showing me a red line under the dot operator
Array[i].getAverageGrade is a function. You can compare that function to another function (like Array[j].getAverageGrade) but what you really want is to
call that function
compare the result to the result of calling the other function:
Array[i].getAverageGrade() == Array[j].getAverageGrade()
BTW: Please keep in mind what others have told you about comparing double values.
What I understand is that, you are looking for duplicates in the array.
First sort your array.
Then, Use a single loop to iterate through the array. Two loops are not needed.
bool sameAverage(Student Array[],int size)
{
for(int i = 0; i < size - 1; i++) {
//Use your favorite way to compare floating point numbers for equality
if ((Array[i].getAverageGrade() - Array[i + 1].getAverageGrade()) < 0.0001) {
return true;
}
}
return false;
}