SlideShare a Scribd company logo
1 of 6
Download to read offline
Will upvote asap******
Please help my code gives me incorrect values for heuristics in java:
This code should solve the 8 puzzle in java
Please do not use chatGPT and please run your code before sending it to me as I have gotten
multiple wrong answers
import sys
import heapq
import copy
class PriorityQueue():
def __init__(self):
self.thisQueue = []
def push(self, thisNode):
heapq.heappush(self.thisQueue, (thisNode.val, -thisNode.id, thisNode))
def pop(self):
return heapq.heappop(self.thisQueue)[2]
def isEmpty(self):
return len(self.thisQueue) == 0
def length(self):
return len(self.thisQueue)
class Set():
def __init__(self):
self.thisSet = set()
def add(self, entry):
if entry is not None:
self.thisSet.add(entry.__hash__())
def length(self):
return len(self.thisSet)
def isMember(self, query):
return query.__hash__() in self.thisSet
class Node():
def __init__(self, val, startstate, endstate, depth):
global nodeid
self.id = nodeid
nodeid += 1
self.val = val
self.state = startstate
self.endstate = endstate
self.depth = depth
depth+=1
def __str__(self):
return 'Node: id=%d val=%d' % (self.id, self.val)
def expand(current_node, closedlist, goal_state):
closedlist.add(current_node.state)
successors = []
up_child = current_node.state.up()
down_child = current_node.state.down()
right_child = current_node.state.right()
left_child = current_node.state.left()
children = [left_child, right_child, up_child, down_child]
for child in children:
if child is not None and not closedlist.isMember(child):
s = Node(0, child, None, current_node.depth + 1)
s.parent_node = current_node
if child == left_child:
s.action = "left"
elif child == right_child:
s.action = "right"
elif child == up_child:
s.action = "up"
elif child == down_child:
s.action = "down"
successors.append(s)
return successors
def h0(currenttiles, stiles):
misplaced = 0
for i in range(len(stiles)):
for j in range(len(currenttiles)):
if stiles[i][j] != currenttiles[i][j]:
misplaced += 1
return misplaced
def manhattan(currenttiles, stiles):
total = 0
for i in range(len(stiles)):
for j in range(len(currenttiles)):
if stiles[i][j] != currenttiles[i][j]:
y = stiles[i][j]
a = i
b = j
for k in range(len(stiles)):
for l in range(len(stiles)):
if currenttiles[k][l] == y:
d = k
e = l
count = (abs(d - a) + abs(e - b))
total += count
return total
class State():
def __init__(self):
self.xpos = 0
self.ypos = 0
self.tiles = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
def left(self):
if self.ypos == 0:
return None
s = self.copy()
s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos][s.ypos - 1]
s.ypos -= 1
s.tiles[s.xpos][s.ypos] = 0
return s
def right(self):
if self.ypos == 2:
return None
s = self.copy()
s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos][s.ypos + 1]
s.ypos += 1
s.tiles[s.xpos][s.ypos] = 0
return s
def up(self):
if self.xpos == 0:
return None
s = self.copy()
s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos - 1][s.ypos]
s.xpos -= 1
s.tiles[s.xpos][s.ypos] = 0
return s
def down(self):
if self.xpos == 2:
return None
s = self.copy()
s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos + 1][s.ypos]
s.xpos += 1
s.tiles[s.xpos][s.ypos] = 0
return s
def __hash__(self):
return (tuple(self.tiles[0]), tuple(self.tiles[1]), tuple(self.tiles[2]))
def __str__(self):
return '%d %d %dn%d %d %dn%d %d %dn' % (
self.tiles[0][0], self.tiles[0][1], self.tiles[0][2],
self.tiles[1][0], self.tiles[1][1], self.tiles[1][2],
self.tiles[2][0], self.tiles[2][1], self.tiles[2][2])
def copy(self):
s = State()
s.xpos = self.xpos
s.ypos = self.ypos
s.tiles = [row[:] for row in self.tiles]
return s
def astar(initial_state, goal_state, closedlist, heuristic_type):
initial_node = Node(0, initial_state, goal_state, 0)
frontier = PriorityQueue()
frontier.push(initial_node)
V = 0
N = 0
d = 0
while not frontier.isEmpty():
if frontier.length() > N:
N = frontier.length()
current_node = frontier.pop()
V += 1
if current_node.state.tiles == goal_state.tiles:
d = current_node.depth # Found the solution
return V, N,d
expanded = expand(current_node, closedlist, goal_state)
for node in expanded:
if heuristic_type == 0:
f_val = h0(node.state.tiles, goal_state.tiles) + node.depth
elif heuristic_type == 1:
f_val = manhattan(node.state.tiles, goal_state.tiles) + node.depth
# Add more heuristics as needed
node.val = f_val
frontier.push(node)
return None,d,V, N
def main():
global nodeid
nodeid = 0
if len(sys.argv) != 2:
print("Usage: python a-star.py ")
return
heuristic_type = int(sys.argv[1])
inputs = []
for line in sys.stdin:
inputs += line.split()
array = [
[int(inputs[0]), int(inputs[1]), int(inputs[2])],
[int(inputs[3]), int(inputs[4]), int(inputs[5])],
[int(inputs[6]), int(inputs[7]), int(inputs[8])]
]
goal_state = State()
goal_state.tiles = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
s = State()
current = State()
current.tiles = array
print(current.tiles)
s.tiles = [[1, 0, 2], [4, 3, 5], [6, 7, 8]]
printMan = manhattan(array, goal_state.tiles)
print("Initial State:")
print(current)
print("Goal State:")
print(goal_state)
print("Manhattan Distance:", printMan)
closedlist = Set()
nodeid = 0
V, N, d= astar(current, goal_state, closedlist, heuristic_type)
print("nHeuristic", heuristic_type)
print("Nodes Visited/Expanded (V):", V)
print("Maximum Nodes Stored in Memory (N):", N)
print("Depth of Optimal
Solution
(d):",d)
print(d)
if __name__ == "__main__":
main()

More Related Content

Similar to Will upvote asapPlease help my code gives me incorrect val.pdf

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Coding test review2
Coding test review2Coding test review2
Coding test review2SEMINARGROOT
 
Coding test review
Coding test reviewCoding test review
Coding test reviewKyuyongShin
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningBig_Data_Ukraine
 
Implemeting queue in python.pptx
Implemeting queue in python.pptxImplemeting queue in python.pptx
Implemeting queue in python.pptxKennyDon5
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfinfo706022
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009Jordan Baker
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M Ecfministries
 
Introduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from ScratchIntroduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from ScratchAhmed BESBES
 
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...Philip Schwarz
 
Retos de Programación en Python
Retos de Programación en PythonRetos de Programación en Python
Retos de Programación en PythonJavier Abadía
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AINAVER Engineering
 

Similar to Will upvote asapPlease help my code gives me incorrect val.pdf (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Coding test review2
Coding test review2Coding test review2
Coding test review2
 
Coding test review
Coding test reviewCoding test review
Coding test review
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Monadologie
MonadologieMonadologie
Monadologie
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Implemeting queue in python.pptx
Implemeting queue in python.pptxImplemeting queue in python.pptx
Implemeting queue in python.pptx
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdfpython3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
python3 HashTableSolutionmain.pyfrom ChainingHashTable impor.pdf
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M E
 
Introduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from ScratchIntroduction to Neural Networks and Deep Learning from Scratch
Introduction to Neural Networks and Deep Learning from Scratch
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...
 
Retos de Programación en Python
Retos de Programación en PythonRetos de Programación en Python
Retos de Programación en Python
 
Python Homework Sample
Python Homework SamplePython Homework Sample
Python Homework Sample
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI
 

More from sales223546

XML, XSDCreate an XML file that satisfies the following schema..pdf
XML, XSDCreate an XML file that satisfies the following schema..pdfXML, XSDCreate an XML file that satisfies the following schema..pdf
XML, XSDCreate an XML file that satisfies the following schema..pdfsales223546
 
Write the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfWrite the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfsales223546
 
Write ItemList.h and ItemList.cItemList is used to store a list .pdf
Write ItemList.h and ItemList.cItemList is used to store a list .pdfWrite ItemList.h and ItemList.cItemList is used to store a list .pdf
Write ItemList.h and ItemList.cItemList is used to store a list .pdfsales223546
 
Write a python script that will perform these operations procedurall.pdf
Write a python script that will perform these operations procedurall.pdfWrite a python script that will perform these operations procedurall.pdf
Write a python script that will perform these operations procedurall.pdfsales223546
 
Write a Python program that allows users to keep track of soccer pla.pdf
Write a Python program that allows users to keep track of soccer pla.pdfWrite a Python program that allows users to keep track of soccer pla.pdf
Write a Python program that allows users to keep track of soccer pla.pdfsales223546
 
Who started the apple organization What were they doing at the time.pdf
Who started the apple organization What were they doing at the time.pdfWho started the apple organization What were they doing at the time.pdf
Who started the apple organization What were they doing at the time.pdfsales223546
 
Which supervision conditions are pertinent to these sex offenders.pdf
Which supervision conditions are pertinent to these sex offenders.pdfWhich supervision conditions are pertinent to these sex offenders.pdf
Which supervision conditions are pertinent to these sex offenders.pdfsales223546
 
Which of the following is a form of market participation A. The South.pdf
Which of the following is a form of market participation A. The South.pdfWhich of the following is a form of market participation A. The South.pdf
Which of the following is a form of market participation A. The South.pdfsales223546
 
Which of the following is a form of market participation A) the.pdf
Which of the following is a form of market participation A) the.pdfWhich of the following is a form of market participation A) the.pdf
Which of the following is a form of market participation A) the.pdfsales223546
 
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdf
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdfWeek 6 Class Assessment Implementation Plan for an HRD Learning Int.pdf
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdfsales223546
 
