Percolation Algorithm Java Implementation, Study notes of Algorithms and Programming

This java program implements the percolation algorithm, which is a probabilistic algorithm used to determine the connectivity of a two-dimensional grid. The algorithm simulates the filling of a grid with fluid, starting from the bottom-left corner, and checks for connectivity between adjacent sites. The program outputs the probability p of the fluid reaching the top of the grid after filling.

Typology: Study notes

2014/2015

Uploaded on 03/03/2015

Ayush.Agrawal
Ayush.Agrawal 🇮🇳

8 documents

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
import java.util.Scanner;
class Percolation
{
static int grid[];
public static int root(int i)
{
while(i!=grid[i])
{
grid[i]=grid[grid[i]];
i=grid[i];
}
return i;
}
public static boolean connected(int a,int b)
{
if(root(a)==root(b))
return true;
else
return false;
}
public static void union(int a,int b)
{
int root_a=root(a);
int root_b=root(b);
grid[root_a]=root_b;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the size of grid: ");
int n=in.nextInt();
grid=new int[n*n+2];
int count=1;
for(int i=1;i<n*n+1;i++)
grid[i]=count++;
final int n_sq=n*n;
final int last=n_sq+1;
grid[last]=last;
int num1,num2;
for(int i=1;i<n+1;i++)
{
union(i,0);
union(last-i,last);
pf2

Partial preview of the text

Download Percolation Algorithm Java Implementation and more Study notes Algorithms and Programming in PDF only on Docsity!

import java.util.Scanner;

class Percolation { static int grid[];

public static int root(int i) { while(i!=grid[i]) { grid[i]=grid[grid[i]]; i=grid[i]; } return i; }

public static boolean connected(int a,int b) { if(root(a)==root(b)) return true; else return false; } public static void union(int a,int b) { int root_a=root(a); int root_b=root(b);

grid[root_a]=root_b; }

public static void main(String args[]) { Scanner in=new Scanner(System.in); System.out.print("Enter the size of grid: "); int n=in.nextInt();

grid=new int[n*n+2]; int count=1;

for(int i=1;i<n*n+1;i++) grid[i]=count++;

final int n_sq=n*n; final int last=n_sq+1; grid[last]=last; int num1,num2;

for(int i=1;i<n+1;i++) { union(i,0); union(last-i,last);

double p=0.0;

int count2=0;

while(!connected(0,last)) { num1=(int)(Math.random()n_sq); num2=(int)(Math.random()n_sq); if(!connected(num1,num2)) { p++; union(num1,num2); } }

double ans=p/n_sq;

System.out.println("The value of p* obtained from the simulation is: "+ans);