Get the Recurrence of Days Randomally

I faced a problem where I had to generate random picks in a week so that it  can include permutations of all days in a week, in every possible manner.

Computationally it creates following possibilities, plus one more fora none condition

P = 7C1 + 7C2 + 7C3 + 7c4 + 7C5 + 7C6 + 7C7
   = 7 + 21 + 35 + 35 + 21 + 7 + 1
   = 127

So 128 conditions including 1 none of all condition.

Where nCk is computed as   n!/((n-k)!*k!) or (n (n-1) (n-2) .... (n-k+1))/ (k (k-1) (k-2)........1)

So going by traditional programming it will take 128 if else conditions or switch cases to generate a random sample.

This will grow exponentially if the value of 'n' increases in case the requirement changes to some thing.

The following method returns a string of a possible random sample out of these 128 probabilities. Here days are marked as follows.

Sunday as 0
Monday as 1
Tuesday as 2
Wednesday as 3
Thursday as 4
Friday as 5
Saturday as 6

The output would come as a random value 0 or 0,7 or 0,1,7 and many more.

String getRecurrence() {
List<String> dayList=new ArrayList<String>();
dayList.add(0, "0");
dayList.add(1, "1");
dayList.add(2, "2");
dayList.add(3, "3");
dayList.add(4, "4");
dayList.add(5, "5");
dayList.add(6, "6");
int numofdays=(int) Math.floor(Math.random() * 8);
int indexCnt=7;
if(numofdays % 8==0)
return null;
String recurrence=null;
while(numofdays!=0){
int index=(int) Math.floor(Math.random() * (indexCnt));
recurrence=(recurrence==null?"":recurrence+",") +dayList.get(index);
dayList.remove(index);
numofdays--;
indexCnt--;
}
if(recurrence.length()>1){
String s[]=recurrence.split(",");
Arrays.sort(s);
recurrence=null;
for(String str:s){
recurrence=(recurrence==null?"":recurrence+",") +str;
}
}
return recurrence;
}

Comments

Popular posts from this blog

Delete horizontal, vertical and angled lines from an image using Python to clear noise and read text with minimum errors

Unordered JSON compare for differences using javascript

Java Currency Formatter Changing $ to ¤