Amazon Interview Question
SDE1sCountry: United States
Interview Type: Written Test
Good one(+1 for you) and reason I see is that perfect square has odd number of factors. Since the doors were all initially closed, an even number of factors for a given door number closes it and the odd number of factors opens it.
Code to demonstrate what Vic said:
public class Doors {
public static void main(String[] args) {
boolean[] doors = new boolean[101];
for (int i = 0; i < doors.length; ++i) doors[i] = false;
for (int iteration = 1; iteration <= 100; ++iteration)
for (int i = 1; iteration * i < doors.length; ++i)
doors[iteration * i] = !doors[iteration * i];
for (int i = 1; i <= 100; i++)
System.out.println("door " + i + " is " + (doors[i] ? "open" : "closed"));
}
}
done!
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <string.h>
#define OPEN 1
#define CLOSE 0
int main()
{
int doors[100];
int *d,i,m;
d=&doors[0];
for(i=0;i<99;i++)
doors[i]=CLOSE;
printf("Entered data");
int inc=0,j=0;
for(inc=1;inc<100;inc++)
{
m=100/inc;
for(j=0;j<m;j++)
{
d=d+inc;
if(*d==OPEN)
{
*d=CLOSE;
}
else{*d=OPEN;}
}
d=&doors[0];
}
for(i=0;i<100;i++)
{
if(doors[i]==OPEN)
{
printf("\t %d",i);
}
}
}
//enjoyy
void door_open(int a[])
{
int i;
int a[100];
/* initialising array to 100 numbers */
for(i=1;i<=100;i++)
a[i]=i;
/* here it will toggle 2,3,4..... till 100 */
int cnt=2;
while(cnt!=100)
{
for(i=cnt;i<100;i=i+cnt)
a[i]=0;
}
/*printing all doors opened */
for(i=1;i<100;i++)
printf("%d\t",a[i]);
}
1 4 9 16 25 36 49 64 81 100
#include <stdio.h>
int main () {
int door[100];
int i = 0; //0 - close, 1 - Open
int j;
for (i=1; i <= 100; i++) {
door[i] = 1;
}
j = 2;
do {
for (i=j; i <= 100; i ++ ) {
if (i%j == 0) {
door[i] = ~door[i];
}
}
j ++;
} while (j <= 100);
for (i = 1; i <= 100; i ++ ) {
if (door[i] == 1) {
printf("%d ", i);
}
}
}
public static void printDoorsOpenedOrClosed(int passes)
{
HashMap<Integer, Boolean> doors=new HashMap<Integer, Boolean>();
int i = 0;
//Open all doors as default in the start
while(i < passes)
{
doors.put(i, false);
i++;
}
for(int j = 1; j <= passes; j++)
{
for(int k = j - 1; k < passes; k += j)
doors.put(k, !(doors.get(k)));
}
for(int l = 0; l < passes; l++)
{
System.out.println("The door number "+(l + 1)+" is "+(doors.get(l) == true ? "Opened" : "Closed"));
}
}
close=1,open=0;
initial state is 1 1 1 1 1 1...
after first toggle
:-0 0 0 0 0.....
after second toggle(toggle every second element)
:-0 1 0 1 0....
after third toggle
:-0 1 1 0 0....
after fourth toggle
:-0 1 1 1 0...
after fifth toggle
:-0 1 1 1 1
if we do so the answer would be, one gate left after all(100) the iterations.
doors with numbers 1, 4, 9 ...
- Vin June 26, 2013Basically door numbers which is a perfect square is the answer.