This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have tried to solve an algorithm problem, I'm newbie and I'm trying to practice a lot in programming problems. So I wanted to construct an Identity matrix n*n. I came up with a stupid solution, that worked for a 4*4 matrix, but it didn't work with 5*5. I know that its weird solution and the solution to the problem is really easy when I looked at it. I need to know what did I do wrong so that I can learn, and is my solution is really stupid and I will be better in the future after working much in solving those kind of problems ?
#include <iostream>
#include <vector>
#include <sstream>
#include <iomanip> // for setw, setfill
using namespace std;
int binary(int number);
int main()
{
vector<vector<int> > matrix;
cout<<"Please enter the size of the identity matrix"<<endl;
int n;
cin>>n;
matrix.resize(n);
for (int i=0; i<n;i++)
{
matrix[i].resize(n);
}
int steps = 1<<n-1;
int bin = binary(steps);
ostringstream binString;
binString <<bin;
if(binString.str().size()<n)
{
std::string dest = binString.str();
int nPaddings = n-binString.str().size();
if (nPaddings==0) nPaddings=1;
dest = std::string( nPaddings, '0').append( binString.str());
binString.str("");
binString<<dest;
}
for (int col = 0; col<n; col++)
{
if(col>=1)
{
steps= (int)steps/2;
int bin = binary(steps);
binString.str("");
binString << bin;
if(binString.str().size()<n)
{
std::string dest = binString.str();
int nPaddings = n-steps;
if (nPaddings==0) nPaddings=1;
dest = std::string( nPaddings, '0').append( binString.str());
binString.str("");
binString<<dest;
}
}
for (int row=0; row<n; row++)
{
matrix[col][row] =binString.str().at(row)-'0';
}
}
return 0;
}
int binary(int number) {
long rem,i=1,sum=0;
do
{
rem=number%2;
sum=sum + (i*rem);
number=number/2;
i=i*10;
}while(number>0);
return sum;
}
There is a much simpler way to do it.
First, you should allocate your matrix with the specified size. Then, you know that only the diagonal is 1s:
vector<vector<int> > matrix;
int n;
cout << "Please enter the size of the identity matrix" << endl;
cin >> n;
// Initialize the matrix as a n x n array of 0.
matrix = vector<vector<int> >(n, vector<int>(n,0));
// Set the diagonal to be 1s
for(unsigned int t = 0; t < n; t++)
matrix[t][t] = 1;
You can see a live example here.
Edit:
Your error comes from this line:
int nPaddings = n-steps;
In fact, you're not using the size of dest to compute the padding, which is not correct. See here, I added some debug printfs to see the state of the variables. You can see that nPaddings == -3, hence the errors.
The idea you have:
for each column
get the representation of the column as a string
set the i-th value of the column as the i-th character of the string
So, here is a simpler program using your idea. Separating the code in several functions helps a lot. Also, std::ostringstream and std::string is just pure overkill here.
#include <iostream>
#include <vector>
#include <iomanip> // for setw, setfill
using namespace std;
std::string binStr(unsigned int exponent, unsigned int size);
int main()
{
vector<vector<int> > matrix;
cout<<"Please enter the size of the identity matrix"<<endl;
int n;
cin>>n;
// Initialize the matrix
matrix.resize(n);
for (int i=0; i<n;i++)
matrix[i].resize(n);
// Fill the matrix
for (int col = 0; col<n; col++)
{
std::string bin = binStr(n-col,n);
for (int row=0; row<n; row++)
matrix[col][row] = bin[row]-'0';
}
// Print the matrix and return
for(unsigned int y = 0; y < n; y++)
{
for(unsigned int x = 0; x < n; x++)
cout << "\t" << matrix[y][x];
cout << "\n";
}
return 0;
}
std::string binStr(unsigned int exponent, unsigned int size)
{
// You do not need a string stream (which is like using a bazooka to kill a fly...)
// Instead, just create a string of the required length
// 'str' will contain the binary representation of 2^exponent
std::string str(size,'0');
if(exponent <= size && exponent > 0)
str[size - exponent] = '1';
return str;
}
You can see it in action here.
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > make_idty_matrix( int n )
{
vector<vector<int> > idty( n, vector<int>( n, 0 ));
for( int i = 0; i < n; ++i )
idty[i][i] = 1;
return idty;
}
int main()
{
vector<vector<int> > matrix = make_idty_matrix( 5 );
// your code here
// ...
return 0;
}
Related
This question already has answers here:
Declare large array on Stack
(4 answers)
Closed 9 months ago.
I am programming for simple matrices multiplication. However, for large values of matrix size, I faced with matrix overflow error. Could someone help me with this.
here the code!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int r,c;
cout<<"Rows: ";
cin>>r; // 5000
cout<<"Clumns: ";
cin>>c; // 5000
int m[r][c];
for (int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
m[i][j]=i+j;
cout<<setw(4)<<m[i][j];
}
cout<<endl;
}
}
I ran your program with different sizes. And the problem is simply that the array is too big. It works with smaller array sizes, but you can only put so much onto the stack.
So I did this:
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix {
public:
Matrix(int r, int c)
: rows(r), cols(c)
{
m = new int *[rows];
for (int index = 0; index < rows; ++index) {
m[index] = new int[cols];
}
}
int & at(int r, int c) {
return m[r][c];
};
int rows = 0;
int cols = 0;
int ** m = nullptr;
};
int main(int argc, char **argv)
{
int r = atoi(argv[1]);
int c = atoi(argv[2]);
Matrix m(r, c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
m.at(i, j) = i+j;
cout << setw(4) << m.at(i, j);
}
cout<<endl;
}
}
And that appears to work. Now, there are some things in here that are bad. I didn't write a destructor, so there's a memory leak. And I didn't do any range checking in the at() method. I was only showing what you could do for very large arrays.
Now, I'm going to beg you... PLEASE put white space in your code. You're going to have no end of errors when you shove everything together the way you do. Notice my for-loops have a lot more space than you do. I didn't fix everywhere, but the coding policy where I work is to include white space for readability. Walls of numbers and operators can be very, very hard to read.
Also, name your variables something longer than a single character.
Both these changes will dramatically reduce future bugs.
So, I need to make a function that is going to return the chromatic number of a graph. The graph is given through an adjecency matrix that the function finds using a file name. I have a function that should in theory work and which the compiler is throwing no issues for, yet when I run it, it simply prints out an empty line and ends the program.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int Find_Chromatic_Number (vector <vector <int>> matg, int matc[], int n) {
if (n == 0) {
return 0;
}
int result, i, j;
result = 0;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (matg[i][j] == 1) {
if (matc[i] == matc[j]) {
matc[j]++;
}
}
}
}
for (i = 0; i < n; i++) {
if (result < matc[i]) {
result = matc[i];
}
}
return result;
}
int main() {
string file;
int n, i, j, m;
cout << "unesite ime datoteke: " << endl;
cin >> file;
ifstream reader;
reader.open(file.c_str());
reader >> n;
vector<vector<int>> matg(n, vector<int>(0));
int matc[n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
reader >> matg[i][j];
}
matc[i] = 1;
}
int result = Find_Chromatic_Number(matg, matc, n);
cout << result << endl;
return 0;
}
The program is supposed to use an freader to convert the file into a 2D vector which represents the adjecency matrix (matg). I also made an array (matc) which represents the value of each vertice, with different numbers corresponding to different colors.
The function should go through the vector and every time there is an edge between two vertices it should check if their color value in matc is the same. If it is, it ups the second vale (j) by one. After the function has passed through the vector, the matc array should contain n different number with the highest number being the chromatic number I am looking for.
I hope I have explained enough of what I am trying to accomplish, if not just ask and I will add any further explanations.
Try to make it like that.
Don't choose a size for your vector
vector<vector<int> > matg;
And instead of using reader >> matg[i][j];
use:
int tmp;
reader >> tmp;
matg[i].push_back(tmp);
I am a new in C++ and have difficulties in importing specific data (numbers) from the file.
My input looks like:
Open High Low Close
1.11476 1.11709 1.10426 1.10533
1.10532 1.11212 1.10321 1.10836
1.10834 1.11177 1.10649 1.11139
1.09946 1.10955 1.09691 1.10556
1.10757 1.11254 1.09914 1.10361
1.10359 1.12162 1.10301 1.11595
1.09995 1.10851 1.09652 1.10097
I use the following code which works fine for me to read the second column entirely, however I need to read specific data only. For example the third row/ third column which is 1.10649How can I read specific data? Do I need to use the string to get the row/column and then convert it to int in order to read it in a vector? I am open for any suggestions and would be greatly appreciated if any could help me with this issue.
// Data import 2nd Column
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
const int columns = 4;
vector< vector <double> > data;
ifstream market_data("market_data.txt");
if (market_data.is_open()) {
double num;
vector <double> line;
while (market_data >> num) {
line.push_back(num);
if (line.size() == columns) {
data.push_back(line);
line.clear();
}
}
}
vector <double> column;
double col = 2;
for (double i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
system ("pause");
return 0;
}
You need to use a integer value for indexing (size_t to be precise), change
for (double i = 0; i < data.size(); ++i) {
to
for( size_t i = 0; i < data.size(); ++i) {
// ^^^^^^
Otherwise everything seems fine from your code sample.
If your numbers will always contain 7 characters (i assume it's not binary file), then you could make this simple.
Use seekg() method of ifstream.
Each number fills 10 characters (7 of number, 3 spaces). So, if you have table ROWS x COLUMNS, then to get specific number, you can do this:
const int ROW_LEN = 4
const int DATA_LEN = 10
...
int row,column;
double num;
std::cin >> row; //assume first row is 0
std::cin >> column //assume first column is 0
marked_data.seekg((column*ROW_LEN + row)*DATA_LEN);
marked_data >> num // here is your number
Thank you for replies.. I have solved the issue. So instead of:
vector <double> column;
double col = 2;
for (double i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
enough to write:
cout << data[2][2] << endl;
I've just solved a problem on SPOJ, I do DFS and use STL stack instead of recursive, I got TLE. Then i use array stack instead of STL stack and got Accepted.
The problem is : Give an n*n table, each square have a number. First, you can start at any square, choose a number K.Then you can go to squares that have a common edge with the square you stand, and abs( number on that square - number on the square you stand) == K. What is the biggest area that you can go ?
This is my solution :
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <utility>
#include <cmath>
#include <cstring>
#include <stack>
using namespace std;
#define maxn 1010
int n, a[maxn][maxn],visited[maxn][maxn], direction[5][3],cnt,anscnt,dd[1000010],dc[1000010],k[1000010];
bool Free[maxn][maxn][5];
/*void visit(int d,int c,int dif) {
stack<int> dd,dc,k;
dd.push(d);
dc.push(c);
k.push(1);
visited[d][c]=dif;
cnt = 0;
while (!dd.empty()) {
int ud = dd.top(), uc = dc.top() , i = k.top();
k.pop();
for (;i<=4;i++)
if (Free[ud][uc][i]) {
int vd = ud+direction[i][1], vc = uc + direction[i][2];
if ((vd==0) or (vc==0) or (vd>n) or (vc>n)) continue;
if ((visited[vd][vc]==dif) or (abs(a[vd][vc]-a[ud][uc])!=dif)) continue;
if (Free[vd][vc][5-i]==false) continue;
visited[vd][vc]=dif;
Free[vd][vc][5-i]=false;
Free[ud][uc][i]=false;
k.push(i+1);
dd.push(vd);
dc.push(vc);
k.push(1);
break;
}
if (i==5) {
cnt++;
cout << ud << ' ' << uc << ' ' << dd.top() << ' ' << dc.top() << ' ' << dd.size() << '\n';
dd.pop(); dc.pop();
}
}
if (cnt > anscnt) {anscnt = cnt;}
} */
void visit(int d,int c,int dif) {
int topdd=0, topdc=0, topk=0;
dd[++topdd]=d;
dc[++topdc]=c;
k[++topk]=1;
visited[d][c]=dif;
cnt = 0;
while (topdd>0) {
int ud = dd[topdd], uc = dc[topdc] , i = k[topk];
topk--;
for (;i<=4;i++)
if (Free[ud][uc][i]) {
int vd = ud+direction[i][1], vc = uc + direction[i][2];
if ((vd==0) or (vc==0) or (vd>n) or (vc>n)) continue;
if ((visited[vd][vc]==dif) or (abs(a[vd][vc]-a[ud][uc])!=dif)) continue;
if (Free[vd][vc][5-i]==false) continue;
visited[vd][vc]=dif;
Free[vd][vc][5-i]=false;
Free[ud][uc][i]=false;
k[++topk]=(i+1);
dd[++topdd]=(vd);
dc[++topdc]=(vc);
k[++topk]=(1);
break;
}
if (i==5) {
cnt++;
topdd--; topdc--;
}
}
if (cnt > anscnt) {anscnt = cnt;}
}
int main()
{
std::ios_base::sync_with_stdio(false);
anscnt = 1;
direction[1][1] = -1; direction[1][2] = 0;
direction[2][1] = 0; direction[2][2] = 1;
direction[3][1] = 0; direction[3][2] = -1;
direction[4][1] = 1; direction[4][2] = 0;
cin >> n;
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++) cin >> a[i][j];
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++) visited[i][j]=-1;
memset(Free,true,sizeof(Free));
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++) {
if (i>1) visit(i,j,abs(a[i][j]-a[i-1][j]));
if (j<n) visit(i,j,abs(a[i][j]-a[i][j+1]));
if (j>1) visit(i,j,abs(a[i][j]-a[i][j-1]));
if (i<n) visit(i,j,abs(a[i][j]-a[i+1][j]));
}
cout << anscnt;
}
http://ideone.com/Hn6Dl4
When n = 1000, and all square in table = 0, STL stack is more than 2s and array stack is less than 1s.
So i think STL implementation of stack is slower than implementing stack by array. Queue, deque also can be implemented by array too.
Why is STL implementation slower and should i implement them by array to improve performane ?
As usual you should always use direct memory access (like arrays) in simple cases or implement your own data structure for complex cases for better perfomance. Std containers have checks, inderections and throw exceptions that decrease memory access perfomance. Moreover in your algorithm in 'stack' version you use methods to increase/decrease stack size, that can (but not must) cause large amout of memory allocation/deallocation that also leads to perfomance issues.
I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};