Bernoulli.java
public class Bernoulli
{
public static int binomial(int N, double p)
{
int heads = 0;
for (int i = 0; i < N; i++)
{
if (StdRandom.bernoulli(p))
{
heads++;
}
}
return heads;
}
public static int binomial(int N)
{
int heads = 0;
for (int i = 0; i < N; i++)
{
if (StdRandom.bernoulli(0.5))
{
heads++;
}
}
return heads;
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
StdDraw.setYscale(0, 0.2);
int[] freq = new int[N+1];
for (int t = 0; t < T; t++)
{
freq[binomial(N)]++;
}
double[] normalized = new double[N+1];
for (int i = 0; i <= N; i++)
{
normalized[i] = (double) freq[i] / T;
}
StdStats.plotBars(normalized);
double mean = N / 2.0;
double stddev = Math.sqrt(N) / 2.0;
double[] phi = new double[N+1];
for (int i = 0; i <= N; i++)
{
phi[i] = Gaussian.phi(i, mean, stddev);
}
StdStats.plotLines(phi);
}
}
Euclid.java
public class Euclid
{
public static int gcd(int p, int q)
{
if (q == 0) return p;
else return gcd(q, p % q);
}
public static int gcd2(int p, int q)
{
while (q != 0)
{
int temp = q;
q = p % q;
p = temp;
}
return p;
}
public static void main(String[] args)
{
int p = Integer.parseInt(args[0]);
int q = Integer.parseInt(args[1]);
int d = gcd(p, q);
int d2 = gcd2(p, q);
System.out.println("gcd(" + p + ", " + q + ") = " + d);
System.out.println("gcd(" + p + ", " + q + ") = " + d2);
}
}
TowersOfHanoi.java
public class TowersOfHanoi
{
public static void moves(int n, boolean left)
{
if (n == 0) return;
moves(n-1, !left);
if (left) System.out.println(n + " left");
else System.out.println(n + " right");
moves(n-1, !left);
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
moves(N, true);
}
}
No comments:
Post a Comment