How to complete this for-loop that calls a function [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am having trouble trying to make a certain for-loop continue to completion in the 1D Queens problem.
First, I used goto statements for everything. Now I am trying to get rid of the goto statements by using functions instead. I will eventually get rid of all of them, but I am focusing on NR (new row) and backtrack first, since they are meant to call each other.
The for loop I am having trouble with is the one that checks if a position is safe for a queen. I point out the for-loop that does not complete in the comments.
//forward declarations
int backtrack (int board[], int& c_position);
//NR: q[c]++;
//if (q[c]==8) goto backtrack;
void NR (int board[], int& c_position) //new row
{
board[c_position]++;
if (board[c_position]==8) {backtrack(board, c_position);}
}
int backtrack (int board[], int& c_position) // backtrack
{
c_position--;
if (c_position==-1) {system("PAUSE"); exit(1);}
NR(board, c_position);
}
int main ()
{
int q[8] = {0}; //1D array, the board, all set to 0;
int c=0;
int count=0;
NC: c++; //new column
if (c==8) goto print;
q[c]=-1;
NR(q, c);
//test to see if position is safe
for (int i=0; i<c; i++) //this is the for loop I am having trouble with
{
if ( (q[i]==q[c]) || ((c-i)==abs(q[c]-q[i])) ) { NR(q, c); }
}
goto NC;
print: //printing the 1D board gives us a single line, where each number represents a row where a queen is
count++;
cout << count << endl;
for(int j = 0; j <= 7; j++)
{
cout << q[j] << " ";
}
cout << endl;
backtrack(q, c);
system("PAUSE"); return 0;
}

You're passing c by reference to a function that passes it to another function that decrements it.
That appears to foil your (outer goto-based) loop's attempt to increment it.
Anyway, that's what I'd look at more closely.

Related

passing two dimensional array to function [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a problem with passing my created table to fillMatrix function.
Another thing is how to refer to this table in my function. I really appreciate every kind of help. I didn't get any console problem. Program is freezing.
int **createTable(int n)
{
int **table = new int*[n];
for(int i = 0; i<n; i++)
{
table[i] = new int[n];
}
return table;
}
void fillMatrix(int n, int **tab)
{
for(int x = 0; x<=n; x++)
{
for(int y= 0; y<=n; y++)
{
tab[x][y] = 0;
}
}
}
int main()
{
int n;
cout <<"Add size of table";
cin >> n;
int **table = createTable(n);
srand(time(NULL));
fillMatrix(n, table);
return 0;
}
I see only one problem in your code:
for(int x = 1; x <= n; x++)
{
for(int y = 1; y <= n; y++)
{
tab[x][y] = 0;
}
}
Arrays in C++ are zero-based, but you tried to assign tab[n][n] which causes undefined behavior.
Also, you should delete your array once it is no longer needed.
As another solution I suggest you use std::vector instead of dynamically allocated arrays.
it is what they told you about. Your for statement should be like this
for( int i = 0 ; i < n ; i++ )
instead of
for( int i = 0 ; i <= n ; i++ )
The compiler want warn you if you accidentally go beyond the size of an array thats why you didnt have any warnings or errors.
Think about using a vector instead of an array as suggested above.

c++ multiple finder [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
im trying to find multiples of an array using a loop
int array[11] = {1,2,3,4,5,6,7,8,9,10,11};
int size=11;
for(int i=0;i > size;i++)
{
if (i%2==!0)
cout << array[i];
}
why wont this work
//Declare num first.
//Correct if condition..
//correct condition checking in for loop
int array[11] = {1,2,3,4,5,6,7,8,9,10,11};
int index=2;
int size=11;
int num = 5;
for(int i=0;i < size;i++)
{
if (i%num==0)
cout << array[i];
}
I think you might want to change the (somewhat ... unusual):
if (i%2==!0)
into:
if (i % 2 == 0)
In addition, you loop termination condition is such that the loop will never execute. Try:
for (int i = 0; i < size; i++)

Coordinate system in C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi I would like to make a coordinate system using c++. I will be getting a few (x,y) coordinates from the user and using it I need to make a coordinate system(more of a map) style. How can I achieve this? It needs to look like the diagram below. Should I use a 2D array or vector and how to make the loop do the marking differently?
(2,0)(4,3)(7,8)
Needs to look like
**1************
***************
***************
***************
***1***********
***************
***************
********1******
This is the code I got so far, but the problem is I can't mark more than one coordinate in it. I just used 2 for loops to do it
for(int i = -6; i < 7; i++)
if (i < 0)
cout<<" "<<i;
else
cout<<" "<<i;
cout<<endl;
for(int i = 0; i < 15; i++)
{
cout<<(char)(i + 49);
for(int j = -6; j < 7; j++)
if(i == y - 1 && j == x)
cout<<" x ";
else
cout<<" . ";
cout<<(char)(i + 49)<<endl;
}
Please advise. Thanks !!
I would advice you to use either vector<string> or vector<vector<char> > or even vector<vector<string> > depending on what do you intend to store in a cell. If a cell is a single character then probably the first option is the best.
And after that creating the map is really easy:
int n,m;
cin >> n >> m;
vector<string> a(n, string(m, '*');
I am not sure what are the '.' and 'x' in the code above but I imaging all that is left for you is to input several pairs of coordinates and replace the respective element in the vector<string> with '1'.
Hope this helps.
I would advice using std::set of std::pair instead of std::vector - there is no need to keep whole grid in memory, we just need points.
http://liveworkspace.org/code/f434521b804485f16786556762780448
To answer your other problem, you could use a loop to make the changes and another to show your result.
Using izomorphius's suggestion, it would look like this if you use a list to store pairs of coordinates:
vector<string> matrix ;
list<pair> PairList ;
for (list<pair>::const_iterator it = PairList.beguin(); i < PairList.end(); it++) {
matrix[ (*it).second ][ (*it).first ] = "." ;
}
And to show the result:
for (int i = 0; i < matrix.size; i++) {
cout << matrix[i] << endl ;
}

arrays and index [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
How can I enter numbers into an array such that duplicate entries are ignored?
For example, if I put 6 and then 3 into the array, attempting to then insert 6 into the the array should cause 6 to be rejected (since it is already in the array).
#include <iostream>
using namespace std;
int main()
{
int x,y;
int number;
int arr[5];
for (x=0; x<5; )
{
cout<<"enter a number:"<<endl;
cin>>number;
bool replace = True;
for (y=0; y<x; y++)
{
if (number != arr[y])
{
cout << "try next time" << endl;
replace = False;
break;
}
}
if (replace)
{
arr[x] = number;
x++;
}
}
return 0;
}
std::set<int> would do what you want. This is not indexable, though.
You could use Boost.MultiIndex to give you random access and enforce uniqueness on the same underlying list of values.
btw - asking directly for code is not recommended practice.
you have too many x++'s and you don't preset arr (maybe more style than error)
how do you know it's not working?
(put some debug code inside of if (number == arr[y]) and if (replace)
What you really want is a set. Sets cannot contain duplicate elements.
Here is a reference to the set in C++.
Just use the set as a container for your numbers. When you try to add a duplicate, it will be automatically rejected.
You don't want an array but a datastructure called Hashtable for that;
Alternatively, you might want to look up a datastructure called associative array.
You shouldn't use arrays for this. You should use, for example, std::set. Or, if you need to have an array as your data structure, you could encapsulate the array (e.g. realized through std::vector) in a class and define specific functions to access the array elements. Additionally, you could hold a std::set to provide a fast check for existing elements.
Should be :
int arr[5] = {0,0,0,0,0};
Remove the x++ from the following line:
for (x=0;x<5;x++)
Then:
bool replace=true;
for (y=0;y<x;y++)
{
if (number == arr[y])
{
replace=false;
break;
}
}
if (replace)
{
arr[x]=number;
x++;
}
Finally, remove the :
else if(number == arr[x])
{
arr[x]=number;
cout << "try next time"<<endl;
}
You can insert :
cout << "try next time"<<endl;
before the
replace=false;
Take out the x++ in the for loop, That way you will only increment that count when you enter a new number.
Also, if you want to only run the loop five times, your outer for loop should be only to x<5.
All in all your outer loop should read:
for (x=0;x<5;)
Take a closer look at where you increment x.
It looks like you want to read in a sequence of numbers eliminating any duplicates.
It also appears that the maximum number of unique numbers is 5.
int n = 0; /* The number of unique numbers read in so far */
for {;;}
cout << "enter nmber" << endl;
cin >> number;
for (x=0; x < n; ++x) {
if (number == arr[x]) goto L1; /* I love messing with peoples head by using this goto */
}
arr[n] = number;
++n;
if (n == 5) break;
L1:
continue;
}

accessing an array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
i am declaring a global array,and then assigning the values inside a if statement. But when i am using the array in another if statement the array has different values other than i assigned previously.
For example:
int arr[5];
xyz(bool p,bool q)
{
if(p)
{
for(int i=0;i<5;i++)
{
arr[i]=rand()%100;
}
}
if(q)
{
for(i=0;i<5;i++)
printf("%d",arr[i]);
}
}
can anyone help??
Well, if p != q then any changes you make to arr in the first conditional will not be printed when you enter the second conditional. If arr was never initialized, it will almost certaninly not have the values you expect.
Edit: Based on your comment below, Try using a std::vector<int> instead of a C style integer array, as in:
#include <vector>
std::vector<int> arr(5); // was int arr[5]
Also a couple suggestions:
Where practical (which is almost, but not quite always) you should be using the standard containers in C++. They tend to be better behaved than C style arrays.
Use of global variable can sometimes lead to more problems than they solve. Recommend you make arr a local variable and pass it as a parameter where needed. This helps people looking at your code know what it needs and what it accesses without having to actually dig through the code to see it all. It's possible (perhaps even likely) that something else is changing arr without you knowing it. If you always pass arguments and refrain from using globals, this will help you discover where it's being changed.
So, combining these I would recommend doing something like:
#include <vector>
#include <iostream>
xyz(std::vector<int>& arr, bool p, bool q)
{
std::vector<int>::iterator ai;
if(p)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
*ai = rand() % 100;
}
}
if(q)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
std::cout << *ai << std::endl;
}
}
}
int main()
{
std::vector<int> arr(5);
xyz(arr, true, false);
xyz(arr, false, true);
return 0;
}
Try adjusting your first code block to something more like this:
if (p) {
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
printf("%i: %d\n", i, temp);
arr[i] = temp;
}
}
Now, you will get a listing of the random values before they are written into the array. Compare this list to what you get when you read them from the array later.
Update: I ran the above modification to your code on Codepad, and I am seeing the exact same values both times.
I don't even see why you're adding those 'bool' variables since you're not creating to never run it!
So just use this code [ which is the same as beta's version];
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
cout << i << temp << endl;
arr[i] = temp;
}