In: Computer Science
Java question: A rumor spreads in the following way: a person picks at random another person to inform of the rumor. If that person hasn't already been informed of the rumor, that person starts spreading the rumor as well. If that person had already been informed of the rumor, neither person spreads this rumor any further. Starting with 999 people who don't know the rumor and one who does and starts spreading it (1000 people in total), write a class in Java named RumorSpreading that simulates this situation and then prints the final percentage of the population that ends up knowing the rumor. Assume that we do NOT consider the case where more than one person spreads the rumor simultaneously.
Here's the solution to the given problem. I have added comments so that it's easier for you to understand. Keep learning :)
RumorSpreader.java:
import java.util.Random;
public class RumorSpreader {
static Random rd = new Random();
public static int generateRandomOtherThanSelf(int x)
{
int random =
rd.nextInt(1000);
while(random==x)
random =
rd.nextInt(1000);
return random;
}
public static void main(String[] args) {
int arr[] = new int[1000];
arr[0] = 1;
int next,i;
while(true) {
int flag =
0;
// Iterate
through all the people
// State 0
denotes that the person doesn't know the rumor.
// State 1
denotes that the person knows the rumor and can spread it.
// State 2
denotes that the person knows the rumor and can't spread it.
for (i=0;
i<1000; i++) {
// If anyone knows the rumor, spread it to a
random person
if(arr[i] == 1) {
// flag 1 denotes that we
found a person who can spread the rumor.
flag = 1;
next =
generateRandomOtherThanSelf(arr[i]);
// If the next person didnt
know the rumor already, he'll spread further
if(arr[next] == 0) {
arr[next]
= 1;
}
// If the next person knew
the rumor already,
// both next nd current will
stop participating in spreading the rumour futher
else if(arr[next] == 1)
{
arr[next]
= 2;
arr[i] =
2;
}
break;
}
}
// If we didnt
find any person, who can spread the rumor, break
if(flag==0)
break;
}
// Finally, count the number of
people who know the rumor
int count=0;
for (i=0; i<1000; i++) {
if(arr[i] !=
0)
count++;
}
System.out.println("Percentage of
people knowing the rumor: " + ((double)count/1000) * 100);
}
}
Output: