无法可视化鳕鱼问题代码的工作

时间:2020-11-04 11:03:09

标签: java c# loops stack codility

有人可以解释一下以下代码在每次迭代中如何工作吗?我已经从https://codesays.com/2014/solution-to-fish-by-codility/引用了此代码。但是我无法弄清楚每个循环条件如何工作。为了简化起见,我附上了到目前为止我已经理解的问题的图片表示。如果您可以提供进一步的帮助,将会很有帮助。红色圆圈代表鱼已被吃掉。绿色代表他们终于还活着。

public static int fish(int[] A, int[] B) {
  Stack<Integer> s = new Stack<Integer>();
  
  for(int i = 0; i < A.length; i++){
    int size    = A[i];
    int dir     = B[i];
    if(s.empty()){
      s.push(i);
    }
    else{
      while(!s.empty() && dir - B[s.peek()] == -1 && A[s.peek()] < size){
        s.pop();
      }
      if(!s.empty()){
        if(dir - B[s.peek()] != -1) s.push(i);
      }
      else{
        s.push(i);        
      }
    }
  }
  return s.size();
}

Pictorial Representation

During jdweng's debugging code execution

1 个答案:

答案 0 :(得分:0)

以下代码可帮助您进行调试:

        public static int fish(int[] A, int[] B)
        {
            StreamWriter writer = new StreamWriter("@c:\temp\test.log");
            Stack<int> s = new Stack<int>();

            for (int i = 0; i < A.Length; i++)
            {
                writer.WriteLine("A[] = '{0}', B[] = '{0}'", string.Join(",", A.Select(x => x.ToString()), A.Select(x => x.ToString()))); 
                int size = A[i];
                int dir = B[i];
                writer.WriteLine("I = '{0}', Size = '{1}', Dir = '{2}'", i, size, dir);
                if (s.Count() == 0)
                {
                    writer.WriteLine("Push : '{0}'", s.Peek()); 
                    s.Push(i);
                }
                else
                {
                    while (!(s.Count() == 0) && dir - B[s.Peek()] == -1 && A[s.Peek()] < size)
                    {
                        writer.WriteLine("Pop : '{0}'", s.Peek());
                        s.Pop();
                    }
                    if (s.Count() != 0)
                    {
                        writer.WriteLine("Count not zero, Dir = '{0}', B = '{1}', Value = '{2}', Peek = '{3}'", dir, B[s.Peek()] , dir - B[s.Peek()], s.Peek()); 
                        if (dir - B[s.Peek()] != -1) s.Push(i);
                    }
                    else
                    {
                        writer.WriteLine("Push : '{0}'", i);
                        s.Push(i);
                    }
                }
            }
            return s.Count();
        }