Water restored in parts of Tshwane after two-day outagePretoria - .pdf
Water restored in parts of Tshwane after two-day outagePretoria - .pdfWater restored in parts of Tshwane after two-day outagePretoria - .pdf
Water restored in parts of Tshwane after two-day outagePretoria - .pdfsales223546
 
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdf
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdfVenture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdf
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdfsales223546
 
using draw.io You are tasked with designing a database for a Movie.pdf
using draw.io You are tasked with designing a database for a Movie.pdfusing draw.io You are tasked with designing a database for a Movie.pdf
using draw.io You are tasked with designing a database for a Movie.pdfsales223546
 
Using jQuery, set up functionality to capture the forms input eleme.pdf
Using jQuery, set up functionality to capture the forms input eleme.pdfUsing jQuery, set up functionality to capture the forms input eleme.pdf
Using jQuery, set up functionality to capture the forms input eleme.pdfsales223546
 
using draw.io Task 3 Design an ER Diagram for a Library Management .pdf
using draw.io Task 3 Design an ER Diagram for a Library Management .pdfusing draw.io Task 3 Design an ER Diagram for a Library Management .pdf
using draw.io Task 3 Design an ER Diagram for a Library Management .pdfsales223546
 
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdf
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdfusing draw.io Task 2 Design an ER Diagram for a Music Streaming.pdf
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdfsales223546
 
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdf
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdfUnixLinux 1. Use screen shots or video to demonstrate the before an.pdf
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdfsales223546
 
