There are precisely 9 portraits of 9 animals hanging on the wall of a museum. The animals are:
Bear, cat, dog, hamster, horse, lion, monkey, mouse, and tiger.
Precisely one animal is displayed on each of these portraits.
The portraits are displayed in terms of a 3x3 grid as follows:
A B C
+---+---+---+
1 | | | |
+---+---+---+
2 | | | |
+---+---+---+
3 | | | |
+---+---+---+
Where, each of A, B, and C represents the three columns, and each of 1, 2, and 3 denotes the three rows.
The following is known about the order of the portraits:
- Two of the portraits in each of Row-3 and Column-C have two animals that start with the same letter.
- The bear is in the same row as the hamster.
- The dog is in Cell 2A.
- The horse is in the same row as the monkey.
- The dog is NOT next to the tiger.
- The monkey is either above or below the dog
- Either the lion or the tiger is below the cat.
Determine the order of the portraits from the above-mentioned clues.
clearvars, clc
a={'bear','cat','dog','hamster','horse','lion','monkey','mouse','tiger'};
all=perms(a);
for i=1:length(all)
row= all(i,:) ;
wall=reshape(row,[3 3]);
r3=strcat(wall{3,1}(1),wall{3,2}(1),wall{3,3}(1));
c3=strcat(wall{1,3}(1),wall{2,3}(1),wall{3,3}(1));
if length(unique(r3))<3 && length(unique(c3))<3
if isequal(wall{2,1},'dog')
for r=1:3
for c=1:3
eval([wall{r,c} '=[' char(string(r)) ' ' char(string(c)) '];'])
end
end
if bear(1)==hamster(1) && horse(1)==monkey(1)
good=true;
if dog(1)==tiger(1) && abs(dog(2)-tiger(2))==1 ...
|| dog(2)==tiger(2) && abs(dog(1)-tiger(1))==1
good=false;
end
if good
if monkey(2)==dog(2) && abs(monkey(1)-dog(1))==1
if lion(2)==cat(2) && lion(1)==cat(1)+1 ...
|| tiger(2)==cat(2) && tiger(1)==cat(1)+1
disp(string(wall))
disp(' ')
end
end
end
end
end
end
end
finds
"bear" "cat" "hamster"
"dog" "lion" "tiger"
"monkey" "mouse" "horse"
>>
This program exercises many features of Matlab, so was a good practice in that language:
The perms() function, generating all the permutations of an array.
The reshape() function, converting a linear array into a 3x3 array.
The unique() function, converting, say, hmh (from hamster, monkey, horse), into hm, with the difference in size showing the presence of a duplicate initial.
The eval() function, used to create a variable with the name of the contents of a cell, to hold the coordinates of the cell containing that name. Here eval is more like exec(ute) to execute the command formed via a concatenated string.
And it examines all 9! = 362,880 permutations of the wall in 40 seconds.
|
Posted by Charlie
on 2022-04-21 08:55:19 |