You are here: Foswiki>Main/Cimec Web>MarioStorti>SolvingPuzzleWithOctave (26 Mar 2020, MarioStorti)Edit Attach
On 2020-03-25 the following puzzle was posted on Twitter https://twitter.com/segregustavo/status/1242609081191407618?s=20

ET6iTklXgAEf65w.jpeg

The following Octave script solves the problem

## Solving puzzle 
## https://twitter.com/segregustavo/status/1242609081191407618?s=20
digits = [6,2,1,4,0];

## Number of correct entries (irrespective of position)
function n = correct1(z,zref);
  ## If all numbers are different then unique will return 6 elements
  ## If there is one repeated number then it will return 5, and so on
  n = 6-length(unique([z,zref]));
endfunction

## Number of correct entries (value and position)
function n = correct2(z,zref);
  ## Just compare element by element
  n = sum(z==zref);
endfunction

## Try all possible permutations. Just traverse all triplets and skip
## thos with repeated values
ndig = length(digits);
for k=1:ndig
  for l=1:ndig
    for m=1:ndig
      ## Skip repeated values
      if k==l || k==m || l==m; continue; endif
      z = [digits(k),digits(l),digits(m)];
      ## OK will end up true if the triplet is good, false if not
      OK = 1;

      ## Check consistency with first triplet 
      OK &= correct1(z,[6,8,2])==1;
      OK &= correct2(z,[6,8,2])==1;

      ## Check consistency with second triplet 
      OK &= correct1(z,[6,1,4])==1;
      OK &= correct2(z,[6,1,4])==0;

      ## Check consistency with third triplet 
      OK &= correct1(z,[2,0,6])==2;
      OK &= correct2(z,[2,0,6])==0;

      ## Check consistency with fourth triplet 
      OK &= correct1(z,[7,8,0])==1;
      OK &= correct2(z,[7,8,0])==0;

      ## If Z passed all tests then it is the good one
      ## If the code is OK we would get a single answer: [0,4,2]
      if OK; disp(z); endif
    endfor
  endfor
endfor
Topic revision: r1 - 26 Mar 2020, MarioStorti
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback