Thursday, April 8, 2010

Generate random numbers who's sum is a pre-determined

Here We want to generate a 9 digit unique no that is divisible by 9 or multiple of 9
here starting no is 700000002 sum : 7+0+0+0+0+0+0+0+2 =9 and its sum is multiple of 9
suppose you want to generate a no whose starting no is 712 then 712000008 sum=7+1+2+0+0+0+0+0+8=18
now find max no from database and add it


{
// XPCollection XPDomain = new XPCollection(ObjectSpace.Session);
//var a = XPDomain.Select(c => c.UniqueNo).Max();
int a;
select a= max(srno) from Table
int b = Convert.ToInt32(a);
GetUnique(b);
ObjectSpace.CommitChanges();
View.Refresh();
}


public void GetUnique(int MaxNo)
{
int PreviousNo = MaxNo;
for (int a = 0; a <= 1000; a++)
{

if (PreviousNo == 0)
{
DomainObject1 dm = new DomainObject1(ObjectSpace.Session);
dm.UniqueNo = "700000002";
PreviousNo = Convert.ToInt32(dm.UniqueNo);
dm.Save();
}
else
{
DomainObject1 dm = new DomainObject1(ObjectSpace.Session);
dm.UniqueNo =Convert.ToString (PreviousNo + 9);
PreviousNo = Convert.ToInt32(dm.UniqueNo);
dm.Save();
}
}

}

Generate random numbers who's sum is a pre-determined number in C#

Here we have gererated a 9 digit random number whose sum is multiple of 9
and starting no will be 6 and 7

public void GetUnique()
{
string b=Getval();
char[] a=b.tochararray()

int b1=0;
foreach(char v in a)
{
b1+=Convert.ToInt32(v);
}

if (b1%9==0)
{
print value;
}
else
GetUnique() ;

}

public string Getval()
{
Random r = new Random();
string b = String.Format
(
"{0}{1}{2}{3}{4}{5}{6}{7}{8}",
r.Next(6, 7),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9),
r.Next(0, 9)
);
return b;

}

Followers

Visitor No

click for free hit counter
Download a free hit counter here.