Advertisement
Guest User

Car in box riddle

a guest
Jul 3rd, 2015
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.63 KB | None | 0 0
  1. #!/usr/local/bin/perl
  2. # Author: Longree (2015-07-03)
  3. # Computes answer to riddle: https://brilliant.org/problems/the-boxes/
  4. # ( if my logic below is correct )
  5.  
  6. use warnings;
  7. use strict;
  8.  
  9. # Box state matrix
  10. # [box1, box2, box3] (1 if object in box)
  11. my @boxstates = (
  12.         [1, 0, 0],
  13.         [0, 1, 0],
  14.         [0, 0, 1]
  15. );
  16.  
  17. # Test each box state
  18. my $viablecount = 0;
  19. for my $boxstate ( @boxstates )
  20. {
  21.         my $result = &runtest(@{$boxstate});
  22.         printf("[%s] - %s\n", join(":", @{$boxstate}),
  23.                 ($result eq 1) ? "Viable" : "Not viable");
  24.         $viablecount++ if ($result == 1);
  25. }
  26.  
  27. # Output Result
  28. if($viablecount < 1)
  29. {
  30.         print "None of the above :(\n";
  31. }
  32. elsif($viablecount == 1)
  33. {
  34.         print "One case exists! See above :)\n";
  35. }
  36. elsif(1 < $viablecount)
  37. {
  38.         print "Not enough information :(";
  39. }
  40.  
  41. exit 0;
  42.  
  43. # Run test for given set of box states
  44. sub runtest()
  45. {
  46.         my @boxstates = @_;
  47.  
  48.         my ($box1state, $box2state, $box3state) = @boxstates;
  49.  
  50.         my ($falsecount, $truecount) = (0, 0);
  51.  
  52.         &isinbox1($box1state) ? $truecount++ : $falsecount++;
  53.         &notinbox2($box2state) ? $truecount++ : $falsecount++;
  54.         &notinbox1($box1state) ? $truecount++ : $falsecount++;
  55.  
  56.         return (($falsecount == 2) && ($truecount == 1));
  57. }
  58.  
  59. # statements 1
  60. sub isinbox1()
  61. {
  62.         my $box1state = shift;
  63.  
  64.         return ($box1state == 1);
  65. }
  66.  
  67. # statement 2
  68. sub notinbox2()
  69. {
  70.         my $box2state = shift;
  71.  
  72.         return ($box2state == 0);
  73. }
  74.  
  75. # statement 3
  76. sub notinbox1()
  77. {
  78.         my $box1state = shift;
  79.  
  80.         return ($box1state == 0);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement