2017.11.9.23:09
Incremental Algorithm Implementation for sparse array utilities.
Basic Data Structure
public struct Index{
public int i, j;
public Index(int i, int j){
this.i = i;
this.j = j;
}
}
public struct Entry{
public Index ind;
public double v;
public Entry(int i, int j){
this.ind = new Index(i,j);
this.v = 0;
}
public Entry(int i, int j, double v):this(i,j){
this.v = v;
}
}
public struct SArray{
public int m, n, num;
public List<Entry> sa;
public SArray(int row=10, int col=10){
this.m = row;
this.n = col;
this.num = 0;
this.sa = new List<Entry>();
}
public SArray(int row, int col, int number, int max):this(row, col){
this.num = number;
Random rd = new Random();
List<Index> inds = new List<Index>();
int w = 0;
while(w < number){
Index temp = new Index(rd.Next(number),rd.Next(number));
if(inds.Contains(temp)){
continue;
}
else{
inds.Add(temp);
w++;
}
}
for(int k = 0; k<number; k++){
Entry et = new Entry(inds[k].i,inds[k].j,rd.Next(max)+rd.NextDouble());
sa.Add(et);
}
}
}
Here Index struct is used to index the non-zero entry of the array;
Entry is used to hold the index and value of the entry;
SArray is used to hold all the entries with the number of rows, columns, non-zero entries and the maximum value randomly generated.
Attention:
1. To use generic List avoids the boxing and unboxing of ArrayList.
2. Constructor of SArray creates a list of indices first, in turn used to create entries.
Sparse Array Multiply Method
public static SArray SparseArrayMul(SArray a, SArray b){
if(a.n!=b.m){
WriteLine("Row number in a is NOT equal to column number in b!");
}
SArray result = new SArray(a.m,b.n);
foreach(Entry ea in a.sa){
foreach(Entry eb in b.sa){
if(ea.ind.j==eb.ind.i){
result.sa.Add(new Entry(ea.ind.i,eb.ind.j,ea.v*eb.v));
result.num++;
}
}
}
//SparseArrayPres(result);
Shrink(ref result);
//SparseArrayPres(result);
return result;
}
Attention:
1. Idea is to multiply the necessary operands for later sum operation.
2. Has to sum up with another round of loops.
Facilities
public static bool SparseArrayPres(SArray a){
WriteLine($"SArray {a.GetHashCode()} has {a.num} entries:");
WriteLine("Row\t\t Col\t\t Val");
foreach(Entry e in a.sa){
WriteLine($"{e.ind.i}\t\t {e.ind.j}\t\t {e.v}");
}
return true;
}
public static bool Shrink(ref SArray a){
//Index ti = new Index();
List<Entry> result = new List<Entry>();
for(int i=0;i<a.num;i++){
Entry et = a.sa[i];
for(int j=i+1;j<a.num;j++){
if(a.sa[i].ind.i==a.sa[j].ind.i&&a.sa[i].ind.j==a.sa[j].ind.j){
et.v+=a.sa[j].v;
a.num--;
a.sa.RemoveAt(j);
WriteLine($"Shrinked for entry ({a.sa[i].ind.i},{a.sa[i].ind.j}).");
}
}
result.Add(et);
}
a.sa = result;
//SparseArrayPres(a);
return true;
}
Attention:
1. Pres is for display.
2. Shrink is for sum the value of the result array.