Difficulty: Medium · Puzzle 5 of 6 · Topic: Queue and Array Puzzles
Predict outputs of `first`, `next`, `num`, and `exists`.
module p5;
int aa[string];
string k;
bit ok;
initial begin
aa["b"] = 2;
aa["a"] = 1;
ok = aa.first(k);
$display("first_ok=%0d k=%s", ok, k);
ok = aa.next(k);
$display("next_ok=%0d k=%s", ok, k);
$display("num=%0d ex_c=%0d", aa.num(), aa.exists("c"));
end
endmoduleAssociative arrays iterate in index order, not insertion order.
1) Keys are `"a"` and `"b"`; lexical order gives `"a"` first.
2) `first(k)` returns 1 and sets k to `a`.
3) `next(k)` from `a` returns 1 and sets k to `b`.
4) `num()` is 2 and `exists("c")` is 0.Answer: first_ok=1 k=a, next_ok=1 k=b, num=2 ex_c=0
Checked by running the code in Verilator 5; the printed output supports the answer above. String keys iterate in lexical order; Icarus 13 does not support string-indexed associative arrays.
Associative arrays iterate in key order (strings compare lexicographically), not insertion order, and `next` on the last key returns 0 and leaves the key variable unchanged.
What does `aa.next(k)` return if called once more after `k=b`? Model answer: 0, because there is no next key, and `k` stays "b" (run).
I would remember that an associative array walks its keys in sorted order, not insertion order, and strings compare lexicographically. So first gives a, next gives b, there are two entries, and key c does not exist. The trap is that next on the last key returns 0 and leaves the key variable unchanged. I would check whether the code is wrongly relying on insertion order.