MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today*This is a Matlab adaptation of the* Knives and Knaves *logical puzzles*.

*You are in an island where all inhabitants are either* Knights, *who always tell the truth, or* Knaves, *who always lie. The island inhabitants can always tell Knights and Knaves apart by their appearance, but to you, as an outsider, they look exactly the same*.

Previous problem in this series: Knights and Knaves (part 1)

Next problem in this series: Knights and Knaves (part 3)

**Chapter 2**

After your initial encounter with two island inhabitants you follow the road to the castle. You were minding your own business when suddenly you find yourself surrounded by a small mob of dubious-looking islanders. Blissfully unaware of the latest mob-behavior theories, you decide it will be safe to stay if most of these islanders turn out to be friendly Knights, while you better start running if most of them turn out to be treacherous Knaves. What question(s) you could ask them to determine your best course of action? (note: you are always confronted by an odd number of islanders)

**Details**

You function will take a cell array of function handles as input (one element per islander), and must return *true* if you decide to run (if there are more Knaves than Knights) or *false* if you decide to stay (if there are more Knights than Knaves).

function run = solver(f)

You may ask each inhabitant a question by evaluating his associated function handle on a char string (the 'question'). Strings must be a valid matlab commands that when evaluated return a scalar logical value (yes/no questions, where *true* is a yes, and *false* is a no). Strings may refer to the following variables:

- A: an array (samel length as f) of logical values identifying each of the islanders as a Knight (true) or Knave (false)

**Asking questions, examples**:

x=f{3}('A(3)==true');

asks the third islander whether he is a Knight (note: this returns always *true*, since both Knights and Knaves would tell you they are Knights; remember, Knaves always lie)

x=f{1}('sum(A)>2');

asks the first islander whether there are more than two Knights in the group (not particularly useful by itself since we do not know whether he is going to respond truthfully or not)

19 correct solutions
8 incorrect solutions

Last solution submitted on Aug 14, 2013

1 player likes this solution

1 Comment