There is a puzzle:

On the window curtain with a checkered pattern, 9 flies sat down. By chance, they settled in such a way that no two flies were in the same row - neither direct nor oblique (Fig.)

enter image description here

Task:
After a few minutes, three flies changed places and crawled into neighboring, unoccupied cells; the remaining 6 did not move. But it’s funny: although three flies moved to other places, all 9 were again placed so that no pair was in the same straight or oblique row. Can you tell which three flies and where they moved to?

Answer: a6-> b6, b3-> a4, d4-> d3

Obviously, the task is based on the eight queens problem. In our case, it turns into a problem about 9 flies. I implemented on 9 flies, but with the withdrawal of all possible arrangements. I need to improve this program, so that there would be a choice of 3 flies and check their permutations on neighboring cells and the output of the resulting answer. Do you have any ideas?


I add the decision which I implemented. Here is the search for all the answers, and not on the task. I would like to get an answer only to the puzzle, without finding all the solutions. Specifically, it does not work for me. I present two solutions: either make the full implementation of the search for exactly 3 flies, or sort the results from which to select exactly these 3 flies and bring out. Can you help to do this?

myhi([]). % когда список пуст - решение найдено myhi([ Row/Col | Rest]) :- % в противном случае для каждой строки myhi(Rest), % помещаем муху в каждую высокую строку member(Col, [1,2,3,4,5,6,7,8,9]), % и выбираем одну из возможных позиций столбца safe( Row/Col, Rest). % смотрим безопасная ли позиция, если нет, % возвращаемся назад и пробуем другую safe(Anything, []). % пустая занавеска всегда безопасная safe(Row/Col, [Row1/Col1 | Rest]) :- % проверяем строку Col =\= Col1, % проверяем столбец Col1 - Col =\= Row1 - Row, % проверяем диагональ Col1 - Col =\= Row - Row1, safe(Row/Col, Rest). % если всё нормально, пробуем подставить member(X, [X | Tail]). member(X, [Head | Tail]) :- member(X, Tail). myhi([1/R9, 2/R8, 3/R7, 4/R6, 5/R5, 6/R4, 7/R3, 8/R2, 9/R1]),write([1/R9, 2/R8, 3/R7, 4/R6, 5/R5, 6/R4, 7/R3, 8/R2, 9/R1]),nl,fail. 
  • Give the code of your program, describe what exactly you can not. PS And here, rather than a forum, but a knowledge base, that is, your question and the answers to it should be of benefit to others. - Kromster
  • I have provided my decision below. Did I do everything right? - Kilian Martin
  • SWI-Prolog has built-in (library) member/2 predicate - Anton Danilov

0