I have an assignment in which i have to create a console program in c++ that draws Hexagons in a given style. The problem i am having is; my For loops are never entered and i can't figure out why. here's the snippet of code I'm having trouble with.
void display()
{
int counter=0;//var that keeps track of the layer that is being drawn
for(int i=0;i>=size;i++)//spaces before first layer of hexagon
{
cout<<" ";
}
for (int k=0; k>size;k++)//top layer of hexagon
{
cout<<"_";
}
cout<<endl;//ends the first layer
for (counter; counter>=size-1;counter++)//outer loop for the top half that controls the size
{
for( int j=0;j>(size-counter);j++)//adds spaces before the shape
{
cout<<" ";
}
cout<<"/";
for( int p=0; p>(size+(counter*2));p++)//loop for the hexagon fill
{
cout<<fill;
}
cout<<"\\"<<endl;
}
for(counter;counter==0;counter--); //loop for bottom half of the hexagon
{
for( int j=0;j>(size-counter);j++)//adds spaces before the shape
{
cout<<" ";
}
cout<<"\\";
for( int p=0; p>(size+(counter*2));p++)//loop for the hexagon fill
{
cout<<fill;
}
cout<<"/"<<endl;
}
cout<<"\\";
for(int r=0; r>=size;r++){cout<<"_";}
cout<<"/"<<endl;
}
the 'Size' and 'fill' are selceted earlier in the program during my main()
I'm probably missing something very simple but I've been struggling with this for a while. Any help would be greatly appricated!
Your loops use > and start at 0. It seems you want < instead. For example
for(int i=0;i<size;i++)//spaces before first layer of hexagon
{
cout<<" ";
}
I am not sure what is the content of your size variable but it looks like you have got your loop conditions wrong:
for(int i=0;i>=size;i++)
probably should be:
for(int i=0;i<size;i++)
The same goes for other loops.
Assuming your size is a postive number, it works as per your condition.
Change the > conditojs to < in your conditions.
In your conditions, invert the > to <
< means inferior, you want to do a
for i = 0; if i < size; i++
You do
for i = 0 ; if i > size ; i ++
if size is superior to i (0) the loop will never trigger
Aren't all of your < and > reversed? Because
(int k=0; k>size;k++)
makes no sense to me.
for loops in C++ are while loops, not until loops.
C++ has only while loops (with the meaning of as long as):
for (int i=0; i<10; ++i)
....
int i=0;
while (i<10) {
....
++i;
}
Related
The n-queens problem asks how many different ways are there to put n queens on a n-by-n board such that the queens cannot attack each other in one move. I've written a program which partially solves this problem. I say partially because my program only works for n<=10. However, I did not specify or hard-code the value 10, or any other value, in my code.
For example, my code outputs 92 solutions for 8-by-8, 352 for 9-by-9, and 724 for 10-by-10. These are the expected values as stated on the n-queens wikipedia page. However, my code outputs 1649 for 11-by-11. The expected answer is 2,680.
I really have no idea why this would occur.
using namespace std;
class Board{
struct Position{
int r;
int c;
};
public:
int size;
vector<vector<int> > b;
Position pos;
vector<int> placements;
int count;
Board(int s){
size=s;
pos.r=0;
pos.c=0;
for(int i=0; i<s; i++){
b.push_back(vector<int>());
for(int j=0; j<s; j++){
b.at(i).push_back(0);
}
}
count=0;
}
bool hasQueens(){
for(int i=0; size-i>=0; i++){
if(b[pos.r][pos.c-i]==1){
return true;
}
if(pos.r-i >= 0){
if(b[pos.r-i][pos.c-i]==1){
return true;
}
}
if(pos.r+i < size){
if(b[pos.r+i][pos.c-i]==1){
return true;
}
}
}
return false;
}
void placeQueen(){
b[pos.r][pos.c]=1;
placements.push_back(pos.r);
}
void backtrack(){
pos.c--;
b[placements[pos.c]][pos.c]=0;
pos.r = placements[pos.c] +1;
placements.pop_back();
if(pos.r==size) backtrack();
}
bool canBacktrack(){
if(pos.c==1 && placements[0]==size-1) return false;
else return true;
}
void nextSol(){
while(pos.c!=size){ //while the board is not filled
if(pos.r==size && canBacktrack()){
backtrack();
} else if(pos.r==size && !canBacktrack()){
break;
}else if(!hasQueens()){
placeQueen();
pos.r=0;
pos.c++;
} else {
pos.r++;
}
}
}
void print(){
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
cout << b[i][j];
}
cout<<endl;
}
cout<<endl;
}
};
int main(){
Board board(11);
board.print();
while(true){
board.nextSol();
if(!board.canBacktrack()) break;
cout << ++board.count << endl;
board.backtrack();
}
}
Your code segfaults for me. Running it through valgrind says that there is invalid read in this line:
if(b[pos.r][pos.c-i]==1){
in function hasQueens(). And indeed, there are cases in which pos.c-i becomes negative: whenever pos.c is smaller than size.
The organization of the code is messy, I would suggest to write your boundaries out clearly instead of relying on stopping for col == 1 and r == size (which if access incorrectly can cause a segfault). Also, NQueen problem has an elegant solution with recursion, I would suggest to look into that as well.
I was able to make some changes to your program and got the expected answer for 11 x 11, however I think there are more bugs in the code. The problem lies in the backtrack() and placeQueen() function, pos.c is decremented without checking if it's greater than 0, so it can potentially go negative and crash when access. Most importantly you don't need to do push_back/pop_back on the placement vector since you know you only can place one queen on each column so it should really be fixed size. when placing queen, you can do placement[c] = r. Hope this helps.
I'm trying to design a matrix solving program in C++. When I call the function Ax_b() it's supposed to create an integer matrix out of strings and then print the output. This works when I call the function in the main, but when I have conditions on the function everything except the printing works.
Example:
void main(){
Ax_b(); //runs fine and prints output to console
}
but...
void main(){
int x;
while(true){
cout<<"What would you like to do?"<<endl<<endl;
cout<<"1. Solve Ax=b"<<endl;
cout<<"1. Reduce a matrix to REF"<<endl;
cout<<"2. Reduce a matrix to RREF"<<endl;
cout<<"3. Find the nullspace of a matrix"<<endl;
cout<<"4. Quit"<<endl<<endl;
cin>>x;
cout<<endl;
if(x == 1)
Ax_b(); //runs function but doesn't print matrix to console
else
exit(1);
}
}
Ax_b() looks like this:
void Ax_b(){
vector<string> strMatrix = storeStrings();
vector<vector<int>> matrix = parseMatrix(strMatrix);
printMatrix(matrix);
}
printMatrix:
void printMatrix(vector<vector<int>> matrix){
int mSize = matrix.size();
int vSize = matrix[0].size();
for(int i = 0; i < mSize; i++){
cout<<endl;
for(int j = 0; j < vSize; j++){
cout<<matrix[i][j]<<" ";
}
}
cout<<endl<<endl;
}
It seems so stupid but I can't figure out why this isn't working, any help is much appreciated.
We don't see at the point of posting this anwser the printMatrix function, possibly Your problem is there. remember that console is a stream, maybe You're missing a endl to force the flush.
I can't comment so...
Did you try printing something outside of the loops, but in the function?
Maybe if you did if (cond) with the {} something might change.
Look out for those loops! I once did a while (cond) with a ; before the {}. That was not fun. None of the code inside ran until I removed the ;.
I have a program with bool function issquare, which code don't need for you for my question. I have iterative variable T, which is response for how many times I will put squarsized's time string. But after first input of strings programs stop, at T=1, and don't go to next iteration. Why?
int main(){
int T;
std::string line;
std::cin>>T;
int squaresize;
int** arr=new int*[30];
for(int d=0; d<30; d++){
arr[d]=new int[30];
}
for(int i=0; i<T; i++){
for (int d=0; d<30; d++){
for(int d1=0; d<30; d++){
arr[d][d1]=0;
}
}
std::cin>>squaresize;
for(int j=0; i<squaresize; i++){
std::cin>>line;
for(int a=0; a<squaresize; a++){
if (line[a]=='#'){
arr[j][a]=1;
}
}
}
if (issquare(arr, squaresize)==true){
std::cout<<"Case #"<<i+1<<": YES";
}
else{
std::cout<<"Case #"<<i+1<<": NO";
}
std::cout<<T;
}
return 0;
}
Instead of
std::cin>>line;
Try
getline(std::cin, line);
operator>> doesn't read an entire line, only until the first whitespace.
Instead of j you are comparing and incrementing i, which is also used by the outer loop:
for(int j=0; i<squaresize; i++){
std::cin>>line;
for(int a=0; a<squaresize; a++){
if (line[a]=='#'){
arr[j][a]=1;
}
}
}
In the future (and with possibly more complex programs), learning how to use of a debugger can really help you to locate such bugs. Your problem was that the outmost loop executed less than T times:
for(int i=0; i<T; i++){
Since the value of T is constant, something must be modifying i inside the loop. An easy way to debug this would be using a debugger to find out where the variable is changed. In Visual Studio this can be done by breaking and adding a data breakpoint from Debug -> New Breakpoint -> New Data Breakpoint -> Address: &i
well ive been trying to edit the element of an array so lets assume that we have a 2d array
so
a 2d array 9 x 9;
for(... ... ... ++)
{
for(.. ... ...++){}
}
lets say that the code will use another set of for loops to display the 2d array its a simple array nothing fancy
00000000
00000000
00000000...
so if i wanted to to display an E from elements[1][0] to [2][3] how would i do that?
00000000
eeeeeeee
eeee0000
00000000
what i had in mind was something like while(x < y)
{ array[x++][y];}
but this idea doesnt seem to work.
would gladly take any help. thx
for(int i=0; i<9; i++) //This loops on the rows.
{
for(int j=0; j<9; j++) //This loops on the columns
{
board[i][j] = grid; // set the array to the char on grid '0'.
}
}
board[s_col][s_row] = 'Z';
while(s_col < e_col)//s_col is the start of the rows and columns
//{
//if(s_col != e_col)
{
++s_col;
board[s_col][s_row];
}
//}
//cout << board[s_col][s_row++] <<endl;
// display the array
for(int i=0; i<9; i++) //This loops on the rows.
{
for(int j=0; j<9; j++) //This loops on the columns
{
cout << board[i][j] << " ";
}
cout << endl;
}
You were on the right track with the approach:
for(... ... ... ++)
{
for(.. ... ...++){}
}
Here is some code that should help you:
#include <stdio.h>
#include <memory.h>
#define MAX_ROW 4
#define MAX_COL 8
void fillRange(char fillChar, int startRow, int startCol, int count);
char myArray[MAX_ROW][MAX_COL];
void printArray();
int main(int argc, char *argv[])
{
memset(myArray, '0', sizeof(myArray));
printf("\nBefore:\n");
printArray();
fillRange('e', 1, 0, 12);
printf("\nAfter:\n");
printArray();
}
void fillRange(char fillChar, int startRow, int startCol, int count)
{
int i, j, filledChars = 0;
for(i = startRow; i < MAX_ROW; i++)
{
for(j = startCol; j < MAX_COL; j++)
{
myArray[i][j] = fillChar;
if(++filledChars == count)
return;
}
}
}
void printArray()
{
int i, j;
for(i = 0; i < MAX_ROW; i++)
{
for(j = 0; j < MAX_COL; j++)
putchar(myArray[i][j]);
printf("\n");
}
}
If you instead wanted to end at a particular point in the array then you just need to change the condition that triggers the return.
This is one of the many reasons why the more coding you do the more you tend to avoid 2D arrays of the sort you have.
Instead you use a 1D array like this: board[i][j] == board_1D[i*num_columns+j]. That also means you can just iterate through the entire board in a single for loop.
Now you simply calculate the begin and end indices of your e range, and simply test if your counter is within that range. In other words, you have a single if statement inside your inner-most loop.
You can, of course, convert your i,j 2D indices into the equivalent 1D index and take the same approach. index_1D = i*9+j;
I'll leave the code to you.
Dealing with a sequence of adjacent values is easiest done when you have an underlying contiguous array and you don't need to deal with double indexing (see Adam's answer on that). However, in your simple case it also quite doable:
You'd initialize your row and column variables with the start row and column (in your case 0 and 1). You then walk with your column until you reached either the target column (2) and you are on the target row (3) or you reached the end of the matrix in which case you set the column to 0 and increment the row.
I want to make a program for solving a 3*3 sudoku puzzle. I have made a program but it is only working for 50% problems and for the rest it gives 60% right solution. I do not know how to solve it in a finite number of steps for every possible problem. The technique I have used is that I am searching every individual element of array and check which no does not exist in the same row and column and then I put it in that unit and move to the next. But this is not the solution for every problem. The next thing that come to mind was that we should have to write each and every possible number for a unit and then proceed. But how will we decide that which number we should finally put in the unit. I just want that how to write a solution that will work for every problem. I hope you got the point.
The code I have written is
#include<iostream>
using namespace std;
int rowsearch(int l[9][9],int row,int num) // function to search a particular number from a row of array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[row][c]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int colsearch(int l[9][9],int col,int num) // function to search a number from a column of an array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[c][col]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int rowcolnotexist(int x[9][9],int row , int col) // to find a nuber which does not exists int a row and column
{
for (int c=1 ; c<=9 ; c++)
{
if ( rowsearch(x,row,c)!=1 && colsearch(x,col,c)!=1)
return c;
}
return 0;
}
int main()
{
int l[9][9]={};
// input of the list
for (int i=0 ; i<9 ; i++)
for (int j=0 ; j<9 ; j++)
{
cout<<"Enter "<<i+1<<"*"<<j+1<<"entry of the list(For not entering a number enter 0).";
cin>>l[i][j];
}
// operations
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
if (l[i][j]==0)
l[i][j]=rowcolnotexist(l,i,j);
}
// printing list
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
{
cout<<l[i][j];
if ((j+1)%3==0)
cout<<" ";
else
cout<<" ";
}
if ((i+1)%3==0)
cout<<"\n\n\n";
else
cout<<"\n\n";
}
return 0;
}
I'd recommend the same algorithm I use when solving them myself ;-)
Choose an arbitrary square and list all the valid values for it, based on what is present in all the other rows (there's probably a way to make a more efficient decision about which square to start with).
Then move on to a related empty square (there's probably a way to make a more efficient decision about which square to check next) and store all its possible values.
Rinse and repeat until you find a square that has only one valid value.
Then unzip.
This should sounds like a recursive problem, by now. (note: almost anything that can be done recursively can be done conventionally, but the idea is the same).
So, store up a list of partially solved squares, and when you get to a square that's been solved completely, go back through your list in reverse order re-evaluating your partial solutions with the new data (namely, the one you WERE able to solve).
Rinse and repeat for full body and volume.