《算法》第五章部分程序 part 7

▶ 书中第五章部分程序,包括在加上自己补充的代码,字符串的二进制表示、十六进制表示、图形表示

● 二进制表示

 package package01;

 import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.BinaryStdIn; public class class01
{
private class01() {} public static void main(String[] args)
{
int bitPerLine = 16; // 默认每行显示 16 Bit
if (args.length == 1)
bitPerLine = Integer.parseInt(args[0]);
int count; // 统计输入的字符数
for (count = 0; !BinaryStdIn.isEmpty(); count++)
{
if (bitPerLine == 0)
{
BinaryStdIn.readBoolean();
continue;
}
if (count % bitPerLine == 0) // 显示够 bitPerLine 个 bit,换行
StdOut.println();
StdOut.print(BinaryStdIn.readBoolean() ? 1 : 0);// 读取一个 bit,分别显示 1 和 0
}
if (bitPerLine != 0)
StdOut.println();
StdOut.println(count + " Bits"); // 总字符数
}
}

● 十六进制表示

 package package01;

 import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.BinaryStdIn; public class class01
{
private class01() {} public static void main(String[] args)
{
int bytePerLine = 16; // 默认每行显示 16 Byte
if (args.length == 1)
bytePerLine = Integer.parseInt(args[0]);
int count;
for (count = 0; !BinaryStdIn.isEmpty(); count++)
{
if (bytePerLine == 0)
{
BinaryStdIn.readChar();
continue;
}
if (count % bytePerLine == 0)
StdOut.println();
else
StdOut.print(" ");
StdOut.printf("%02x", BinaryStdIn.readChar() & 0xff);
}
if (bytePerLine != 0)
StdOut.println();
StdOut.println(count + " Bytes");
}
}

● 图形表示

 package package01;

 import java.awt.Color;
import edu.princeton.cs.algs4.BinaryStdIn;
import edu.princeton.cs.algs4.Picture; public class class01
{
private class01() {} public static void main(String[] args)
{
int width = Integer.parseInt(args[0]), height = Integer.parseInt(args[1]); // 列数(Bit)和行数
Picture picture = new Picture(width, height); // 新建一张图
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if (!BinaryStdIn.isEmpty()) // 按照输入流填充依次图形
picture.set(col, row, BinaryStdIn.readBoolean() ? Color.BLACK : Color.WHITE);
else
picture.set(col, row, Color.RED); // 红色补齐没有元素的部分
}
}
picture.show();
}
}

■ 用图形显示《白鲸记》前 18 万字符

《算法》第五章部分程序 part 7

上一篇:Flume:sink.type=hive


下一篇:***Redis hash是一个string类型的field和value的映射表.它的添加、删除操作都是O(1)(平均)。hash特别适合用于存储对象