Last active
February 11, 2018 12:36
-
-
Save shintakezou/557a53da0440fd014a1403e3a9b77188 to your computer and use it in GitHub Desktop.
Bruteforcing towards the solution for "Quesito con la Susi n. 948" from an Italian magazine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
! Find the solution for the problem | |
! "Quesito con la Susi n. 948" | |
! from Italian magazine "La Settimana Enigmistica". | |
! Brute force, as usual. | |
! | |
! Find | |
! n = 3*y0 + y1 + y2 + y3 + y4 + y5 + y6 | |
! so that | |
! y(i) is between 4 and 10 included | |
! (hence n is between 36 and 90 included) | |
! y(i) /= y(j) if i /= j | |
! mod(n, 9) == 0 | |
! | |
! In the code, x = y(0) | |
! | |
! (The original problem is not stated this way, of course.) | |
program Susi948 | |
implicit none | |
integer, dimension(6) :: y | |
! We have seven symbols (4,5,6,7,8,9,10); | |
! once we pick y0, for the other six y1..y6 we have | |
! six accessible symbols, where order doesn't matter | |
! (because sum(y1..y6) will be the same); hence we | |
! have only 7 possible different n; but let's keep | |
! the dimension oversized. | |
integer, dimension(10) :: sols | |
integer :: x, n, i | |
sols = 0 | |
i = 1 | |
do x = 4, 10 | |
y = 4 ! = [4, 5, 6, 7, 8, 9] | |
do while (.not. all(y == 10)) | |
n = 3*x + sum(y) | |
if (mod(n, 9) == 0 & | |
.and. alldiff([x,y]) & | |
.and. all(sols(1:i-1) /= n)) then | |
print *, n | |
print *, x, x, x, y | |
sols(i) = n | |
i = i + 1 | |
end if | |
call nexty(y, 4, 11) | |
end do | |
end do | |
contains | |
! an iterative version would be better, but... | |
recursive subroutine nexty(y, z, b) | |
implicit none | |
integer, dimension(:), intent(inout) :: y | |
integer, intent(in) :: z, b | |
y(1) = y(1) + 1 | |
if (y(1) == b) then | |
y(1) = z; | |
if (size(y) > 1) then | |
call nexty(y(2:), z, b) | |
end if | |
end if | |
end subroutine nexty | |
function alldiff(y) | |
implicit none | |
logical :: alldiff | |
integer, dimension(:), intent(in) :: y | |
integer :: i | |
alldiff = .true. | |
do i = lbound(y,1), ubound(y,1) - 1 | |
alldiff = alldiff .and. all(y(i+1:ubound(y,1)) /= y(i)) | |
if (.not. alldiff) exit | |
end do | |
end function alldiff | |
end program Susi948 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment