Difficulty: Easy · Puzzle 1 of 6 · Topic: Queue and Array Puzzles
Compute final `q`, `deleted`, and `da` after all operations. Work out each intermediate state yourself.
module p1;
int q[$] = '{1,2,3};
int da[] = '{10,20,30,40};
int deleted;
initial begin
q.push_front(9);
q.insert(2, 77);
deleted = q.pop_back();
q.delete(1);
da = new[2](da);
da = new[5](da);
$display("q=%p deleted=%0d da=%p", q, deleted, da);
end
endmodule`insert(i, x)` places x before index i; `delete(i)` removes only the element at index i and shifts the rest down. Dynamic-array `new[N](old)` copies only the prefix `min(old.size, N)`.
1) `push_front(9)` gives {9,1,2,3}; `insert(2,77)` puts 77 before index 2, giving {9,1,77,2,3}.
2) `pop_back()` removes and returns 3, leaving {9,1,77,2}.
3) `delete(1)` removes the element at index 1 (the value 1), giving {9,77,2}.
4) `new[2](da)` keeps the first two elements {10,20}; `new[5](da)` extends that truncated array with default-initialised slots: {10,20,0,0,0}.Answer: q holds 9, 77, 2; deleted=3; da holds 10, 20, 0, 0, 0 (the exact `%p` layout is tool-specific, for example '{9, 77, 2})
Checked by running the code in Icarus Verilog 13 and Verilator 5; the printed output supports the answer above. Elements printed one by one because Icarus cannot print a whole queue with %p. The %p layout (hex values, '{ } braces) is tool-specific; the values 9, 77, 2 and 10, 20, 0, 0, 0 are what matter.
`delete(1)` removes index 1, not the value 1 you just inserted next to, and the second `new[5](da)` cannot bring back 30 and 40 because the first resize already threw them away.
How can you preserve full original data before truncating a dynamic array? Model answer: copy it first (`saved = da;` for a dynamic array assignment copies by value) or resize into a different array (`other = new[2](da);`), so `da` itself is not overwritten.
I would apply each method in order and write the queue after every step. Push front and insert give 9, 1, 77, 2, 3, the pop back returns 3, and delete of index 1 removes the 1, leaving 9, 77, 2. For the dynamic array, the first resize keeps only 10 and 20, so the second resize adds three default zeros and the old 30 and 40 are gone. The trap is that delete takes an index, not a value, and that the resize is not undone. The exact print layout is tool specific, so I would check the contents and not the format.