use python Problem 2. Selection Sort In this problem you will implem.pdf
use python Problem 2. Selection Sort In this problem you will implem.pdfuse python Problem 2. Selection Sort In this problem you will implem.pdf
use python Problem 2. Selection Sort In this problem you will implem.pdfsales223546
 
You are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfYou are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfsales223546
 

More from sales223546 (19)

XML, XSDCreate an XML file that satisfies the following schema..pdf
XML, XSDCreate an XML file that satisfies the following schema..pdfXML, XSDCreate an XML file that satisfies the following schema..pdf
XML, XSDCreate an XML file that satisfies the following schema..pdf
 
Write the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdfWrite the code in C, here is the template providedThe input used .pdf
Write the code in C, here is the template providedThe input used .pdf
 
Write ItemList.h and ItemList.cItemList is used to store a list .pdf
Write ItemList.h and ItemList.cItemList is used to store a list .pdfWrite ItemList.h and ItemList.cItemList is used to store a list .pdf
Write ItemList.h and ItemList.cItemList is used to store a list .pdf
 
Write a python script that will perform these operations procedurall.pdf
Write a python script that will perform these operations procedurall.pdfWrite a python script that will perform these operations procedurall.pdf
Write a python script that will perform these operations procedurall.pdf
 
Write a Python program that allows users to keep track of soccer pla.pdf
Write a Python program that allows users to keep track of soccer pla.pdfWrite a Python program that allows users to keep track of soccer pla.pdf
Write a Python program that allows users to keep track of soccer pla.pdf
 
Who started the apple organization What were they doing at the time.pdf
Who started the apple organization What were they doing at the time.pdfWho started the apple organization What were they doing at the time.pdf
Who started the apple organization What were they doing at the time.pdf
 
