理解java中的布尔值!array[i]

发布于 2025-01-07 08:07:23 字数 372 浏览 2 评论 0原文

http://introcs.cs.princeton.edu/java/14array/CouponCollector .java.html

好的,据我了解,如果

boolean[] found = new boolean

未初始化,则为其分配默认的布尔值,即 false。但由于 false 的负数为 true (!found[val]),当所有布尔值都设置为默认值 (false) 时,此条件如何起作用?提前致谢。

http://introcs.cs.princeton.edu/java/14array/CouponCollector.java.html

Okay, so from what I understand, if

boolean[] found = new boolean

is not initialized, it is assigned with the default boolean value, which is false. But since the negatron of false is true (!found[val]), how is it that this condition works when all of the boolean values are set to default (false)? Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拥抱没勇气 2025-01-14 08:07:23

这里没有什么神秘的。我认为你只是没有仔细阅读代码。以下是相关片段及其“含义”。

    boolean[] found = new boolean[N];    // found[i] = true if card i has been collected

found 的所有元素最初都是 false。 (注释记录了 found 数组的不变量。)

    if (!found[val]) valcnt++;

如果 !found[val] 为 true(即 found[val] 为仍然为 false)增加计数器……

    found[val] = true;

并将 found[val] 设置为 true,这样我们就不会再次计算该 val。

There's no mystery here. I think you just didn't read the code carefully. Here are the relevant snippets and what they "mean".

    boolean[] found = new boolean[N];    // found[i] = true if card i has been collected

All elements of found are initially false. (The comment is documenting the invariant for the found array.)

    if (!found[val]) valcnt++;

If !found[val] is true (i.e. it found[val] is still false) increment the counter ...

    found[val] = true;

... and set found[val] to true so that we don't count this val again.

青丝拂面 2025-01-14 08:07:23

检查后,无论发生什么情况,found[val] 都会设置为 true。所以 if (!found[val]) 基本上意味着“如果我以前没有见过这个 val”。

最终结果是 valcnt 最终成为唯一 val 的计数。

After the check, regardless of what happens, found[val] is set to true. So if (!found[val]) basically means "if i haven't seen this val before".

The end result is that valcnt ends up being the count of unique vals.

一个人的旅程 2025-01-14 08:07:23

第一次有假。

int val = (int) (Math.random() * N);

这会生成一个随机数,因此在此循环中可能会生成多个随机数,例如五个。当第一次生成 5 时,found[5] 为 false,但第二次生成为 true,因此条件为 false,并且 valcnt++; 将不再达到。

There are false at first time.

int val = (int) (Math.random() * N);

this generates a random number so in this loop there may be generated more then one say fives. When 5 is generated at first time found[5] is false but in second time it's true so condition is false and valcnt++; won't be reached anymore.

浅暮の光 2025-01-14 08:07:23

因为 'val' 是 0 到 N-1 之间的随机整数。相同的值可能在 while 循环中出现两次,并且您只想更新在该索引处找到的内容一次。

Because 'val' is a random integer between 0 and N-1. The same value might occur twice in the while loop and you want to update found at that index only once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文