软件渣渣真的要发愤图强啊,保完研的日子不能荒废,把学得渣一样的数据结构和算法重新捡起来,加油啦~
第一周的编程作业,在这里记录一下,Percolation
public class Percolation {
int[][]id;
int n;
public Percolation(int n)
{
// create n-by-n grid, with all sites blocked
id=new int[n][n];
this.n=n;
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
id[a][b]=0;
}
}
}
public void open(int i, int j){
// open site (row i, column j) if it is not open already
id[i-1][j-1]=1;
if(j<n&&i<n&&j>1&&i>1)
{
if((id[i-1][j]==2)||(id[i][j-1]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2))
{
id[i-1][j-1]=2;
}
}
else
{
if(i==1)
{
id[i-1][j-1]=2;
}
else if(j==1&&i<n&&((id[i-1][j]==2)||(id[i][j-1]==2)||(id[i-2][j-1]==2)))
{
id[i-1][j-1]=2;
}
else if(((j==n&&i<n)&&((id[i][j-1]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2)))||((i==n&&j<n&&j!=1)&&((id[i-1][j]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2))))
{
id[i-1][j-1]=2;
}
else if(((i==n&&j==n)&&((id[i-2][j-1]==2)||(id[i-1][j-2]==2))))
{
id[i-1][j-1]=2;
}
}
}
public boolean isOpen(int i, int j) {
// is site (row i, column j) open?
if(id[i-1][j-1]>0)
{
return true;
}
else{
return false;
}
}
public boolean isFull(int i, int j) {
// is site (row i, column j) full?
System.out.println(n);
System.out.println("i="+i+"j="+j);
if(id[i-1][j-1]==1)
{
if(j<n&&i<n&&j>1&&i>1)
{
if((id[i-1][j]==2)||(id[i][j-1]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2))
{
id[i-1][j-1]=2;
}
}
else
{
if(i==1)
{
id[i-1][j-1]=2;
}
else if(j==1&&i<n&&((id[i-1][j]==2)||(id[i][j-1]==2)||(id[i-2][j-1]==2)))
{
id[i-1][j-1]=2;
}
else if(((j==n&&i<n)&&((id[i][j-1]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2)))||((i==n&&j<n&&j!=1)&&((id[i-1][j]==2)||(id[i-2][j-1]==2)||(id[i-1][j-2]==2))))
{
id[i-1][j-1]=2;
}
else if(((i==n&&j==n)&&((id[i-2][j-1]==2)||(id[i-1][j-2]==2))))
{
id[i-1][j-1]=2;
}
else if(j==1&&i==n&&(id[i-2][j-1]==2||id[i-1][j]==2))
{
id[i-1][j-1]=2;
}
}
}
if(id[i-1][j-1]==2)
{
return true;
}
else{
return false;
}
}
public boolean percolates() {
// does the system percolate?
for(int a=0;a<n;a++)
{
if(id[n-1][a]==2)
{
return true;
}
}
return false;
}
}
ProcolationStats
public class PercolationStats {
double[] p;
int trials;
public PercolationStats(int n, int trials)
{
// perform trials independent experiments on an n-by-n grid
this.trials=trials;
p=new double[n];
for(int i=0;i<trials;i++)
{
Percolation p1=new Percolation(n);
int a=0;
while(true)
{
int x=StdRandom.uniform(n)+1;
int y=StdRandom.uniform(n)+1;
System.out.println(x+" "+y);
p1.open(x, y);
p1.isFull(x, y);
a++;
if(p1.percolates())
{
break;
}
}
p[i]=(a/n);
}
}
public double mean()
{
// sample mean of percolation threshold
return StdStats.mean(p);
}
public double stddev(){
// sample standard deviation of percolation threshold
return StdStats.stddev(p);
}
public double confidenceLo() {
// low endpoint of 95% confidence interval
return mean()-1.96*stddev()/trials;
}
public double confidenceHi() {
// high endpoint of 95% confidence interval
return mean()+1.96*stddev()/trials;
}
}
这一周主要是快速查找、归并查找,用树形结构存储,后来又提出根据树的大小归并进行优化,用数组存储树,很棒啊~