100 doors problem


See On Github

Data

Contributor

Generic placeholder thumbnail

by kennyledet

in c

Tags

puzzle

Source Code

` H__PAGEZERO(__TEXT__text__TEXT__stubs__TEXT44__stub_helper__TEXT@$@__cstring__TEXTd.d__unwind_info__TEXTH__eh_frame__TEXT8__DATA__nl_symbol_ptr__DATA__got__DATA__la_symbol_ptr__DATAH__LINKEDIT  L"0  8@ (h h !	!P! /usr/lib/dyld!k	)5cd$	
	
*(8/usr/lib/libSystem.B.dylib& ) + @UHHHNHHEE}HuDžLLc(HcLDŽPLLHP{HPHPsH= H
#H!HDHΰH
H	HUH9щHH]fffff.UHH}E}ckE-E}c>HcUHu<@@DHcUHuEMMEE]UHHH}E}cXH=!H(H
&UHcuLEA<AEHDH°EEEH]fUHH}E}cYHcEHM</HEHcM*Q,1U	EEEEE$]Ð%%LAS%hhTest: %s
PassFailDoor #%d: %s
OpenClosed4444zRxPZ"R@___stack_chk_guardQr@dyld_stub_binderr@___stack_chk_failr @_printf__mh_execute_header0main4p9test_doors\ass_doorsRrint_doorsW<(libSystem.B
(05ASfn@ __mh_execute_header_main_pass_doors_print_doors_test_doors___stack_chk_fail___stack_chk_guard_printfdyld_stub_binder
/*
Kendrick Ledet 2014

There are 100 doors in a long hallway. They are all closed. The first time you walk by each door, you open it. 
The second time around, you close every second door (since they are all opened). 
On the third pass you stop at every third door and open it if it’s closed, close it if it’s open. 
On the fourth pass, you take action on every fourth door. You repeat this pattern for 100 passes.
*/
#include <math.h>
#include <stdio.h>
#include <stdbool.h>

void pass_doors(int[]);
bool test_doors(int[]);
void print_doors(int[]);

int main(int argc, char const *argv[])
{
    // Allocate array with 100 elements initialized to 0 to represent all doors being closed.
    int doors[100];
    for (int i = 0; i <= 99; ++i)
        doors[i] = 0;

    // Run algorithm
    pass_doors(doors);

    // Print out final door states
    print_doors(doors);

    // Test that all perfect square # doors are open
    printf("Test: %s\n", test_doors(doors) ? "Pass" : "Fail");

    return 0;
}

void pass_doors(int doors[])
{
    // Track the current pass number
    for (int pass_num = 1; pass_num <= 99; ++pass_num) {

        // Offset into hallway, by current pass number
        for (int i = pass_num-1; i <= 99; i += pass_num)
            doors[i] = doors[i] == 1 ? 0 : 1;  // close if open, open if close
    }
}

void print_doors(int doors[])
{
    /* Print out door statuses: "Open" if 1, "Closed" if 0 */
    for (int i = 0; i <= 99; ++i)
        printf("Door #%d: %s\n", i+1, doors[i] == 1 ? "Open" : "Closed");
}

bool test_doors(int doors[])
{
    for (int i = 0; i <= 99; ++i) {
        if ( doors[i] && (int) sqrt(doors[i]) % 1 != 0 )  // if door is open and door # is not a perfect square
            return false;
    }
    return true;
}
CFLAGS="-Wall -g"

clean:
	rm -f 100-Doors

all: 100-Doors

100-Doors:
	clang 100-Doors.c -o 100-Doors