Reading Matrix Market file C++ issues - c++

I'm trying to read and use a matrix market file, but my current attempts haven't produced anything. I'm extremely new to C++ so be gentle. Here's what I've got so far:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream f("GX30.mtx");
int m,n,l;
while(f.peek()=='%') f.ignore(2048, '\n');
f>>m>>n>>l;
cout<<l;
int I[m],J[n],val[l];
int mat[m][n];
for(int i=1;i<=l;i++)
{
f>>I[i]>>J[i]>>val[i];
}
for(int k=1; k<=l;k++)
{
mat[I[k]][J[k]]=val[k];
cout<<"test";
}}
My test output produces nothing, and none of the variables determining the matrix parameters initialize properly. The first few lines from the file I'm reading from are as follows:
%%MatrixMarket matrix coordinate integer general
%% X {5,5} [[30,8,3]] [ (b*a^-1)^3 ]
12 30 60
1 1 1
1 3 1
1 4 1
The first line not proceeded by % indicates the number of rows, then columns, then lastly the number of non zero entries (I think)
Then the following lines index the row and column position of each entry, with its corresponding value.

There are few issues you need to fix.
The main problem is how you access arrays. Array index starts from 0, not 1. Array sizes are different in your application too.
I[m],J[n],val[l];
m, n, l are not equal so you go beyond boundaries of two arrays:
for(int i=1;i<=l;i++)
for(int k=1; k<=l;k++)
You code most likely causes an access violation and crashes, hence you don't even see the result of cout<<l; operation.
You shouldn't access all array from a single loop like you do. Something like the following is alright.
for (int i = 0; i < l; ++i)
{
val[i] ... // val array, not I or J here
}
Also, Matrix Market allows for float values but you are using integers.
Yet another thing: Lines may be separated by "\r", "\n" and "\r\n" but you expect '\n'. Does Matrix Market format specify anything or it relies on OS conventions? If lines are separated with '\r' then your code may not work:
while(f.peek()=='%') f.ignore(2048, '\n');

Related

Can' t print position of element in an array after heapify-up C++

Can someone help me with the code in c++ below?
#include <iostream>
#include <fstream>
using namespace std;
int PARENT(int i)
{
return (i/2);
}
int Heapify_up(int arra[], int i)
{
int j,k;
if (i>1){
j = PARENT(i);
if (arra[i]<arra[j]){
k=arra[i];
arra[i]=arra[j];
arra[j]=k;
Heapify_up(arra, j);
}
}
return j;
}
int main()
{
int array3[15];
int i,p,array_length;
ifstream inputFile1("Heapfile.txt");
if (inputFile1.good()){
int current_number = 0;
i=1;
while (inputFile1>> current_number)
array3[i++] = current_number;
inputFile1.close();
}
array_length = i;
cout<<"Please, enter an integer: ";
cin>>p;
array3[array_length+1]=p;
int pos=Heapify_up(array3, array_length+1);
for (i=1; i<15; i++){
cout<<array3[i]<<" ";
}
cout<<"The position is "<<pos;
}
Let me explain you that have an array in a txt file. After i insert a random integer and with the heapify-up algorith I'm sorting this random number to the array. I want to print the new sorted array(I' have done that) and the new position of the random element that i have entered. Any idea?
thanks in advance!
P.S. I am new here and i find it somehow difficult to post my code correctly... still learning! XD
Okay, there are multiple problems with your code.
You make no effort to ensure you don't blow past the size of your
static array.
You skip a spot in the array when appending your manually-added
value
Your array length is wrong
You aren't initializing your variables
Let's start with the last one. Please do something like this:
int i{0}, p, array_length;
This ensures the i variable is properly initialized to zero.
Next, your code does this:
array3[i++] = current_number;
This means that at any given time, i is the length of the array.
But later you do this:
array_length = i;
array3[array_length+1]=p;
Frankly, I would drop variable i entirely and use array_length instead. There is no need for both.
But even without that, you're setting array_length correctly, but then you're inserting to a point AFTER that, so you might start with:
[ 1, 2, 3, 4, 5 ]
At this point, i == 5. Input a 6 and have:
[ 1, 2, 3, 4, 5, 0, 6 ]
Because you put it at index i+1 not at index i.
At this point, array_length is no longer an accurate length. But you do this:
int pos=Heapify_up(array3, array_length+1);
So it kind of works.
I don't know why Heapify_up is returning j -- it's just the midpoint of the array. That's not a useful value.
Furthermore, I don't really know what your heapify thing is trying to accomplish.. It certainly isn't a heap-sort. If the middle and end numbers are in sorted order, it doesn't actually do a thing.
This URL might help you with some code:
Heap sort at Geeks for Geeks
As for using a fix-length array -- that's problematic, too, but using std::vector is probably a bit much for you. I'd make sure that your input loop doesn't run into issues or start with a much longer beginning array.

using while loop for determining square roots of numbers c++

I am running a c++ program, using while loop for determining square roots of numbers, here i have defined variables, tried but nothings seems to work for me, any hand would be great to assist me.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n=10, N=0, i=0;
while(i<5)
N=i*n;
cout<<"numbers ="<<"\t Square root="<<sqrt(N)<<endl;
return 0;
}
The program execute successfully but nothing display (emptyb line). thanks.
while(i<5)
N=i*n;
Because you didn't indent or use brackets, you may have missed this and is equal to:
while (i < 5) {
N = i * n;
}
because the language specifies that no brackets means you just apply it to the next statement only and keep looping on that.
So this just loops forever as i never grows beyond 5 to exit the loop.
Just add fancy brackets to your loop and check where you want to change i and n.