Which supervision conditions are pertinent to these sex offenders.pdf
Which supervision conditions are pertinent to these sex offenders.pdfWhich supervision conditions are pertinent to these sex offenders.pdf
Which supervision conditions are pertinent to these sex offenders.pdf
 
Which of the following is a form of market participation A. The South.pdf
Which of the following is a form of market participation A. The South.pdfWhich of the following is a form of market participation A. The South.pdf
Which of the following is a form of market participation A. The South.pdf
 
Which of the following is a form of market participation A) the.pdf
Which of the following is a form of market participation A) the.pdfWhich of the following is a form of market participation A) the.pdf
Which of the following is a form of market participation A) the.pdf
 
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdf
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdfWeek 6 Class Assessment Implementation Plan for an HRD Learning Int.pdf
Week 6 Class Assessment Implementation Plan for an HRD Learning Int.pdf
 
Water restored in parts of Tshwane after two-day outagePretoria - .pdf
Water restored in parts of Tshwane after two-day outagePretoria - .pdfWater restored in parts of Tshwane after two-day outagePretoria - .pdf
Water restored in parts of Tshwane after two-day outagePretoria - .pdf
 
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdf
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdfVenture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdf
Venture Investors Bet AI Can Improve Supply-Chain ManagementLogist.pdf
 
using draw.io You are tasked with designing a database for a Movie.pdf
using draw.io You are tasked with designing a database for a Movie.pdfusing draw.io You are tasked with designing a database for a Movie.pdf
using draw.io You are tasked with designing a database for a Movie.pdf
 
Using jQuery, set up functionality to capture the forms input eleme.pdf
Using jQuery, set up functionality to capture the forms input eleme.pdfUsing jQuery, set up functionality to capture the forms input eleme.pdf
Using jQuery, set up functionality to capture the forms input eleme.pdf
 
using draw.io Task 3 Design an ER Diagram for a Library Management .pdf
using draw.io Task 3 Design an ER Diagram for a Library Management .pdfusing draw.io Task 3 Design an ER Diagram for a Library Management .pdf
using draw.io Task 3 Design an ER Diagram for a Library Management .pdf
 
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdf
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdfusing draw.io Task 2 Design an ER Diagram for a Music Streaming.pdf
using draw.io Task 2 Design an ER Diagram for a Music Streaming.pdf
 
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdf
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdfUnixLinux 1. Use screen shots or video to demonstrate the before an.pdf
UnixLinux 1. Use screen shots or video to demonstrate the before an.pdf
 
use python Problem 2. Selection Sort In this problem you will implem.pdf
use python Problem 2. Selection Sort In this problem you will implem.pdfuse python Problem 2. Selection Sort In this problem you will implem.pdf
use python Problem 2. Selection Sort In this problem you will implem.pdf
 
You are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfYou are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdf
 

Recently uploaded

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 

