Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!

Problem 1187. Knave in the middle attack

This is a Matlab adaptation of the Knives and Knaves logical puzzles, mixed with the famous man-in-the-middle attack in computer security.

You are in an island where all inhabitants are either Knights, who always tell the truth, or Knaves, who always lie. Your job is to sit in the middle of an islander and a second person interviewing the islander, intercepting all questions posed to the islander, and answering to the interviewer in a way that will make him think that the islander is the opposite type of what he really is (answer as a Knave if the islander is a Knight, or answer as a Knight if the islander is a Knave).


You are given a function handle F of an islander (either a Knight or a Knave, you do not know which). The function y=F(str) takes a string as input (the 'question'), and returns a logical value (the yes/no 'answer' this particular islander would give to this question). Valid questions are any valid matlab command. The islander has access to the following variables (his pool of 'knowledge'):

  • A: Islander's type: true for a Knight, false for a Knave
  • X: A secret formula only islanders know. A function on positive integer values that when evaluated returns a logical value.

Your function will receive as input a function handle of an islander, and a question. It should return the answer this same islander would give to this question if he was the opposite type than he really is. In other words:

 your_function(@Knight,str) should return Knave(str)
 your_function(@Knave,str) should return Knight(str)

Your function might query the function handle of the islander with whatever questions it sees fit before responding.


 your_function(@Knight,'A==true') == true;
 your_function(@Knave,'A==true') == true; 

This question asks whether the islander is a Knight; a Knave would respond true to this question, since he always lies.

 your_function(@Knight,'F(''A==true'')==true') == false; 
 your_function (@Knave,'F(''A==true'')==true') == true; 

This question asks if the islander would respond yes to the question of whether he is a Knight. A Knight would respond 'yes', while a Knave would (falsely) respond 'no'.

 your_function(@Knight,'X(3)~=X(2)') == true
 your_function(@Knave,'X(3)~=X(2)') == false 

(Assuming X(2)==X(3); you do not know the values of X, only islanders do)

Problem Group

Solution Statistics

8 correct solutions 20 incorrect solutions
Last solution submitted on Oct 12, 2015

Problem Comments