Note that there are some explanatory texts on larger screens.

plurals
  1. POSearch method of Stack class always returning -1
    text
    copied!<p>I have this class to hold two values:</p> <pre><code>public class Coord { public int x; public int y; public Coord(int x, int y) { this.x = x; this.y = y; } } </code></pre> <p>I am trying to use it in a depth-first search algorithm:</p> <pre><code>x = this.move_to_x; y = this.move_to_y; Coord stack = new Coord(0, 0); Stack&lt;Coord&gt; start = new Stack&lt;Coord&gt;(); Stack&lt;Coord&gt; visited = new Stack&lt;Coord&gt;(); start.push(stack); visited.push(stack); while (!start.empty()) { Coord tmp = (Coord)start.pop(); int j,k; j = tmp.x; k = tmp.y; // there is only 8 possible ways to go (the neighbors) for (int a = -1; a &lt; 2; a++) { tmp.x = j + a; for (int b = -1; b &lt; 2; b++) { if (a == 0 &amp;&amp; b == 0) { continue; } tmp.y = k + b; if (tmp.x &lt; 0 || tmp.y &lt; 0) { continue; } if (tmp.x &gt; 5 || tmp.y &gt; 5) { continue; } if (tmp.x == x &amp;&amp; tmp.y == y) { System.out.println("end!"); return; } Coord push = new Coord(tmp.x, tmp.y); System.out.println("visited: " + visited); if (visited.search(push) == -1) { System.out.println("added x " + push.x + " y " + push.y + " " + visited.search(push)); start.push(push); visited.push(push); } else { System.out.println("visited x " + tmp.x + " y " + tmp.y + " index " + visited.search(push)); } } } } </code></pre> <p>The problem is that the <code>visited.search</code> method is always returning <code>-1</code>. Here is the log:</p> <pre><code>visited: [Agent.ExampleAgent.Coord@1af6a711] added x 0 y 1 -1 visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896] added x 1 y 0 -1 visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e] added x 1 y 1 -1 visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4] added x 0 y 0 -1 visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4, Agent.ExampleAgent.Coord@262f6be5] added x 0 y 1 -1 visited: [Agent.ExampleAgent.Coord@1af6a711, Agent.ExampleAgent.Coord@1c727896, Agent.ExampleAgent.Coord@5fbd8c6e, Agent.ExampleAgent.Coord@427a8ba4, Agent.ExampleAgent.Coord@262f6be5, Agent.ExampleAgent.Coord@199d4a86] </code></pre> <p>Note that the first element that is added to the visited stack is <code>(0,1)</code>, however when it is searched for <code>(0,1)</code>, later the method returns <code>-1</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload