NavMenu

Monday, August 30, 2010

Working with Arrays: Array.IndexOf

In my Sudoku project, I'm working a lot with arrays and ArrayLists.  Searching an array for things like a value (e.g. a matching digit of 1-9) or an open spot (e.g. open tile in column) can be cumbersome.  At first I was for statements often.

But then I discovered Array.IndexOf.  The syntax is straightforward Array.IndexOf(arrayName, objectValueToSearchFor). It searches one-dimensional array, starting with the first element (i.e. 0, remember arrays are zero-based) and ending with the last element..  Each element is compared to the specified objectValueToSearchFor. If it finds it, it returns the first element location. 

Here's an example:

        #region "StoreEiliminatedDigit"
        /// <summary>
        /// Stores the digit parameter into the first available
        /// slot in the EliminatedDigits bucket array
        /// </summary>
        /// <param name="digit">Digit to store, valid range 1-9</param>
        /// <returns>Index where stored or -1 if the incoming digit
        /// was invalid or no open slots were available</returns>
        public int StoreEliminatedDigit(int digit)
        {
            int index = -1;

            if ((digit >= 1) && (digit <= 9))
            {
                int openSlot = Array.IndexOf(EliminatedDigits, 0);
                if (openSlot >= 0)
                {
                    EliminatedDigits[openSlot] = digit;
                    index = openSlot;
                }
            }

            return index;
        }
        #endregion

The same code above using a for statement would like this:


                for (int i = 0; i < EliminatedDigits.Length; i++)
                {
                    if (EliminatedDigits[i] == 0)
                    {
                        EliminatedDigits[i] = digit;
                        index = openSlot;
                    }
                }

Obviously looping through each of the array elements with the for statement is inefficient as compared to using the Array.IndexOf() method.

kick it on DotNetKicks.com

Shout it

No comments:

Post a Comment

About

My photo
Welcome to my blog! This blog is about my journey to become a Master .NET coder and teacher.

Followers