Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- static boolean[] alive;
- static int n;
- static int election(int helper){
- int i, j, temp=n;
- for(i = helper; i<n; i++){ //election from i
- if(!alive[i]) continue;
- System.out.println("\nELECTION from "+(i+1));
- for(j = i+1; j<n; j++){ //reply from j
- if(alive[j]){
- System.out.println("OK from "+ (j+1)+" to "+(i+1));
- temp = j;
- }
- else System.out.println("No reply from "+(j+1));
- }
- }
- if(temp<n) helper = temp;
- return helper;
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter the number of nodes: ");
- n = sc.nextInt();
- alive = new boolean[n];
- int i, j, helper = n;
- for(i = 0; i< n; i++)
- alive[i] = true;
- int coordinator = n-1;
- System.out.println("All nodes are made alive. "+(coordinator+1)+" is the coordinator.");
- boolean cont = true;
- while(cont){
- System.out.println("1.Crash 2.Respawn 3.Check status 4. Exit");
- switch(sc.nextInt()){
- case 1:
- System.out.print("Select a node to crash: ");
- int toCrash = sc.nextInt()-1;
- while(toCrash>=n||toCrash<0||!alive[toCrash]){
- System.out.print("Invalid input. Select a node to crash: ");
- toCrash = sc.nextInt()-1;
- }
- alive[toCrash] = false;
- System.out.println((toCrash+1)+" has crashed.");
- if(toCrash==coordinator) {
- System.out.print("Enter the node that finds out that " + (toCrash+1) + " is down: ");
- helper = sc.nextInt()-1;
- while (helper>=n||helper<0||!alive[helper]){
- System.out.print("Invalid input. Try again: ");
- helper = sc.nextInt()-1;
- }
- coordinator = election(helper);
- System.out.println((coordinator+1)+" is the coordinator.");
- }
- break;
- case 2:
- System.out.print("Select a node to respawn: ");
- int toRespawn = sc.nextInt()-1;
- while(toRespawn>=n||toRespawn<0||alive[toRespawn]) {
- System.out.println("Invalid input. Select a node to respawn: ");
- toRespawn = sc.nextInt() - 1;
- }
- alive[toRespawn] = true;
- System.out.println((toRespawn+1)+" is up and running.");
- coordinator = election(toRespawn);
- System.out.println((coordinator+1)+" is the coordinator.");
- break;
- case 3:
- for(i = 0; i< n; i++)
- if(alive[i]) System.out.println("Node "+(i+1)+": Alive");
- else System.out.println("Node "+(i+1)+": Dead");
- System.out.println((coordinator+1)+" is the coordinator.");
- break;
- case 4:
- cont = false;
- break;
- default: System.out.println("Invalid choice.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement