Count Open Lockers

Problem:

Suppose you are in a hallway lined with 100 closed lockers. You begin by opening all 100 lockers. Next, you close every second locker. Then you go to every third locker and close it if it is open or open it if it is closed (call this toggling the locker). You continue toggling every nth locker on pass number n. After your hundredth pass of the hallway, in which you toggle only locker number 100, how many lockers are open?

In a hall with k lockers, how many lockers remain open after pass k?

 

Solution using C#:

 

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

namespace Lockers
{
    class Lockers
    {
        static void Main(string[] args)
        {
            try
            {
                //In a hall with n lockers, how many lockers remain open after pass n
                Console.Write("Enter number of lockers in the hall: ");
                int n = int.Parse(Console.ReadLine());
                int[] lockers = new int[n];
                int open = 0;
                for (int i = 1; i <= n; i++)//pass counter
                {
                    for (int j = i; j <= n; j = j + i)//locker counter
                    {
                        if (lockers[j – 1] == 0)
                        {
                            lockers[j – 1] = 1;
                        }
                        else
                        {
                            lockers[j – 1] = 0;
                        }
                    }
                    //display locker status after nth pass
                    for (int j = 1; j <= n; j++)
                    {
                        Console.Write(lockers[j – 1]);
                    }
                    Console.WriteLine();
                }
                //counting number of open lockers
                for (int i = 1; i <= n; i++)
                {
                    if (lockers[i – 1] == 1)
                    {
                        open++;
                    }
                }
                Console.WriteLine("Number of open lockers = " + open.ToString());
                //By using formula
                Console.WriteLine("Number of open lockers = " + Math.Floor(Math.Sqrt(n)));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
        }
    }
}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s