这是 Stack Overflow 第三周周报, 本周加入了 Python 的内容, 原计划两篇 Java, 两篇 Python. 但明天过节所以今天就先把周报发了, 两篇 Java, 一篇 Python. 公众号「渡码」为日更, 欢迎关注.
DAY1. 使用随机数打印 "hello world"
今天我们看一个有意思的例子, 看看下面的代码为什么每次运行都能输出 "hello world".
- public static String randomString(int i) {
- Random ran = new Random(i);
- StringBuilder sb = new StringBuilder();
- while (true) {
- int k = ran.nextInt(27);
- System.out.println(k);
- if (k == 0) {
- break;
- }
- sb.append((char)('`' + k));
- }
- return sb.toString();
- }
我们不禁会想, 生成随机数不是随机吗, 为什么每次运行结果都一样.
要解释这个问题, 我们需要了解 "伪随机" 的概念. 只要随机数是由确定的算法生成的, 那就是伪随机, 也就是说它的生成看似随机但是有一定规律的. 而 "真随机" 需要真实的随机事件取得, 所以计算机只能生成伪随机数.
知道了 "伪随机" 概念, 今天的例子就好解释了. 在之前的文章中我们看过生成随机数的代码, 是根据当前种子 (seed) 通过特定的规则 (算法) 生成随机数并更新种子, 因此 Random 生成的随机数是 "伪随机" 数. 此外我们都知道算法有个特性叫确定性, 也就是说相同的输入只能得出相同的输出. 对于生成随机数这个算法来说, 每次调用只要初始种子 (seed) 不变, 那么一定会生成相同的随机数. 这就解释了, 为什么每次执行生成的随机数序列都是一样的.
最后, 生成的 int 类型随机数 k, 通过 (char)('`' + k) 这行代码转成字符, 这里用到的是 ASCII 码相关的知识, 不再赘述.
今天通过这个简单的例子了解了伪随机的概念. 欢迎交流, 关注公众号每天分享一个知识点.
- class OuterClass {
- private static int a =10;
- class StaticNestedClass {
- }
- }
- // 用法
- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
- class OuterClass {
- private int a = 10;
- class InnerClass {
- }
- }
- // 用法
- OuterClass outerObject = new outerObject();
- OuterClass.InnerClass innerObject = outerObject.new InnerClass();
- def a():
- print("a executed")
- return []
- def b(x=a()):
- x.append(5)
- print(x)
- b()
- b()
- b()
- a executed
- [5]
- [5, 5]
- [5, 5, 5]
- fruits = ("apples", "bananas", "loganberries")
- def eat(food=fruits):
- print(food)
- def some_random_function():
- global fruits
- fruits = ("blueberries", "mangos")
- StringBuffer s = new StringBuffer("Hello World");
- Map<StringBuffer,Integer> counts = new HashMap<StringBuffer,Integer>();
- counts.put(s, 5);
- s.append("!!!!");
- for (Map.Entry<StringBuffer, Integer> entry : counts.entrySet()) {
- System.out.println(entry.getKey() + "\t" + entry.getValue());
- }
来源: https://www.cnblogs.com/duma/p/11509552.html