Simple, Quality, Awesome Software

Reverse It!

Below is the complete code for the Reverse It! Try It Out! problem.

Two slightly different solutions are shown. The first is a simple version, the second adds color to the display and handles invalid input gracefully.

The Simple Version

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpBook.Examples.ReverseIt
{
    class Program
    {
        /// <summary>
        /// Runs the game from start to finish.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Generate teh array.
            int[] array = BuildArray();

            // Keep going until they get the array sorted.
            while (!IsArraySorted(array))
            {
                // Print the current state, ask for a number to reverse, and
                // make it so.
                PrintArray(array);
                int numberToReverse = GetNumberToReverse();
                ReverseIt(array, numberToReverse);
                Console.WriteLine();
            }

            // Print the end game.
            PrintArray(array);
            Console.WriteLine("Congratulations! You won!");
            Console.ReadKey();
        }

        /// <summary>
        /// Determines if the array is currently sorted or not.
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private static bool IsArraySorted(int[] array)
        {
            // You could also have done this with a fairly simple loop.
            if (array[0] != 1) { return false; }
            if (array[1] != 2) { return false; }
            if (array[2] != 3) { return false; }
            if (array[3] != 4) { return false; }
            if (array[4] != 5) { return false; }
            if (array[5] != 6) { return false; }
            if (array[6] != 7) { return false; }
            if (array[7] != 8) { return false; }
            if (array[8] != 9) { return false; }

            return true;
        }

        /// <summary>
        /// Does the work of reversing a part of the array. For any time
        /// that the amount is less than the full array (most of the time)
        /// the first part of the array is reversed, and the end is left
        /// alone.
        /// </summary>
        /// <param name="array"></param>
        /// <param name="numberToReverse"></param>
        private static void ReverseIt(int[] array, int numberToReverse)
        {
            int side1 = 0;
            int side2 = numberToReverse - 1;

            while (side1 < side2)
            {
                int temp = array[side1];
                array[side1] = array[side2];
                array[side2] = temp;

                side1++;
                side2--;
            }
        }

        /// <summary>
        /// Asks the user for an amount to reverse.
        /// </summary>
        /// <returns></returns>
        private static int GetNumberToReverse()
        {
            Console.Write("How many numbers do you want to reverse? ");
            string input = Console.ReadLine();
            int number = Convert.ToInt32(input);
            return number;
        }

        /// <summary>
        /// Prints the given array.
        /// </summary>
        /// <param name="array"></param>
        private static void PrintArray(int[] array)
        {
            for (int index = 0; index < array.Length; index++)
            {
                Console.Write(array[index] + " ");
            }

            Console.WriteLine();
        }

        /// <summary>
        /// Creates an array containing the numbers 1 through 9 in random
        /// order.
        /// </summary>
        /// <returns></returns>
        private static int[] BuildArray()
        {
            // We'll use a Random object to randomize things.
            Random random = new Random();

            // We'll use 0 as a placeholder to indicate that the spot
            // hasn't been filled yet.
            int[] numbers = new int[9] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            // Go through each number...
            for (int number = 1; number <= 9; number++)
            {
                int spot = random.Next(9);

                // Pick a random spot in the array...
                do
                {
                    spot = random.Next(9);
                } while (numbers[spot] != 0); // Repeat until you find one that's still 0.

                numbers[spot] = number;
            }

            return numbers;
        }
    }
}

The Advanced Version

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpBook.Examples.ReverseIt
{
    class Program
    {
        /// <summary>
        /// Runs the game from start to finish.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Generate teh array.
            int[] array = BuildArray();

            // Keep going until they get the array sorted.
            while (!IsArraySorted(array))
            {
                // Print the current state, ask for a number to reverse, and
                // make it so.
                PrintArray(array);
                int numberToReverse = GetNumberToReverse();
                ReverseIt(array, numberToReverse);
                Console.WriteLine();
            }

            // Print the end game.
            PrintArray(array);
            Console.WriteLine("Congratulations! You won!");
            Console.ReadKey();
        }

        /// <summary>
        /// Determines if the array is currently sorted or not.
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private static bool IsArraySorted(int[] array)
        {
            // You could also have done this with a fairly simple loop.
            if (array[0] != 1) { return false; }
            if (array[1] != 2) { return false; }
            if (array[2] != 3) { return false; }
            if (array[3] != 4) { return false; }
            if (array[4] != 5) { return false; }
            if (array[5] != 6) { return false; }
            if (array[6] != 7) { return false; }
            if (array[7] != 8) { return false; }
            if (array[8] != 9) { return false; }

            return true;
        }

        /// <summary>
        /// Does the work of reversing a part of the array. For any time
        /// that the amount is less than the full array (most of the time)
        /// the first part of the array is reversed, and the end is left
        /// alone.
        /// </summary>
        /// <param name="array"></param>
        /// <param name="numberToReverse"></param>
        private static void ReverseIt(int[] array, int numberToReverse)
        {
            int side1 = 0;
            int side2 = numberToReverse - 1;

            while (side1 < side2)
            {
                int temp = array[side1];
                array[side1] = array[side2];
                array[side2] = temp;

                side1++;
                side2--;
            }
        }

        /// <summary>
        /// Asks the user for an amount to reverse.
        /// </summary>
        /// <returns></returns>
        private static int GetNumberToReverse()
        {
            int number;

            // loop until you get a valid answer.
            while(true)
            {
                Console.Write("How many numbers do you want to reverse? ");
                string input = Console.ReadLine();
                bool successful = Int32.TryParse(input, out number);

                // If it parsed correctly and is in the right range...
                if (successful && number >= 0 && number <= 9)
                {
                    break;
                }
                else if (successful) // If it parsed correctly, but invalid.
                {
                    Console.WriteLine("Your number must be between 0 and 9.");
                }
                else // Didn't parse correctly.
                {
                    Console.WriteLine("You must enter a number.");
                }
            }

            return number;
        }

        /// <summary>
        /// Prints the given array.
        /// </summary>
        /// <param name="array"></param>
        private static void PrintArray(int[] array)
        {
            for (int index = 0; index < array.Length; index++)
            {
                if (array[index] == index + 1) { Console.ForegroundColor = ConsoleColor.Green; }
                else { Console.ForegroundColor = ConsoleColor.Red; }
                Console.Write(array[index] + " ");
            }

            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine();
        }

        /// <summary>
        /// Creates an array containing the numbers 1 through 9 in random
        /// order.
        /// </summary>
        /// <returns></returns>
        private static int[] BuildArray()
        {
            // We'll use a Random object to randomize things.
            Random random = new Random();

            // We'll use 0 as a placeholder to indicate that the spot
            // hasn't been filled yet.
            int[] numbers = new int[9] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            // Go through each number...
            for (int number = 1; number <= 9; number++)
            {
                int spot = random.Next(9);

                // Pick a random spot in the array...
                do
                {
                    spot = random.Next(9);
                } while (numbers[spot] != 0); // Repeat until you find one that's still 0.

                numbers[spot] = number;
            }

            return numbers;
        }
    }
}