Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Sparse Array !

Hello ..
I've tried to solve this prob. but I could not :(

Assume that you have a doubly dimention sparse array A[6][6]
List is a class represinting the value A[i][j], if different to zero ..

Let list *row[6] be an array of pointers such that :
row[k] is a pointer on the first element of the list of elemints different to zero in the row k of the matrix A ..

And this is my trial ..

# include<iostream.h>

class node{
public :
int data;
int i,j;
node *next;
node(){ next=0; }
node( int d,int i,int j,node *p)
{
data=d;
i=i;
j=j;
next=p;
}

};

/////////////////////////////

class list{
public :
list(){ head=tail=0; }

int isempty(){
if(head==0)
return 1;
else
return 0;
}

void addtotail(int,int,int);

void print()const;

int size();

private:
node *head,*tail;

};

void list::addtotail(int d,int i,int j)
{
if(tail!=0)
{
tail->next=new node(d,i,j,0);
tail=tail->next;
}
else
head=tail=new node(d,i,j,0);
}

void list::print() const
{
for(node *q=head;q!=0;q=q->next)
cout<<q->data<<"["<<q->i<<"]"<<"["<<q->j<<"]"<<" ";
cout<<endl;
cout<<endl;
}

//////////////////////

int list::size(){
int c=0;
for(node* p=head;p!=0;p=p->next)
c++;
return c;

}

////////////////////////////////

void main()
{
int a[6][6];
for(int i=1;i<6;i++)
{
for(int j=1;j<6;j++)
a[i][j]=1;
}

a[1][1]=0;
a[2][2]=0;
a[2][3]=0;
a[3][5]=0;
a[4][4]=0;

for(int k=1;k<6;k++)
{
for(int l=1;l<6;l++)
cout<<a[k][l]<<" ";
cout<<endl;
}

list *l[6];
for(int z=1;z<6;z++){
for(int q=1;q<6;q++)
{
if(a[z][q]!=0)
l[z]->addtotail(a[z][q],z,q);

}
l[z]->print();
}

}
[2142 byte] By [Qatar] at [2007-11-11 7:19:40]
# 1 Re: Sparse Array !
Plese Help :(
Qatar at 2007-11-11 21:02:28 >
# 2 Re: Sparse Array !
...
for(int z=1;z<6;z++){ l[z] = new list();
...
this is required, but i didnt test rest of it
mr1yh1 at 2007-11-11 21:03:28 >
# 3 Re: Sparse Array !
Well ..

I did it .. But it seems that there is an error in printing !! od in adding to tail

this is the result .. But is totally wrong ..

http://www.qatarp.com/files/9/aqqqqqqqqqq.GIF
Qatar at 2007-11-11 21:04:27 >
# 4 Re: Sparse Array !
node( int d,int i,int j,node *p)
{
data=d;
i=i; // problem
j=j; // problem
next=p;
}
there is a problem in your code,
i and j are local variables not member variables in that scope.
so your node's i and j are not initalised, they are randomise.
change parameter names or member variable's names
mr1yh1 at 2007-11-11 21:05:33 >
# 5 Re: Sparse Array !
Thank You Soooo Much :D

it is working now =)
Qatar at 2007-11-11 21:06:33 >