Here is the original link
- ShannonEntropy.java(香农熵,信息论的重要基础)
public class ShannonEntropy
{
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
int amount = 0;
int[] count = new int[m + 1];
double H = 0.0;
while (!StdIn.isEmpty())
{
int x = StdIn.readInt();
count[x]++;
amount++;
}
for (int i = 1; i <= m; i++)
{
if (count[i] == 0) continue;
H -= (Math.log(count[i] * 1.0 / amount) / Math.log(2)) * count[i] / amount;
}
StdOut.printf("%.4f\n", H);
}
}
- Checkerboard.java (调用StdDraw库绘制)
public class Checkerboard
{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
StdDraw.setScale(0, n);
boolean isBlue = true;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
if (isBlue)
{
StdDraw.setPenColor(StdDraw.BLUE);
}
else
{
StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
}
StdDraw.filledSquare(.5 + i, .5 + j, 0.5);
isBlue = !isBlue;
}
if (n % 2 == 0)
{
isBlue = !isBlue;
}
}
}
}
这里是绘制国际象棋棋盘,如图
- WorldMap.java(调用StdDraw库绘制)
public class WorldMap
{
public static void main(String[] args) {
int width = StdIn.readInt();
int height = StdIn.readInt();
StdDraw.setCanvasSize(width, height);
StdDraw.setXscale(0, width);
StdDraw.setYscale(0, height);
while (!StdIn.isEmpty())
{
String region = StdIn.readString();
int vertices = StdIn.readInt();
double[] x = new double[vertices];
double[] y = new double[vertices];
for (int i = 0; i < vertices; i++)
{
x[i] = StdIn.readDouble();
y[i] = StdIn.readDouble();
}
StdDraw.polygon(x, y);
}
}
}
这里是绘制美国地图,如图