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 ;.
Related
I have two solutions for this problem, but which is one is optimal?
A list of N numbers is given. The player has to arrange the numbers so that all the odd numbers of the list come after the even numbers. Write an algorithm to arrange the given list such that all the odd numbers of the list come after the even numbers.
Input
The first line of the input consists of an integer numbers, representing the size of the list(N).
The second line of the input consists of N space-separated integers representing the values of the list
Output
Print N space-separated integers such that all the odd numbers of the list come after the even numbers
Example
Sample Input
8
10 98 3 33 12 22 21 11
Sample Output
10 98 12 22 3 33 21 11
Solution no1-
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
int p1=0, p2= n-1;
while(p1 < p2){
while(a[p1]%2 == 0 and p1<p2)
p1++;
while(a[p2]%2 != 0 and p1<p2)
p2--;
if(p1 < p2){
swap(a[p1], a[p2]);
p1++;
p2--;
}
}
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
return 0;
}
solution 2-
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]%2==0)
cout<<arr[i]<<" ";
}
for(int i=0;i<n;i++){
if(arr[i]%2!=0)
cout<<arr[i]<<" ";
}
return 0;
}
I would make a few changes, but mostly follow the second example.
First, I would put in an if-statement to ensure that n is a positive number. That's just a good check to do.
Next, I wouldn't output them quite like this. I'd build a second array instead.
int inputArray[n];
int finalArray[n];
int outputIndex = 0;
... Fill inputArray like you currently fill array
for (int i = 0; i < n; ++i) {
if (inputArray[i] % 2 == 0) {
outputArray[outputIndex++] = inputArray[i];
}
}
Do the second loop the same way. Then dump the outputArray.
Now, some other notes. These are stylistic, but will help you. Please use more whitespace in your code. Notice my code has spaces between operators. You're clearly young with young eyes, but good habits now will matter when you have to share code with old farts. Your scrunched-together code is really quite difficult to read and can readily hide errors. You wouldn't believe how many bugs are in code because some programmer was afraid of spaces.
Second, many programmers will tell you that optional braces shouldn't be treated as optional. Notice my if-statement has a pair of braces whereas yours don't. And if you look at how your code was formatted, you'll see that your indentation is wrong. You didn't indent your cout lines properly. This is a way errors hide. If you always use braces, evne when the language thinks they're optional, you'll have fewer bugs.
Lastly, most people will suggest you stop using fixed-length arrays and instead use vector, but as you're a new programmer, maybe you're not ready for that.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int* arr = new int[n];
int* odd = new int[n];
int* even = new int[n];
int oddIndex = 0;
int evenIndex = 0;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]%2==0)
even[evenIndex++] = arr[i];
else
odd[oddIndex++] = arr[i];
}
for(int i=0;i<evenIndex;i++){
cout<<even[i]<<" ";
}
for(int i=0;i<oddIndex;i++){
cout<<odd[i]<<" ";
}
return 0;
}
In c++, I wrote a code for 2d array to add each row-wise elements. But I don't understand why I got sum=3 in row 5 and 6 where I would get the sum = 2 instead of 3.but in my code others row gave the correct results. I don't know where is the problem?
#include<iostream>
using namespace std;
int main(){
int a[8][4]={{1,1,0,0},{0,1,0,0},{0,0,0,0},{0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,1,0},{0,0,1,0}};
for(int i=0;i<8;i++){
for(int j=0;j<4;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
int a_row[4]={0};
cout<<endl;
for(int i=0;i<8;i++)
{
for(int j=0;j<4;j++)
{
a_row[i]=a_row[i]+a[i][j];
}
cout<<"Row"<<i+1<<": "<<a_row[i]<<endl;
}
return 0;
}
and the output i got-
Look how big a_row is
int a_row[4]={0};
Now look how big i is
for(int i=0;i<8;i++)
Now look how you use a_row and i
a_row[i]=a_row[i]+a[i][j];
See the problem?
Actually there's no need to a_row to be an array at all. A simple int variable would work just as well. You don't always have to use an array just because you have a loop.
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 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.
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;
}