lundi 18 mai 2020

I have written a code to find probability of repeating random numbers in an array over no. of iterations. How to improve efficiency of this code?

This code prints the probability of two people among a set of people(n) having their birthday on the same date over certain number of simulations or experiments. How to improve the efficiency of this code? Format of date is an integer (0 implies Jan 1 and 364 implies Dec 31)assuming that there are 365. Also, How to use random seed here? I am new to programming. I don't know what is seed. Please help me.

       package BirthdayProblem;
   import java.util.Scanner;
   import java.util.Random;
   import java.util.Map;
   import java.util.HashMap;

   public class Birthday
   {
   public static void main(String[] args)
   {
   Scanner scan = new Scanner(System.in);
   System.out.printf("Enter number of people: ");
   int n = scan.nextInt();
   System.out.printf("Enter number of simulations: ");
   int simulations = scan.nextInt();
   Random rand = new Random();

   int[] birthDay = new int[n];
   int i,j,positive=0;
   float probability;
   for(j=0;j<simulations;j++)
   {
       for(i=0;i<n;i++)
       {
           birthDay[i]=rand.nextInt(364);
       } 
       Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
       for(int x : birthDay)
       {
           if(!hm.containsKey(x))
           {
               hm.put(x,1);
           }
           else
           {
               hm.put(x,hm.get(x)+1);
           }
       }
       for(int x : hm.keySet())
       {
           if(hm.get(x)>1)
           {
               positive++;
               break;
           }
       }       
   }
   float p = positive;
   float k = simulations;
   probability = (p/k)*100;
   System.out.println(probability+"%");

   }
   }



Aucun commentaire:

Enregistrer un commentaire