Door State Toggling Problem

There are 100 doors initially kept in closed state. One has to go through 100 iterations and in each iteration, he has to toggle a certain set of doors given by the rule below:

In ‘i’th numbered iteration, he has to toggle the doors i, 2i, 3i, 4i, .. n * i. where n * i <= 100 < (n + 1) * i. For instance, in 3rd iteration, doors to be toggled are 3, 6, 9 … 99.

By toggling, it means if the door is closed it has to be opened and if it is opened, it has to be closed.

Given that, question is after 100 iterations, which are all the doors would be in open state.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] door = new char[100];
            for (int i = 0; i < door.Length; i++)
            {
                door[i] = 'C';
            }
            Console.WriteLine("Initial state of the doors: ");
            for (int j = 0; j < 100; j++)
            {
                Console.Write(door[j]);
            }
            Console.WriteLine();
            Console.ReadLine();
            for (int i = 1; i <= 100; i++)
            {
                for (int j = i; j <= 100; j = j + i)
                {
                    if (door[j - 1] == 'C')
                    {
                        door[j - 1] = 'O';
                    }
                    else
                    {
                        door[j - 1] = 'C';
                    }
                }
                Console.WriteLine("State of the doors after toggling by person: " + i.ToString());
                for (int j = 0; j < 100; j++)
                {
                    Console.Write(door[j]);
                }
                Console.WriteLine();
                Console.ReadLine();
            }
        }
    }
}

Initial state of the doors:
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCC

State of the doors after toggling by person: 100
OCCOCCCCOCCCCCCOCCCCCCCCOCCCCCCCCCCOCCCCCCCCCCCCOCCCCCCCCCCCCCCOCCCCCCCCCCCCCCCC
OCCCCCCCCCCCCCCCCCCO

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