Why my program is failing for large input? more than 10^5

I am learning dynamic programming.i'm trying to solve the following question :
Problem Introduction :
You are given a primitive calculator that can perform the following three operations with the current number
x: multiply x by 2, multiply x by 3, or add 1 to x. Your goal is given a positive integer n, find the minimum number of operations needed to obtain the number n starting from the number 1.
Task
Given an integer n, compute the minimum number of operations needed to obtain the number n
starting from the number 1.
The input consists of a single integer 1 < n < 10^6.
code
#include <iostream>
#include <climits>
#include<vector>
#include<list>
void primitive_calculator(int number)
{
std::vector<int> min_steps(number+1,INT_MAX);
std::list<int> path[number+1];
min_steps[0]=0; min_steps[1]=0;
path[0].push_back(0);
path[1].push_back(1);
for (int i=2 ; i<=number ; i++)
{
if(i%3==0)
{
if(min_steps[i/3] < min_steps[i])
{
min_steps[i]=min_steps[i/3]+1;
path[i]=path[i/3];
path[i].push_back(i);
}
}
if(i%2==0)
{
if( min_steps[i/2] < min_steps[i])
{
min_steps[i]=min_steps[i/2]+1;
path[i]=path[i/2];
path[i].push_back(i);
}
}
if( min_steps[i-1] < min_steps[i])
{
min_steps[i]=min_steps[i-1]+1;
path[i]=path[i-1];
path[i].push_back(i);
}
}
std::cout<<min_steps[number]<<"\n";
while(!path[number].empty())
{
std::cout<<path[number].front()<<" ";
path[number].pop_front();
}
}
int main()
{
int number;
std::cin>>number;
primitive_calculator(number);
return 0;
}
This program is failing for input number greater than 10^5 .Why so?
And how can i improve the code?
Your issue is on line:
std::list<int> path[number+1];
It creates an array of std::list variable on stack, so if the number is huge, the stack overflows and gets segment fault.
This code gets warning from GCC:
warning: ISO C++ forbids variable length array 'path' [-Wvla]
It is rejected by clang as well:
error: variable length array of non-POD element type 'std::list'
So do NOT define huge variables on stack.
Instead, what you should do is use std::vector, e.g. change the line to:
std::vector<std::list<int>> path(number+1);
Then your problem is solved.

getting TLE from mouse maze in c++

I keep getting TLE in this question.I have tried to use scanf printf instead of cin cout but it didnt work.Then,I tried another question which has same
description,the only different is input N which means test case change from 1000 to 10^6.However, I got all AC there.I just cant figure out why.
following is the question
Description
Write a program that simulates a mouse in a maze. The program must count the steps taken by the mouse from the starting point to the final point.
The maze type is shown in following figure:
S$###
$$#$$
$$$##
##$$F
it consists of S (starting point), #(walls), $(road) and F (final point).
In above case, it needs 7 steps from S to F as following figure,
S$###
$$#$$
$$$##
##$$F
and the mouse can move in the four directions: up, down, left, right. There may be more than one way to reach final point, the program only need to print the least steps.
If there is no way from S to F, then print -1.
Input
The first line has an integer N(1<=N<=1000), which means the number of test cases.
For each case, the first line has two integers. The first and second integers R and C (3<=R, C<=500) represent the numbers of rows and columns of the maze, respectively. The total number of elements in the maze is thus R x C.
The following R lines, each containing C characters, specify the elements of the maze.
Output
Print out the least steps for each case, and there is a new line character at the end of each line.
Sample Input
3
4 5
S$###
$$#$$
$$$##
##$$F
4 5
S$$##
#$$$#
#$#$#
#$$$F
4 5
##S$#
$##$$
$$$##
#F###
Sample Output
7
7
-1
following is my code
#include <iostream>
#include <climits>
using namespace std;
int least_step;
void maze(char a[501][501],int,int,int,int,int);
#define wall '#'
int main(){
int ncase;
cin>>ncase;
char a[501][501];
while(ncase--){
int num1,num2;
cin>>num1>>num2;
least_step = INT_MAX;
int si,sj;
for(int i=0;i<num1;i++){
for(int j=0;j<num2;j++){
cin >> a[i][j];
if(a[i][j]=='S'){
si = i;
sj = j;
}
}
}
maze(a,si,sj,num1,num2,0);
if(least_step==INT_MAX){
least_step = -1;
}
cout<<least_step<<endl;
}
return 0;
}
void maze(char a[501][501],int i,int j,int num1,int num2,int step){
if(a[i][j] == 'F'){
if(step<least_step){
least_step = step;
}
return;
}
a[i][j] = wall;
if(i+1<num1&&a[i+1][j] != wall){
maze(a,i+1,j,num1,num2,step+1);
}
if(j+1<num2&&a[i][j+1] != wall){
maze(a,i,j+1,num1,num2,step+1);
}
if(i-1>=0&&a[i-1][j] != wall){
maze(a,i-1,j,num1,num2,step+1);
}
if(j-1>=0&&a[i][j-1] != wall){
maze(a,i,j-1,num1,num2,step+1);
}
a[i][j] = '$';
return;
}

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;