Recently uploaded (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

Will upvote asapPlease help my code gives me incorrect val.pdf

  • 1. Will upvote asap****** Please help my code gives me incorrect values for heuristics in java: This code should solve the 8 puzzle in java Please do not use chatGPT and please run your code before sending it to me as I have gotten multiple wrong answers import sys import heapq import copy class PriorityQueue(): def __init__(self): self.thisQueue = [] def push(self, thisNode): heapq.heappush(self.thisQueue, (thisNode.val, -thisNode.id, thisNode)) def pop(self): return heapq.heappop(self.thisQueue)[2] def isEmpty(self): return len(self.thisQueue) == 0 def length(self): return len(self.thisQueue) class Set(): def __init__(self): self.thisSet = set() def add(self, entry): if entry is not None: self.thisSet.add(entry.__hash__()) def length(self): return len(self.thisSet) def isMember(self, query): return query.__hash__() in self.thisSet class Node(): def __init__(self, val, startstate, endstate, depth): global nodeid self.id = nodeid
  • 2. nodeid += 1 self.val = val self.state = startstate self.endstate = endstate self.depth = depth depth+=1 def __str__(self): return 'Node: id=%d val=%d' % (self.id, self.val) def expand(current_node, closedlist, goal_state): closedlist.add(current_node.state) successors = [] up_child = current_node.state.up() down_child = current_node.state.down() right_child = current_node.state.right() left_child = current_node.state.left() children = [left_child, right_child, up_child, down_child] for child in children: if child is not None and not closedlist.isMember(child): s = Node(0, child, None, current_node.depth + 1) s.parent_node = current_node if child == left_child: s.action = "left" elif child == right_child: s.action = "right" elif child == up_child: s.action = "up" elif child == down_child: s.action = "down" successors.append(s) return successors def h0(currenttiles, stiles): misplaced = 0 for i in range(len(stiles)): for j in range(len(currenttiles)): if stiles[i][j] != currenttiles[i][j]: misplaced += 1
  • 3. return misplaced def manhattan(currenttiles, stiles): total = 0 for i in range(len(stiles)): for j in range(len(currenttiles)): if stiles[i][j] != currenttiles[i][j]: y = stiles[i][j] a = i b = j for k in range(len(stiles)): for l in range(len(stiles)): if currenttiles[k][l] == y: d = k e = l count = (abs(d - a) + abs(e - b)) total += count return total class State(): def __init__(self): self.xpos = 0 self.ypos = 0 self.tiles = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] def left(self): if self.ypos == 0: return None s = self.copy() s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos][s.ypos - 1] s.ypos -= 1 s.tiles[s.xpos][s.ypos] = 0 return s def right(self): if self.ypos == 2: return None s = self.copy() s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos][s.ypos + 1] s.ypos += 1
  • 4. s.tiles[s.xpos][s.ypos] = 0 return s def up(self): if self.xpos == 0: return None s = self.copy() s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos - 1][s.ypos] s.xpos -= 1 s.tiles[s.xpos][s.ypos] = 0 return s def down(self): if self.xpos == 2: return None s = self.copy() s.tiles[s.xpos][s.ypos] = s.tiles[s.xpos + 1][s.ypos] s.xpos += 1 s.tiles[s.xpos][s.ypos] = 0 return s def __hash__(self): return (tuple(self.tiles[0]), tuple(self.tiles[1]), tuple(self.tiles[2])) def __str__(self): return '%d %d %dn%d %d %dn%d %d %dn' % ( self.tiles[0][0], self.tiles[0][1], self.tiles[0][2], self.tiles[1][0], self.tiles[1][1], self.tiles[1][2], self.tiles[2][0], self.tiles[2][1], self.tiles[2][2]) def copy(self): s = State() s.xpos = self.xpos s.ypos = self.ypos s.tiles = [row[:] for row in self.tiles] return s def astar(initial_state, goal_state, closedlist, heuristic_type): initial_node = Node(0, initial_state, goal_state, 0) frontier = PriorityQueue() frontier.push(initial_node) V = 0
  • 5. N = 0 d = 0 while not frontier.isEmpty(): if frontier.length() > N: N = frontier.length() current_node = frontier.pop() V += 1 if current_node.state.tiles == goal_state.tiles: d = current_node.depth # Found the solution return V, N,d expanded = expand(current_node, closedlist, goal_state) for node in expanded: if heuristic_type == 0: f_val = h0(node.state.tiles, goal_state.tiles) + node.depth elif heuristic_type == 1: f_val = manhattan(node.state.tiles, goal_state.tiles) + node.depth # Add more heuristics as needed node.val = f_val frontier.push(node) return None,d,V, N def main(): global nodeid nodeid = 0 if len(sys.argv) != 2: print("Usage: python a-star.py ") return heuristic_type = int(sys.argv[1]) inputs = [] for line in sys.stdin: inputs += line.split() array = [ [int(inputs[0]), int(inputs[1]), int(inputs[2])], [int(inputs[3]), int(inputs[4]), int(inputs[5])], [int(inputs[6]), int(inputs[7]), int(inputs[8])] ] goal_state = State()
  • 6. goal_state.tiles = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] s = State() current = State() current.tiles = array print(current.tiles) s.tiles = [[1, 0, 2], [4, 3, 5], [6, 7, 8]] printMan = manhattan(array, goal_state.tiles) print("Initial State:") print(current) print("Goal State:") print(goal_state) print("Manhattan Distance:", printMan) closedlist = Set() nodeid = 0 V, N, d= astar(current, goal_state, closedlist, heuristic_type) print("nHeuristic", heuristic_type) print("Nodes Visited/Expanded (V):", V) print("Maximum Nodes Stored in Memory (N):", N) print("Depth of Optimal Solution (d):",d) print(d) if __name__ == "__main__": main()