Advertisement
Guest User

part1

a guest
Apr 12th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 0.84 KB | None | 0 0
  1. -module(part1).
  2. -export([pass_candy/4]).
  3.  
  4. %% Pass candy until all students have equal values
  5. pass_candy(Turn, S1, S2, S3) ->
  6.     case check(S1,S2,S3) of
  7.         %% If they all have equal candy print the result
  8.         true ->
  9.             io:format("Turn:~B ",[Turn]),
  10.             io:format("S1:~B ",[S1]),
  11.             io:format("S2:~B ",[S2]),
  12.             io:format("S3:~B~n",[S3]);
  13.         %% If not, pass candy around according the rules
  14.         false ->
  15.             pass_candy(Turn+1, adjust(S3,S1), adjust(S1,S2), adjust(S2,S3))
  16.     end.
  17.  
  18. %% Adjust the candy
  19. adjust(Pas, Rec) ->
  20.     %% Passer gives half of their candy
  21.     Give = Pas div 2,
  22.     %% Receiver is reduced by half because they need to give
  23.     Temp = (Rec div 2) + Give,
  24.     %% If the end result is odd, add 1
  25.     case Temp rem 2 of
  26.         0 ->
  27.             Temp;
  28.         1 ->
  29.             Temp+1
  30.     end.
  31.    
  32. %% Check if they are all equal
  33. check(S1, S2, S3) ->
  34.     (S1==S2) andalso (S2==S3).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement