View Single Post
01-11-2013, 05:25 PM   PM User | #10
niralsoni
Regular Coder

Join Date: Mar 2008
Location: London
Posts: 152
Thanks: 4
Thanked 42 Times in 42 Posts
Is this one required solution ??

Hi,

I really found your requirement a kind of challenge. It took me around 3 hours to implement the required functionality.

Below is the random data generator which takes the child object count and layer count as input. And then randomly generates parent objects and assigns them to random number of child objects. This process is repeated upto nth layer.

And yes, it does not have the capabilities of traversing to and fro (like next, first, prev, last etc). But will try to implement them in future if this is the right solution.

Code:
```function generateData(objectCount, layerCount) {
var r = d = i = j = k = c = s = n = 0, pre = '', data = [[]];
c = objectCount;

for(i = 0; i < c; i++) {
data[n][i] = {};
data[n][i].cid = 'Obj' + (layerCount-n) + '' + (i+1);
data[n][i].pid = 'root';
}

for(n = 1; n < layerCount; n++) {
j = s = 0;
r = c;
c = Math.floor(Math.random()*c);
if(c == 0) c = 1;
data[n] = [];
for(d = n-1; d < n; d++) {
pre += 'P';
}

for(i = 0; i < c; i++) {
data[n][i] = {};
data[n][i].cid = pre + 'Obj' + (layerCount-n) + '' + (i+1);
data[n][i].pid = 'root';

if(j == r) continue;

s = Math.floor(Math.random()*(r-j));
if(s == 0) s = 1;
k = (j + s) >= r ? r : (j + s);

for(; j < k; j++) {
data[n-1][j].pid = data[n][i].cid;
}
}
if(j < r) {
data[n][c] = {};
data[n][c].cid = pre + 'Obj' + (layerCount-n) + '' + (i+1);
data[n][c].pid = 'root';

for(; j < r; j++) {
data[n-1][j].pid = data[n][c].cid;
}
c++;
}
}
return data;
}

function renderData(data) {
document.write('Output format is - Child Object : Parent Object <br><br>');
for(i = 0; i < data.length; i++) { // bottom-to-top print
//for(i = data.length-1; i >= 0; i--) { // top-to-bottom print
document.write('{')
for(j = 0; j < data[i].length; j++) {
if(data[i][j])
document.write(data[i][j].cid + ': ' + data[i][j].pid);
if(j+1 < data[i].length) {
document.write(', ');
}
}
document.write('}<br><br>');
}
}

renderData( generateData(10,3) );```
Check it out and tell me whether it suffice your requirement (partly) or not?

And for viewing it in action (using some sort of tree), I have attached a sample (randomTreeGenerator.htm). Check that also. (please note that this sample does not support Chrome. You might have to open it in IE or FF... Strange but true.)

Regards,
Niral Soni
Attached Files
 RandomTreeGenerator.zip (10.3 KB, 21 views)

Last edited by niralsoni; 01-11-2013 at 05:39 PM.. Reason: code explained

 Users who have thanked niralsoni for this post: CoolCaptain (01-11-2013)