|
| 1 | +-module(doors_100). |
| 2 | +-compile(export_all). |
| 3 | +-import(lists). |
| 4 | + |
| 5 | +main() -> |
| 6 | + %% false represents a closed door & true represents an open door |
| 7 | + Doors = lists:duplicate(100, false), |
| 8 | + Result = toggle_doors( Doors, 0 ), |
| 9 | + io:format("Open doors:~n"), |
| 10 | + print_open_doors( Result, 1), |
| 11 | + OpenDoorsIndex = [ X*X || X <- lists:seq( 1, 10) ], |
| 12 | + TestPassed = test_open_doors( Result, 1, OpenDoorsIndex ), |
| 13 | + if TestPassed == true -> |
| 14 | + io:format("~nTest passed~n"); |
| 15 | + true -> |
| 16 | + io:format("~nTest failed~n") |
| 17 | + end. |
| 18 | + |
| 19 | +test_open_doors(_, 101, _) -> |
| 20 | + true; |
| 21 | + |
| 22 | +test_open_doors(Result, CurrentIndex, OpenDoorsIndex) -> |
| 23 | + IsAnOpenDoor = lists:member( CurrentIndex, OpenDoorsIndex ), |
| 24 | + %% index for nth should be >=1 |
| 25 | + Door = lists:nth( CurrentIndex, Result ), |
| 26 | + if IsAnOpenDoor == true -> |
| 27 | + if Door == true -> |
| 28 | + test_open_doors( Result, CurrentIndex + 1, OpenDoorsIndex ); |
| 29 | + true -> |
| 30 | + io:format("test failed for ~p~n", [CurrentIndex]), |
| 31 | + false |
| 32 | + end; |
| 33 | + true -> |
| 34 | + if Door == false -> |
| 35 | + test_open_doors( Result, CurrentIndex + 1, OpenDoorsIndex ); |
| 36 | + true -> |
| 37 | + io:format("test failed for ~s~n", [CurrentIndex]), |
| 38 | + false |
| 39 | + end |
| 40 | + end. |
| 41 | + |
| 42 | +print_list([], _) -> |
| 43 | + io:format("~n"); |
| 44 | +print_list([H|T], N) -> |
| 45 | + io:format("~p ", [H]), |
| 46 | + if (N rem 10) == 0 -> |
| 47 | + io:format("~n"), |
| 48 | + print_list(T, N+1); |
| 49 | + true -> |
| 50 | + print_list(T, N+1) |
| 51 | + end. |
| 52 | + |
| 53 | +print_open_doors([], _) -> |
| 54 | + io:format("~n"); |
| 55 | +print_open_doors([H|T], N) -> |
| 56 | + if H == true -> |
| 57 | + io:format("~p ",[N]), |
| 58 | + print_open_doors(T, N+1); |
| 59 | + true -> |
| 60 | + print_open_doors(T, N+1) |
| 61 | + end. |
| 62 | + |
| 63 | +toggle_doors( Doors, 100 ) -> Doors; |
| 64 | +toggle_doors( Doors, Turn) -> |
| 65 | + toggle_doors( toggle_doors_per_turn( Doors, 1, Turn), Turn + 1 ). |
| 66 | + |
| 67 | +toggle_doors_per_turn( Doors, Current, Turn ) -> |
| 68 | + if Current*(Turn+1) > 100 -> |
| 69 | + Doors; |
| 70 | + true -> |
| 71 | + ToggledDoors = lists:sublist( Doors, Current*(Turn + 1) - 1 ) ++ |
| 72 | + [ not lists:nth( Current*(Turn + 1) , Doors) ] ++ |
| 73 | + lists:sublist( Doors, Current*(Turn + 1) + 1, length( Doors ) - Current*(Turn + 1) + 1 ), |
| 74 | + toggle_doors_per_turn( ToggledDoors, Current + 1, Turn ) |
| 75 | + end. |
0 commit comments