Created
November 7, 2021 11:40
-
-
Save muhammadihabk/bd7403847e54fed6132a4aaf44619c31 to your computer and use it in GitHub Desktop.
Three Jugs Problem
This file contains hidden or 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
# Input | |
alternativesList = [[]] | |
alternativesList[0] = list(map(int, input("Initial state: ").split())) | |
goal = list(map(int, input("Goal: ").split())) | |
# A flag to check if we could make a new alternative | |
# so that we can decide whether to append it to the alternativesList | |
newAlternative = False | |
# Try to reach the goal | |
def threeJugs(): | |
if alternativesList[0][0] == alternativesList[0][1] == 4: | |
return 0 | |
for alternative in alternativesList: | |
# Trying to swaping 8 place with 5 place | |
temp = alternative.copy() | |
temp = swap(0, 1, 5, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
# Trying to swaping 8 place with 3 place | |
temp = alternative.copy() | |
temp = swap(0, 2, 3, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
# Trying to swaping 5 place with 8 place | |
temp = alternative.copy() | |
temp = swap(1, 0, 8, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
# Trying to swaping 5 place with 3 place | |
temp = alternative.copy() | |
temp = swap(1, 2, 3, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
# Trying to swaping 3 place with 8 place | |
temp = alternative.copy() | |
temp = swap(2, 0, 8, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
# Trying to swaping 3 place with 5 place | |
temp = alternative.copy() | |
temp = swap(2, 1, 5, temp) | |
if temp == goal: | |
return alternativesList.index(temp) | |
return -1 | |
# Helper method | |
def swap(a, b, capacity, temp): | |
newAlternative = False | |
while temp[a] > 0 and temp[b] < capacity: | |
temp[a] -= 1 | |
temp[b] += 1 | |
newAlternative = True | |
if newAlternative and temp not in alternativesList: | |
alternativesList.append(temp) | |
if newAlternative: | |
return temp | |
else: | |
return [] | |
index = threeJugs() | |
if index != 1: | |
print("Goal is found at index:", index) | |
else: | |
print("Not found") | |
print("List of alternatives (no duplicates):") | |
for alternative in alternativesList: | |
print(alternative) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment