1

If I have a jagged array set out like this:

[0][0]{128}
[0][1]{512}
[1][0]{64}

How would I get both the indexes of the number. So if I tried to get 64 I would get something like 0,1 indicating the index of the item. I tried using the Array.IndexOf() method but I get -1 as it isn't built for jagged arrays. Format of the output isn't important. It can be a string, two intergers, a byte array, anything.

1

1 Answer 1

2

Try this:

public static Tuple<int, int> IndexOf<T>(this T[][] jaggedArray, T value)
{
    for (int i = 0; i < jaggedArray.Length; i++)
    {
        T[] array = jaggedArray[i];
        for (int j = 0; j < array.Length; j++)
            if (array[j].Equals(value))
                return Tuple.Create(i, j);
    }
    return Tuple.Create(-1, -1);
}

You can use it as:

int[][] myArray = ...
Tupple<int, int> position = myArray.IndexOf(64);

Or for matrixes:

public static Tuple<int, int> IndexOf<T>(this T[,] matrix, T value)
{
    int width = matrix.GetLength(0); 
    int height = matrix.GetLength(1); 

    for (int x = 0; x < width; ++x)
        for (int y = 0; y < height; ++y)
            if (matrix[x, y].Equals(value))
                return Tuple.Create(x, y);

    return Tuple.Create(-1, -1);
}

You might still want to check for NULL values or NULL arrays, but that is up to you.

Sign up to request clarification or add additional context in comments.

2 Comments

Why are you copying this solution? stackoverflow.com/questions/3260935/…
I thought the same Pawel but the top solution he provided is different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.