Since the complexity of the random number generator module is not given, I
don't think its a good idea to repeatedly call the function. Instead we can
try,
int sum = n*(n+1)/2;
int result = rand(sum);
int sub = n-1;
do
{
if(result<=n && result>0)
return result;
else
{
result = result - sub;
sub--;
}
}while(sub>0);
Let me try to explain my approach with an example. Let n be 6. sum=21;
01 02 03 04 05 06
07 08 09 10 11
12 13 14 15
16 17 18
19 20
21
Identify to which column "result" belongs and return it. The do while loop
determines the column number. The difference between subsequent row elements
are in Arithmetic Progression, starting from -(n-1) to -1 or till the column
number has been calculated..
If there is any fault/drawback in the procedure, please let me know....
@Piyush: Can you explain the solution you posted initially.
B.Prabhat Kiran
CS08B014
4th Year UnderGrad
Comp Sci & Engg
IIT-Madras
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.