I was recently trying to complete a pretty good LeetCode exercise, and I can say that the solution I'm trying to use is not the best, but it's still been good practice. However, I noticed when using the Array.Exists function, I don't get consistent results as I'd expect when debugging with Console.WriteLine. Granted, I'm using this on a jagged array, but I would THINK that this would work, iterating on an array line by line. Considering the following example 2D array:
[[0,1],[0,1],[0,1]]
Given this array, you would THINK that when iterating through the array, you would be able to use Array.Exists to find that there IS, indeed, a 1 AND a 0 each subsequent sub-array, like when running these lines:
Console.WriteLine(Array.Exists<int>(grid[i], x => x.Equals(0)));
Console.WriteLine(Array.Exists<int>(grid[i], x => x.Equals(1)));
I would expect to return the following while looping through the array with i and j iterators:
True
True
However, when moving from the FIRST sub-array (grid[0] onto grid[1], for example), I would get false negatives, as if there was indeed no 1 in the array, which we know is false:
True
False
These should both be true in this jagged array, but apparently it's not, at least on the LeetCode website.
Is anyone else able to replicate this?
Here's a small program that shows the issue I'm talking about when run in a console application:
using System;
public class Solution {
public static void Main(String[] args) {
int[][] exampleGrid = new int[][]
{
new int[] {2,0},
new int[] {1,0}
};
Solution.Feedback(exampleGrid);
}
public static void Feedback(int[][] grid) {
for(int i = 0; i < grid.GetLength(0); i++)
{
Console.WriteLine(Array.Exists<int>(grid[i], x => x.Equals(0)));
Console.WriteLine(Array.Exists<int>(grid[i], x => x.Equals(1)));
}
}
}
Please note: this only appears to be reproducible in mono 5.18.0 - C# 7.
I can confirm it's definitely not a compiler bug of any sort, but the code itself. I was unable to replicate on Leetcode itself on their playground.
And then I discovered it was definitely a bug of my own. Go figure!
For those that wish to find my bug, give any input, or something different otherwise, feel free to go here:
https://leetcode.com/playground/PSz4zMzL
But this is not the scope of this post anymore - so I'll just move along.